mirror of
https://github.com/ItzCrazyKns/Perplexica.git
synced 2025-06-25 11:18:43 +00:00
Compare commits
3 Commits
develop/v1
...
8607dc0718
Author | SHA1 | Date | |
---|---|---|---|
8607dc0718 | |||
78cf3f9d5f | |||
7844ca9343 |
4
.gitignore
vendored
4
.gitignore
vendored
@ -2,7 +2,6 @@
|
||||
node_modules/
|
||||
npm-debug.log
|
||||
yarn-error.log
|
||||
package-lock.json
|
||||
|
||||
# Build output
|
||||
/.next/
|
||||
@ -38,6 +37,3 @@ Thumbs.db
|
||||
# Db
|
||||
db.sqlite
|
||||
/searxng
|
||||
|
||||
# Dev
|
||||
docker-compose-dev.yaml
|
||||
|
@ -2,6 +2,7 @@
|
||||
|
||||
[](https://discord.gg/26aArMy8tT)
|
||||
|
||||
|
||||

|
||||
|
||||
## Table of Contents <!-- omit in toc -->
|
||||
@ -43,7 +44,7 @@ Want to know more about its architecture and how it works? You can read it [here
|
||||
- **Normal Mode:** Processes your query and performs a web search.
|
||||
- **Focus Modes:** Special modes to better answer specific types of questions. Perplexica currently has 6 focus modes:
|
||||
- **All Mode:** Searches the entire web to find the best results.
|
||||
- **Writing Assistant Mode:** Helpful for writing tasks that do not require searching the web.
|
||||
- **Writing Assistant Mode:** Helpful for writing tasks that does not require searching the web.
|
||||
- **Academic Search Mode:** Finds articles and papers, ideal for academic research.
|
||||
- **YouTube Search Mode:** Finds YouTube videos based on the search query.
|
||||
- **Wolfram Alpha Search Mode:** Answers queries that need calculations or data analysis using Wolfram Alpha.
|
||||
@ -142,7 +143,6 @@ You can access Perplexica over your home network by following our networking gui
|
||||
|
||||
## One-Click Deployment
|
||||
|
||||
[](https://usw.sealos.io/?openapp=system-template%3FtemplateName%3Dperplexica)
|
||||
[](https://repocloud.io/details/?app_id=267)
|
||||
|
||||
## Upcoming Features
|
||||
|
@ -4,7 +4,7 @@ services:
|
||||
volumes:
|
||||
- ./searxng:/etc/searxng:rw
|
||||
ports:
|
||||
- '4000:8080'
|
||||
- 4000:8080
|
||||
networks:
|
||||
- perplexica-network
|
||||
restart: unless-stopped
|
||||
@ -19,7 +19,7 @@ services:
|
||||
depends_on:
|
||||
- searxng
|
||||
ports:
|
||||
- '3001:3001'
|
||||
- 3001:3001
|
||||
volumes:
|
||||
- backend-dbstore:/home/perplexica/data
|
||||
- uploads:/home/perplexica/uploads
|
||||
@ -41,7 +41,7 @@ services:
|
||||
depends_on:
|
||||
- perplexica-backend
|
||||
ports:
|
||||
- '3000:3000'
|
||||
- 3000:3000
|
||||
networks:
|
||||
- perplexica-network
|
||||
restart: unless-stopped
|
||||
|
@ -7,43 +7,34 @@ To update Perplexica to the latest version, follow these steps:
|
||||
1. Clone the latest version of Perplexica from GitHub:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/ItzCrazyKns/Perplexica.git
|
||||
git clone https://github.com/ItzCrazyKns/Perplexica.git
|
||||
```
|
||||
|
||||
2. Navigate to the project directory.
|
||||
2. Navigate to the Project Directory.
|
||||
|
||||
3. Check for changes in the configuration files. If the `sample.config.toml` file contains new fields, delete your existing `config.toml` file, rename `sample.config.toml` to `config.toml`, and update the configuration accordingly.
|
||||
|
||||
4. Pull the latest images from the registry.
|
||||
3. Pull latest images from registry.
|
||||
|
||||
```bash
|
||||
docker compose pull
|
||||
```
|
||||
|
||||
5. Update and recreate the containers.
|
||||
4. Update and Recreate containers.
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
6. Once the command completes, go to http://localhost:3000 and verify the latest changes.
|
||||
5. Once the command completes running go to http://localhost:3000 and verify the latest changes.
|
||||
|
||||
## For non-Docker users
|
||||
## For non Docker users
|
||||
|
||||
1. Clone the latest version of Perplexica from GitHub:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/ItzCrazyKns/Perplexica.git
|
||||
git clone https://github.com/ItzCrazyKns/Perplexica.git
|
||||
```
|
||||
|
||||
2. Navigate to the project directory.
|
||||
|
||||
3. Check for changes in the configuration files. If the `sample.config.toml` file contains new fields, delete your existing `config.toml` file, rename `sample.config.toml` to `config.toml`, and update the configuration accordingly.
|
||||
|
||||
4. Execute `npm i` in both the `ui` folder and the root directory.
|
||||
|
||||
5. Once the packages are updated, execute `npm run build` in both the `ui` folder and the root directory.
|
||||
|
||||
6. Finally, start both the frontend and the backend by running `npm run start` in both the `ui` folder and the root directory.
|
||||
|
||||
---
|
||||
2. Navigate to the Project Directory
|
||||
3. Execute `npm i` in both the `ui` folder and the root directory.
|
||||
4. Once packages are updated, execute `npm run build` in both the `ui` folder and the root directory.
|
||||
5. Finally, start both the frontend and the backend by running `npm run start` in both the `ui` folder and the root directory.
|
||||
|
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "perplexica-backend",
|
||||
"version": "1.10.0-rc3",
|
||||
"version": "1.10.0-rc2",
|
||||
"license": "MIT",
|
||||
"author": "ItzCrazyKns",
|
||||
"scripts": {
|
||||
@ -30,8 +30,8 @@
|
||||
"@iarna/toml": "^2.2.5",
|
||||
"@langchain/anthropic": "^0.2.3",
|
||||
"@langchain/community": "^0.2.16",
|
||||
"@langchain/google-genai": "^0.0.23",
|
||||
"@langchain/openai": "^0.0.25",
|
||||
"@langchain/google-genai": "^0.0.23",
|
||||
"@xenova/transformers": "^2.17.1",
|
||||
"axios": "^1.6.8",
|
||||
"better-sqlite3": "^11.0.0",
|
||||
|
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,45 +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")
|
||||
|
||||
[SEARCH_ENGINE_BACKENDS] # "google" | "searxng" | "bing" | "brave" | "yacy"
|
||||
SEARCH = "searxng"
|
||||
IMAGE = "searxng"
|
||||
VIDEO = "searxng"
|
||||
NEWS = "searxng"
|
||||
|
||||
[MODELS.OPENAI]
|
||||
API_KEY = ""
|
||||
|
||||
[MODELS.GROQ]
|
||||
API_KEY = ""
|
||||
|
||||
[MODELS.ANTHROPIC]
|
||||
API_KEY = ""
|
||||
|
||||
[MODELS.GEMINI]
|
||||
API_KEY = ""
|
||||
|
||||
[MODELS.CUSTOM_OPENAI]
|
||||
API_KEY = ""
|
||||
API_URL = ""
|
||||
|
||||
[MODELS.OLLAMA]
|
||||
API_URL = "" # Ollama API URL - http://host.docker.internal:11434
|
||||
|
||||
[SEARCH_ENGINES.GOOGLE]
|
||||
API_KEY = ""
|
||||
CSE_ID = ""
|
||||
|
||||
[SEARCH_ENGINES.SEARXNG]
|
||||
ENDPOINT = ""
|
||||
|
||||
[SEARCH_ENGINES.BING]
|
||||
SUBSCRIPTION_KEY = ""
|
||||
|
||||
[SEARCH_ENGINES.BRAVE]
|
||||
API_KEY = ""
|
||||
|
||||
[SEARCH_ENGINES.YACY]
|
||||
ENDPOINT = ""
|
@ -15,5 +15,3 @@ server:
|
||||
engines:
|
||||
- name: wolframalpha
|
||||
disabled: false
|
||||
- name: qwant
|
||||
disabled: true
|
||||
|
24
src/app.ts
24
src/app.ts
@ -15,24 +15,42 @@ const corsOptions = {
|
||||
origin: '*',
|
||||
};
|
||||
|
||||
logger.info(`🚀 Initializing Server Setup...`);
|
||||
logger.info(`🛠 CORS Policy Applied: ${JSON.stringify(corsOptions)}`);
|
||||
|
||||
app.use(cors(corsOptions));
|
||||
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.get('/api', (_, res) => {
|
||||
logger.info(`🟢 Health Check Endpoint Hit`);
|
||||
res.status(200).json({ status: 'ok' });
|
||||
});
|
||||
|
||||
// ✅ Log when the server starts listening
|
||||
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);
|
||||
|
||||
// ✅ Better Logging for Uncaught Errors
|
||||
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) => {
|
||||
logger.error(`Unhandled Rejection at: ${promise}, reason: ${reason}`);
|
||||
logger.error(`🚨 Unhandled Rejection at: ${promise}`);
|
||||
logger.error(`💥 Reason: ${reason}`);
|
||||
});
|
||||
|
@ -7,12 +7,7 @@ import { PromptTemplate } from '@langchain/core/prompts';
|
||||
import formatChatHistoryAsString from '../utils/formatHistory';
|
||||
import { BaseMessage } from '@langchain/core/messages';
|
||||
import { StringOutputParser } from '@langchain/core/output_parsers';
|
||||
import { searchSearxng } from '../lib/searchEngines/searxng';
|
||||
import { searchGooglePSE } from '../lib/searchEngines/google_pse';
|
||||
import { searchBraveAPI } from '../lib/searchEngines/brave';
|
||||
import { searchYaCy } from '../lib/searchEngines/yacy';
|
||||
import { searchBingAPI } from '../lib/searchEngines/bing';
|
||||
import { getImageSearchEngineBackend } from '../config';
|
||||
import { searchSearxng } from '../lib/searxng';
|
||||
import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
||||
|
||||
const imageSearchChainPrompt = `
|
||||
@ -41,103 +36,6 @@ type ImageSearchChainInput = {
|
||||
query: string;
|
||||
};
|
||||
|
||||
async function performImageSearch(query: string) {
|
||||
const searchEngine = getImageSearchEngineBackend();
|
||||
let images = [];
|
||||
|
||||
switch (searchEngine) {
|
||||
case 'google': {
|
||||
const googleResult = await searchGooglePSE(query);
|
||||
images = googleResult.results
|
||||
.map((result) => {
|
||||
if (result.img_src && result.url && result.title) {
|
||||
return {
|
||||
img_src: result.img_src,
|
||||
url: result.url,
|
||||
title: result.title,
|
||||
source: result.displayLink,
|
||||
};
|
||||
}
|
||||
})
|
||||
.filter(Boolean);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'searxng': {
|
||||
const searxResult = await searchSearxng(query, {
|
||||
engines: ['google images', 'bing images'],
|
||||
pageno: 1,
|
||||
});
|
||||
searxResult.results.forEach((result) => {
|
||||
if (result.img_src && result.url && result.title) {
|
||||
images.push({
|
||||
img_src: result.img_src,
|
||||
url: result.url,
|
||||
title: result.title,
|
||||
});
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'brave': {
|
||||
const braveResult = await searchBraveAPI(query);
|
||||
images = braveResult.results
|
||||
.map((result) => {
|
||||
if (result.img_src && result.url && result.title) {
|
||||
return {
|
||||
img_src: result.img_src,
|
||||
url: result.url,
|
||||
title: result.title,
|
||||
source: result.url,
|
||||
};
|
||||
}
|
||||
})
|
||||
.filter(Boolean);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'yacy': {
|
||||
const yacyResult = await searchYaCy(query);
|
||||
images = yacyResult.results
|
||||
.map((result) => {
|
||||
if (result.img_src && result.url && result.title) {
|
||||
return {
|
||||
img_src: result.img_src,
|
||||
url: result.url,
|
||||
title: result.title,
|
||||
source: result.url,
|
||||
};
|
||||
}
|
||||
})
|
||||
.filter(Boolean);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'bing': {
|
||||
const bingResult = await searchBingAPI(query);
|
||||
images = bingResult.results
|
||||
.map((result) => {
|
||||
if (result.img_src && result.url && result.title) {
|
||||
return {
|
||||
img_src: result.img_src,
|
||||
url: result.url,
|
||||
title: result.title,
|
||||
source: result.url,
|
||||
};
|
||||
}
|
||||
})
|
||||
.filter(Boolean);
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`Unknown search engine ${searchEngine}`);
|
||||
}
|
||||
|
||||
return images;
|
||||
}
|
||||
|
||||
const strParser = new StringOutputParser();
|
||||
|
||||
const createImageSearchChain = (llm: BaseChatModel) => {
|
||||
@ -154,7 +52,22 @@ const createImageSearchChain = (llm: BaseChatModel) => {
|
||||
llm,
|
||||
strParser,
|
||||
RunnableLambda.from(async (input: string) => {
|
||||
const images = await performImageSearch(input);
|
||||
const res = await searchSearxng(input, {
|
||||
engines: ['bing images', 'google images'],
|
||||
});
|
||||
|
||||
const images = [];
|
||||
|
||||
res.results.forEach((result) => {
|
||||
if (result.img_src && result.url && result.title) {
|
||||
images.push({
|
||||
img_src: result.img_src,
|
||||
url: result.url,
|
||||
title: result.title,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return images.slice(0, 10);
|
||||
}),
|
||||
]);
|
||||
|
@ -7,30 +7,26 @@ import { PromptTemplate } from '@langchain/core/prompts';
|
||||
import formatChatHistoryAsString from '../utils/formatHistory';
|
||||
import { BaseMessage } from '@langchain/core/messages';
|
||||
import { StringOutputParser } from '@langchain/core/output_parsers';
|
||||
import { searchSearxng } from '../lib/searchEngines/searxng';
|
||||
import { searchGooglePSE } from '../lib/searchEngines/google_pse';
|
||||
import { searchBraveAPI } from '../lib/searchEngines/brave';
|
||||
import { searchBingAPI } from '../lib/searchEngines/bing';
|
||||
import { getVideoSearchEngineBackend } from '../config';
|
||||
import { searchSearxng } from '../lib/searxng';
|
||||
import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
||||
|
||||
const VideoSearchChainPrompt = `
|
||||
You will be given a conversation below and a follow up question. You need to rephrase the follow-up question so it is a standalone question that can be used by the LLM to search Youtube for videos.
|
||||
You need to make sure the rephrased question agrees with the conversation and is relevant to the conversation.
|
||||
|
||||
|
||||
Example:
|
||||
1. Follow up question: How does a car work?
|
||||
Rephrased: How does a car work?
|
||||
|
||||
|
||||
2. Follow up question: What is the theory of relativity?
|
||||
Rephrased: What is theory of relativity
|
||||
|
||||
|
||||
3. Follow up question: How does an AC work?
|
||||
Rephrased: How does an AC work
|
||||
|
||||
|
||||
Conversation:
|
||||
{chat_history}
|
||||
|
||||
|
||||
Follow up question: {query}
|
||||
Rephrased question:
|
||||
`;
|
||||
@ -42,102 +38,6 @@ type VideoSearchChainInput = {
|
||||
|
||||
const strParser = new StringOutputParser();
|
||||
|
||||
async function performVideoSearch(query: string) {
|
||||
const searchEngine = getVideoSearchEngineBackend();
|
||||
const youtubeQuery = `${query} site:youtube.com`;
|
||||
let videos = [];
|
||||
|
||||
switch (searchEngine) {
|
||||
case 'google': {
|
||||
const googleResult = await searchGooglePSE(youtubeQuery);
|
||||
googleResult.results.forEach((result) => {
|
||||
// Use .results instead of .originalres
|
||||
if (result.img_src && result.url && result.title) {
|
||||
const videoId = new URL(result.url).searchParams.get('v');
|
||||
videos.push({
|
||||
img_src: result.img_src,
|
||||
url: result.url,
|
||||
title: result.title,
|
||||
iframe_src: videoId
|
||||
? `https://www.youtube.com/embed/${videoId}`
|
||||
: null,
|
||||
});
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'searxng': {
|
||||
const searxResult = await searchSearxng(query, {
|
||||
engines: ['youtube'],
|
||||
});
|
||||
searxResult.results.forEach((result) => {
|
||||
if (
|
||||
result.thumbnail &&
|
||||
result.url &&
|
||||
result.title &&
|
||||
result.iframe_src
|
||||
) {
|
||||
videos.push({
|
||||
img_src: result.thumbnail,
|
||||
url: result.url,
|
||||
title: result.title,
|
||||
iframe_src: result.iframe_src,
|
||||
});
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'brave': {
|
||||
const braveResult = await searchBraveAPI(youtubeQuery);
|
||||
braveResult.results.forEach((result) => {
|
||||
if (result.img_src && result.url && result.title) {
|
||||
const videoId = new URL(result.url).searchParams.get('v');
|
||||
videos.push({
|
||||
img_src: result.img_src,
|
||||
url: result.url,
|
||||
title: result.title,
|
||||
iframe_src: videoId
|
||||
? `https://www.youtube.com/embed/${videoId}`
|
||||
: null,
|
||||
});
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'yacy': {
|
||||
console.log('Not available for yacy');
|
||||
videos = [];
|
||||
break;
|
||||
}
|
||||
|
||||
case 'bing': {
|
||||
const bingResult = await searchBingAPI(youtubeQuery);
|
||||
bingResult.results.forEach((result) => {
|
||||
if (result.img_src && result.url && result.title) {
|
||||
const videoId = new URL(result.url).searchParams.get('v');
|
||||
videos.push({
|
||||
img_src: result.img_src,
|
||||
url: result.url,
|
||||
title: result.title,
|
||||
iframe_src: videoId
|
||||
? `https://www.youtube.com/embed/${videoId}`
|
||||
: null,
|
||||
});
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`Unknown search engine ${searchEngine}`);
|
||||
}
|
||||
|
||||
return videos;
|
||||
}
|
||||
|
||||
const createVideoSearchChain = (llm: BaseChatModel) => {
|
||||
return RunnableSequence.from([
|
||||
RunnableMap.from({
|
||||
@ -152,7 +52,28 @@ const createVideoSearchChain = (llm: BaseChatModel) => {
|
||||
llm,
|
||||
strParser,
|
||||
RunnableLambda.from(async (input: string) => {
|
||||
const videos = await performVideoSearch(input);
|
||||
const res = await searchSearxng(input, {
|
||||
engines: ['youtube'],
|
||||
});
|
||||
|
||||
const videos = [];
|
||||
|
||||
res.results.forEach((result) => {
|
||||
if (
|
||||
result.thumbnail &&
|
||||
result.url &&
|
||||
result.title &&
|
||||
result.iframe_src
|
||||
) {
|
||||
videos.push({
|
||||
img_src: result.thumbnail,
|
||||
url: result.url,
|
||||
title: result.title,
|
||||
iframe_src: result.iframe_src,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return videos.slice(0, 10);
|
||||
}),
|
||||
]);
|
||||
|
149
src/config.ts
149
src/config.ts
@ -10,51 +10,15 @@ interface Config {
|
||||
SIMILARITY_MEASURE: string;
|
||||
KEEP_ALIVE: string;
|
||||
};
|
||||
SEARCH_ENGINE_BACKENDS: {
|
||||
SEARCH: string;
|
||||
IMAGE: string;
|
||||
VIDEO: string;
|
||||
NEWS: string;
|
||||
API_KEYS: {
|
||||
OPENAI: string;
|
||||
GROQ: string;
|
||||
ANTHROPIC: string;
|
||||
GEMINI: string;
|
||||
};
|
||||
MODELS: {
|
||||
OPENAI: {
|
||||
API_KEY: string;
|
||||
};
|
||||
GROQ: {
|
||||
API_KEY: string;
|
||||
};
|
||||
ANTHROPIC: {
|
||||
API_KEY: string;
|
||||
};
|
||||
GEMINI: {
|
||||
API_KEY: string;
|
||||
};
|
||||
OLLAMA: {
|
||||
API_URL: string;
|
||||
};
|
||||
CUSTOM_OPENAI: {
|
||||
API_URL: string;
|
||||
API_KEY: string;
|
||||
MODEL_NAME: string;
|
||||
};
|
||||
};
|
||||
SEARCH_ENGINES: {
|
||||
GOOGLE: {
|
||||
API_KEY: string;
|
||||
CSE_ID: string;
|
||||
};
|
||||
SEARXNG: {
|
||||
ENDPOINT: string;
|
||||
};
|
||||
BING: {
|
||||
SUBSCRIPTION_KEY: string;
|
||||
};
|
||||
BRAVE: {
|
||||
API_KEY: string;
|
||||
};
|
||||
YACY: {
|
||||
ENDPOINT: string;
|
||||
};
|
||||
API_ENDPOINTS: {
|
||||
SEARXNG: string;
|
||||
OLLAMA: string;
|
||||
};
|
||||
}
|
||||
|
||||
@ -74,89 +38,42 @@ export const getSimilarityMeasure = () =>
|
||||
|
||||
export const getKeepAlive = () => loadConfig().GENERAL.KEEP_ALIVE;
|
||||
|
||||
export const getOpenaiApiKey = () => loadConfig().MODELS.OPENAI.API_KEY;
|
||||
export const getOpenaiApiKey = () => loadConfig().API_KEYS.OPENAI;
|
||||
|
||||
export const getGroqApiKey = () => loadConfig().MODELS.GROQ.API_KEY;
|
||||
export const getGroqApiKey = () => loadConfig().API_KEYS.GROQ;
|
||||
|
||||
export const getAnthropicApiKey = () => loadConfig().MODELS.ANTHROPIC.API_KEY;
|
||||
export const getAnthropicApiKey = () => loadConfig().API_KEYS.ANTHROPIC;
|
||||
|
||||
export const getGeminiApiKey = () => loadConfig().MODELS.GEMINI.API_KEY;
|
||||
|
||||
export const getSearchEngineBackend = () =>
|
||||
loadConfig().SEARCH_ENGINE_BACKENDS.SEARCH;
|
||||
|
||||
export const getImageSearchEngineBackend = () =>
|
||||
loadConfig().SEARCH_ENGINE_BACKENDS.IMAGE || getSearchEngineBackend();
|
||||
|
||||
export const getVideoSearchEngineBackend = () =>
|
||||
loadConfig().SEARCH_ENGINE_BACKENDS.VIDEO || getSearchEngineBackend();
|
||||
|
||||
export const getNewsSearchEngineBackend = () =>
|
||||
loadConfig().SEARCH_ENGINE_BACKENDS.NEWS || getSearchEngineBackend();
|
||||
|
||||
export const getGoogleApiKey = () => loadConfig().SEARCH_ENGINES.GOOGLE.API_KEY;
|
||||
|
||||
export const getGoogleCseId = () => loadConfig().SEARCH_ENGINES.GOOGLE.CSE_ID;
|
||||
|
||||
export const getBraveApiKey = () => loadConfig().SEARCH_ENGINES.BRAVE.API_KEY;
|
||||
|
||||
export const getBingSubscriptionKey = () =>
|
||||
loadConfig().SEARCH_ENGINES.BING.SUBSCRIPTION_KEY;
|
||||
|
||||
export const getYacyJsonEndpoint = () =>
|
||||
loadConfig().SEARCH_ENGINES.YACY.ENDPOINT;
|
||||
export const getGeminiApiKey = () => loadConfig().API_KEYS.GEMINI;
|
||||
|
||||
export const getSearxngApiEndpoint = () =>
|
||||
process.env.SEARXNG_API_URL || loadConfig().SEARCH_ENGINES.SEARXNG.ENDPOINT;
|
||||
process.env.SEARXNG_API_URL || loadConfig().API_ENDPOINTS.SEARXNG;
|
||||
|
||||
export const getOllamaApiEndpoint = () => loadConfig().MODELS.OLLAMA.API_URL;
|
||||
|
||||
export const getCustomOpenaiApiKey = () =>
|
||||
loadConfig().MODELS.CUSTOM_OPENAI.API_KEY;
|
||||
|
||||
export const getCustomOpenaiApiUrl = () =>
|
||||
loadConfig().MODELS.CUSTOM_OPENAI.API_URL;
|
||||
|
||||
export const getCustomOpenaiModelName = () =>
|
||||
loadConfig().MODELS.CUSTOM_OPENAI.MODEL_NAME;
|
||||
|
||||
const mergeConfigs = (current: any, update: any): any => {
|
||||
if (update === null || update === undefined) {
|
||||
return current;
|
||||
}
|
||||
|
||||
if (typeof current !== 'object' || current === null) {
|
||||
return update;
|
||||
}
|
||||
|
||||
const result = { ...current };
|
||||
|
||||
for (const key in update) {
|
||||
if (Object.prototype.hasOwnProperty.call(update, key)) {
|
||||
const updateValue = update[key];
|
||||
|
||||
if (
|
||||
typeof updateValue === 'object' &&
|
||||
updateValue !== null &&
|
||||
typeof result[key] === 'object' &&
|
||||
result[key] !== null
|
||||
) {
|
||||
result[key] = mergeConfigs(result[key], updateValue);
|
||||
} else if (updateValue !== undefined) {
|
||||
result[key] = updateValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
export const getOllamaApiEndpoint = () => loadConfig().API_ENDPOINTS.OLLAMA;
|
||||
|
||||
export const updateConfig = (config: RecursivePartial<Config>) => {
|
||||
const currentConfig = loadConfig();
|
||||
const mergedConfig = mergeConfigs(currentConfig, config);
|
||||
|
||||
for (const key in currentConfig) {
|
||||
if (!config[key]) config[key] = {};
|
||||
|
||||
if (typeof currentConfig[key] === 'object' && currentConfig[key] !== null) {
|
||||
for (const nestedKey in currentConfig[key]) {
|
||||
if (
|
||||
!config[key][nestedKey] &&
|
||||
currentConfig[key][nestedKey] &&
|
||||
config[key][nestedKey] !== ''
|
||||
) {
|
||||
config[key][nestedKey] = currentConfig[key][nestedKey];
|
||||
}
|
||||
}
|
||||
} else if (currentConfig[key] && config[key] !== '') {
|
||||
config[key] = currentConfig[key];
|
||||
}
|
||||
}
|
||||
|
||||
fs.writeFileSync(
|
||||
path.join(__dirname, `../${configFileName}`),
|
||||
toml.stringify(mergedConfig),
|
||||
toml.stringify(config),
|
||||
);
|
||||
};
|
||||
|
@ -36,22 +36,6 @@ export const loadGeminiChatModels = async () => {
|
||||
apiKey: geminiApiKey,
|
||||
}),
|
||||
},
|
||||
'gemini-2.0-flash-exp': {
|
||||
displayName: 'Gemini 2.0 Flash Exp',
|
||||
model: new ChatGoogleGenerativeAI({
|
||||
modelName: 'gemini-2.0-flash-exp',
|
||||
temperature: 0.7,
|
||||
apiKey: geminiApiKey,
|
||||
}),
|
||||
},
|
||||
'gemini-2.0-flash-thinking-exp-01-21': {
|
||||
displayName: 'Gemini 2.0 Flash Thinking Exp 01-21',
|
||||
model: new ChatGoogleGenerativeAI({
|
||||
modelName: 'gemini-2.0-flash-thinking-exp-01-21',
|
||||
temperature: 0.7,
|
||||
apiKey: geminiApiKey,
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
return chatModels;
|
||||
|
@ -4,12 +4,6 @@ import { loadOpenAIChatModels, loadOpenAIEmbeddingsModels } from './openai';
|
||||
import { loadAnthropicChatModels } from './anthropic';
|
||||
import { loadTransformersEmbeddingsModels } from './transformers';
|
||||
import { loadGeminiChatModels, loadGeminiEmbeddingsModels } from './gemini';
|
||||
import {
|
||||
getCustomOpenaiApiKey,
|
||||
getCustomOpenaiApiUrl,
|
||||
getCustomOpenaiModelName,
|
||||
} from '../../config';
|
||||
import { ChatOpenAI } from '@langchain/openai';
|
||||
|
||||
const chatModelProviders = {
|
||||
openai: loadOpenAIChatModels,
|
||||
@ -36,27 +30,7 @@ export const getAvailableChatModelProviders = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
const customOpenAiApiKey = getCustomOpenaiApiKey();
|
||||
const customOpenAiApiUrl = getCustomOpenaiApiUrl();
|
||||
const customOpenAiModelName = getCustomOpenaiModelName();
|
||||
|
||||
models['custom_openai'] = {
|
||||
...(customOpenAiApiKey && customOpenAiApiUrl && customOpenAiModelName
|
||||
? {
|
||||
[customOpenAiModelName]: {
|
||||
displayName: customOpenAiModelName,
|
||||
model: new ChatOpenAI({
|
||||
openAIApiKey: customOpenAiApiKey,
|
||||
modelName: customOpenAiModelName,
|
||||
temperature: 0.7,
|
||||
configuration: {
|
||||
baseURL: customOpenAiApiUrl,
|
||||
},
|
||||
}),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
models['custom_openai'] = {};
|
||||
|
||||
return models;
|
||||
};
|
||||
|
@ -1,105 +0,0 @@
|
||||
import axios from 'axios';
|
||||
import { getBingSubscriptionKey } from '../../config';
|
||||
|
||||
interface BingAPISearchResult {
|
||||
_type: string;
|
||||
name: string;
|
||||
url: string;
|
||||
displayUrl: string;
|
||||
snippet?: string;
|
||||
dateLastCrawled?: string;
|
||||
thumbnailUrl?: string;
|
||||
contentUrl?: string;
|
||||
hostPageUrl?: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
accentColor?: string;
|
||||
contentSize?: string;
|
||||
datePublished?: string;
|
||||
encodingFormat?: string;
|
||||
hostPageDisplayUrl?: string;
|
||||
id?: string;
|
||||
isLicensed?: boolean;
|
||||
isFamilyFriendly?: boolean;
|
||||
language?: string;
|
||||
mediaUrl?: string;
|
||||
motionThumbnailUrl?: string;
|
||||
publisher?: string;
|
||||
viewCount?: number;
|
||||
webSearchUrl?: string;
|
||||
primaryImageOfPage?: {
|
||||
thumbnailUrl?: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
};
|
||||
video?: {
|
||||
allowHttpsEmbed?: boolean;
|
||||
embedHtml?: string;
|
||||
allowMobileEmbed?: boolean;
|
||||
viewCount?: number;
|
||||
duration?: string;
|
||||
};
|
||||
image?: {
|
||||
thumbnail?: {
|
||||
contentUrl?: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
};
|
||||
imageInsightsToken?: string;
|
||||
imageId?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export const searchBingAPI = async (query: string) => {
|
||||
try {
|
||||
const bingApiKey = await getBingSubscriptionKey();
|
||||
const url = new URL(`https://api.cognitive.microsoft.com/bing/v7.0/search`);
|
||||
url.searchParams.append('q', query);
|
||||
url.searchParams.append('responseFilter', 'Webpages,Images,Videos');
|
||||
|
||||
const res = await axios.get(url.toString(), {
|
||||
headers: {
|
||||
'Ocp-Apim-Subscription-Key': bingApiKey,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (res.data.error) {
|
||||
throw new Error(`Bing API Error: ${res.data.error.message}`);
|
||||
}
|
||||
|
||||
const originalres = res.data;
|
||||
|
||||
// Extract web, image, and video results
|
||||
const webResults = originalres.webPages?.value || [];
|
||||
const imageResults = originalres.images?.value || [];
|
||||
const videoResults = originalres.videos?.value || [];
|
||||
|
||||
const results = webResults.map((item: BingAPISearchResult) => ({
|
||||
title: item.name,
|
||||
url: item.url,
|
||||
content: item.snippet,
|
||||
img_src:
|
||||
item.primaryImageOfPage?.thumbnailUrl ||
|
||||
imageResults.find((img: any) => img.hostPageUrl === item.url)
|
||||
?.thumbnailUrl ||
|
||||
videoResults.find((vid: any) => vid.hostPageUrl === item.url)
|
||||
?.thumbnailUrl,
|
||||
...(item.video && {
|
||||
videoData: {
|
||||
duration: item.video.duration,
|
||||
embedUrl: item.video.embedHtml?.match(/src="(.*?)"/)?.[1],
|
||||
},
|
||||
publisher: item.publisher,
|
||||
datePublished: item.datePublished,
|
||||
}),
|
||||
}));
|
||||
|
||||
return { results, originalres };
|
||||
} catch (error) {
|
||||
const errorMessage = error.response?.data
|
||||
? JSON.stringify(error.response.data, null, 2)
|
||||
: error.message || 'Unknown error';
|
||||
throw new Error(`Bing API Error: ${errorMessage}`);
|
||||
}
|
||||
};
|
@ -1,102 +0,0 @@
|
||||
import axios from 'axios';
|
||||
import { getBraveApiKey } from '../../config';
|
||||
|
||||
interface BraveSearchResult {
|
||||
title: string;
|
||||
url: string;
|
||||
content?: string;
|
||||
img_src?: string;
|
||||
age?: string;
|
||||
family_friendly?: boolean;
|
||||
language?: string;
|
||||
video?: {
|
||||
embedUrl?: string;
|
||||
duration?: string;
|
||||
};
|
||||
rating?: {
|
||||
value: number;
|
||||
scale: number;
|
||||
};
|
||||
products?: Array<{
|
||||
name: string;
|
||||
price?: string;
|
||||
}>;
|
||||
recipe?: {
|
||||
ingredients?: string[];
|
||||
cookTime?: string;
|
||||
};
|
||||
meta?: {
|
||||
fetched?: string;
|
||||
lastCrawled?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export const searchBraveAPI = async (
|
||||
query: string,
|
||||
numResults: number = 20,
|
||||
): Promise<{ results: BraveSearchResult[]; originalres: any }> => {
|
||||
try {
|
||||
const braveApiKey = await getBraveApiKey();
|
||||
const url = new URL(`https://api.search.brave.com/res/v1/web/search`);
|
||||
|
||||
url.searchParams.append('q', query);
|
||||
url.searchParams.append('count', numResults.toString());
|
||||
|
||||
const res = await axios.get(url.toString(), {
|
||||
headers: {
|
||||
'X-Subscription-Token': braveApiKey,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (res.data.error) {
|
||||
throw new Error(`Brave API Error: ${res.data.error.message}`);
|
||||
}
|
||||
|
||||
const originalres = res.data;
|
||||
const webResults = originalres.web?.results || [];
|
||||
|
||||
const results: BraveSearchResult[] = webResults.map((item: any) => ({
|
||||
title: item.title,
|
||||
url: item.url,
|
||||
content: item.description,
|
||||
img_src: item.thumbnail?.src || item.deep_results?.images?.[0]?.src,
|
||||
age: item.age,
|
||||
family_friendly: item.family_friendly,
|
||||
language: item.language,
|
||||
video: item.video
|
||||
? {
|
||||
embedUrl: item.video.embed_url,
|
||||
duration: item.video.duration,
|
||||
}
|
||||
: undefined,
|
||||
rating: item.rating
|
||||
? {
|
||||
value: item.rating.value,
|
||||
scale: item.rating.scale_max,
|
||||
}
|
||||
: undefined,
|
||||
products: item.deep_results?.product_cluster?.map((p: any) => ({
|
||||
name: p.name,
|
||||
price: p.price,
|
||||
})),
|
||||
recipe: item.recipe
|
||||
? {
|
||||
ingredients: item.recipe.ingredients,
|
||||
cookTime: item.recipe.cook_time,
|
||||
}
|
||||
: undefined,
|
||||
meta: {
|
||||
fetched: item.meta?.fetched,
|
||||
lastCrawled: item.meta?.last_crawled,
|
||||
},
|
||||
}));
|
||||
|
||||
return { results, originalres };
|
||||
} catch (error) {
|
||||
const errorMessage = error.response?.data
|
||||
? JSON.stringify(error.response.data, null, 2)
|
||||
: error.message || 'Unknown error';
|
||||
throw new Error(`Brave API Error: ${errorMessage}`);
|
||||
}
|
||||
};
|
@ -1,85 +0,0 @@
|
||||
import axios from 'axios';
|
||||
import { getGoogleApiKey, getGoogleCseId } from '../../config';
|
||||
|
||||
interface GooglePSESearchResult {
|
||||
kind: string;
|
||||
title: string;
|
||||
htmlTitle: string;
|
||||
link: string;
|
||||
displayLink: string;
|
||||
snippet?: string;
|
||||
htmlSnippet?: string;
|
||||
cacheId?: string;
|
||||
formattedUrl: string;
|
||||
htmlFormattedUrl: string;
|
||||
pagemap?: {
|
||||
videoobject: any;
|
||||
cse_thumbnail?: Array<{
|
||||
src: string;
|
||||
width: string;
|
||||
height: string;
|
||||
}>;
|
||||
metatags?: Array<{
|
||||
[key: string]: string;
|
||||
author?: string;
|
||||
}>;
|
||||
cse_image?: Array<{
|
||||
src: string;
|
||||
}>;
|
||||
};
|
||||
fileFormat?: string;
|
||||
image?: {
|
||||
contextLink: string;
|
||||
thumbnailLink: string;
|
||||
};
|
||||
mime?: string;
|
||||
labels?: Array<{
|
||||
name: string;
|
||||
displayName: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
export const searchGooglePSE = async (query: string) => {
|
||||
try {
|
||||
const [googleApiKey, googleCseID] = await Promise.all([
|
||||
getGoogleApiKey(),
|
||||
getGoogleCseId(),
|
||||
]);
|
||||
|
||||
const url = new URL(`https://www.googleapis.com/customsearch/v1`);
|
||||
url.searchParams.append('q', query);
|
||||
url.searchParams.append('cx', googleCseID);
|
||||
url.searchParams.append('key', googleApiKey);
|
||||
|
||||
const res = await axios.get(url.toString());
|
||||
|
||||
if (res.data.error) {
|
||||
throw new Error(`Google PSE Error: ${res.data.error.message}`);
|
||||
}
|
||||
|
||||
const originalres = res.data.items;
|
||||
|
||||
const results = originalres.map((item: GooglePSESearchResult) => ({
|
||||
title: item.title,
|
||||
url: item.link,
|
||||
content: item.snippet,
|
||||
img_src:
|
||||
item.pagemap?.cse_image?.[0]?.src ||
|
||||
item.pagemap?.cse_thumbnail?.[0]?.src ||
|
||||
item.image?.thumbnailLink,
|
||||
...(item.pagemap?.videoobject?.[0] && {
|
||||
videoData: {
|
||||
duration: item.pagemap.videoobject[0].duration,
|
||||
embedUrl: item.pagemap.videoobject[0].embedurl,
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
return { results, originalres };
|
||||
} catch (error) {
|
||||
const errorMessage = error.response?.data
|
||||
? JSON.stringify(error.response.data, null, 2)
|
||||
: error.message || 'Unknown error';
|
||||
throw new Error(`Google PSE Error: ${errorMessage}`);
|
||||
}
|
||||
};
|
@ -1,79 +0,0 @@
|
||||
import axios from 'axios';
|
||||
import { getYacyJsonEndpoint } from '../../config';
|
||||
|
||||
interface YaCySearchResult {
|
||||
channels: {
|
||||
title: string;
|
||||
description: string;
|
||||
link: string;
|
||||
image: {
|
||||
url: string;
|
||||
title: string;
|
||||
link: string;
|
||||
};
|
||||
startIndex: string;
|
||||
itemsPerPage: string;
|
||||
searchTerms: string;
|
||||
items: {
|
||||
title: string;
|
||||
link: string;
|
||||
code: string;
|
||||
description: string;
|
||||
pubDate: string;
|
||||
image?: string;
|
||||
size: string;
|
||||
sizename: string;
|
||||
guid: string;
|
||||
faviconUrl: string;
|
||||
host: string;
|
||||
path: string;
|
||||
file: string;
|
||||
urlhash: string;
|
||||
ranking: string;
|
||||
}[];
|
||||
navigation: {
|
||||
facetname: string;
|
||||
displayname: string;
|
||||
type: string;
|
||||
min: string;
|
||||
max: string;
|
||||
mean: string;
|
||||
elements: {
|
||||
name: string;
|
||||
count: string;
|
||||
modifier: string;
|
||||
url: string;
|
||||
}[];
|
||||
}[];
|
||||
}[];
|
||||
}
|
||||
|
||||
export const searchYaCy = async (query: string, numResults: number = 20) => {
|
||||
try {
|
||||
const yacyBaseUrl = getYacyJsonEndpoint();
|
||||
|
||||
const url = new URL(`${yacyBaseUrl}/yacysearch.json`);
|
||||
url.searchParams.append('query', query);
|
||||
url.searchParams.append('count', numResults.toString());
|
||||
|
||||
const res = await axios.get(url.toString());
|
||||
|
||||
const originalres = res.data as YaCySearchResult;
|
||||
|
||||
const results = originalres.channels[0].items.map((item) => ({
|
||||
title: item.title,
|
||||
url: item.link,
|
||||
content: item.description,
|
||||
img_src: item.image || null,
|
||||
pubDate: item.pubDate,
|
||||
host: item.host,
|
||||
}));
|
||||
|
||||
return { results, originalres };
|
||||
} catch (error) {
|
||||
const errorMessage = error.response?.data
|
||||
? JSON.stringify(error.response.data, null, 2)
|
||||
: error.message || 'Unknown error';
|
||||
throw new Error(`YaCy Error: ${errorMessage}`);
|
||||
}
|
||||
};
|
@ -1,5 +1,5 @@
|
||||
import axios from 'axios';
|
||||
import { getSearxngApiEndpoint } from '../../config';
|
||||
import { getSearxngApiEndpoint } from '../config';
|
||||
|
||||
interface SearxngSearchOptions {
|
||||
categories?: string[];
|
@ -1,4 +1,5 @@
|
||||
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.
|
||||
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 = `
|
||||
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:
|
||||
- **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 = `
|
||||
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:
|
||||
- **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 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 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
|
||||
|
||||
<examples>
|
||||
@ -62,7 +63,7 @@ Rephrased question:
|
||||
`;
|
||||
|
||||
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:
|
||||
- **Informative and relevant**: Thoroughly address the user's query using the given context.
|
||||
|
@ -20,7 +20,7 @@ Rephrased question:
|
||||
`;
|
||||
|
||||
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:
|
||||
- **Informative and relevant**: Thoroughly address the user's query using the given context.
|
||||
|
@ -1,5 +1,5 @@
|
||||
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.
|
||||
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 = `
|
||||
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.
|
||||
|
||||
Example:
|
||||
@ -20,7 +20,7 @@ Rephrased question:
|
||||
`;
|
||||
|
||||
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:
|
||||
- **Informative and relevant**: Thoroughly address the user's query using the given context.
|
||||
|
@ -10,19 +10,6 @@ import {
|
||||
getGeminiApiKey,
|
||||
getOpenaiApiKey,
|
||||
updateConfig,
|
||||
getCustomOpenaiApiUrl,
|
||||
getCustomOpenaiApiKey,
|
||||
getCustomOpenaiModelName,
|
||||
getSearchEngineBackend,
|
||||
getImageSearchEngineBackend,
|
||||
getVideoSearchEngineBackend,
|
||||
getNewsSearchEngineBackend,
|
||||
getSearxngApiEndpoint,
|
||||
getGoogleApiKey,
|
||||
getGoogleCseId,
|
||||
getBingSubscriptionKey,
|
||||
getBraveApiKey,
|
||||
getYacyJsonEndpoint,
|
||||
} from '../config';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
@ -67,24 +54,6 @@ router.get('/', async (_, res) => {
|
||||
config['anthropicApiKey'] = getAnthropicApiKey();
|
||||
config['groqApiKey'] = getGroqApiKey();
|
||||
config['geminiApiKey'] = getGeminiApiKey();
|
||||
config['customOpenaiApiUrl'] = getCustomOpenaiApiUrl();
|
||||
config['customOpenaiApiKey'] = getCustomOpenaiApiKey();
|
||||
config['customOpenaiModelName'] = getCustomOpenaiModelName();
|
||||
|
||||
// Add search engine configuration
|
||||
config['searchEngineBackends'] = {
|
||||
search: getSearchEngineBackend(),
|
||||
image: getImageSearchEngineBackend(),
|
||||
video: getVideoSearchEngineBackend(),
|
||||
news: getNewsSearchEngineBackend(),
|
||||
};
|
||||
|
||||
config['searxngEndpoint'] = getSearxngApiEndpoint();
|
||||
config['googleApiKey'] = getGoogleApiKey();
|
||||
config['googleCseId'] = getGoogleCseId();
|
||||
config['bingSubscriptionKey'] = getBingSubscriptionKey();
|
||||
config['braveApiKey'] = getBraveApiKey();
|
||||
config['yacyEndpoint'] = getYacyJsonEndpoint();
|
||||
|
||||
res.status(200).json(config);
|
||||
} catch (err: any) {
|
||||
@ -97,51 +66,14 @@ router.post('/', async (req, res) => {
|
||||
const config = req.body;
|
||||
|
||||
const updatedConfig = {
|
||||
MODELS: {
|
||||
OPENAI: {
|
||||
API_KEY: config.openaiApiKey,
|
||||
},
|
||||
GROQ: {
|
||||
API_KEY: config.groqApiKey,
|
||||
},
|
||||
ANTHROPIC: {
|
||||
API_KEY: config.anthropicApiKey,
|
||||
},
|
||||
GEMINI: {
|
||||
API_KEY: config.geminiApiKey,
|
||||
},
|
||||
OLLAMA: {
|
||||
API_URL: config.ollamaApiUrl,
|
||||
},
|
||||
CUSTOM_OPENAI: {
|
||||
API_URL: config.customOpenaiApiUrl,
|
||||
API_KEY: config.customOpenaiApiKey,
|
||||
MODEL_NAME: config.customOpenaiModelName,
|
||||
},
|
||||
API_KEYS: {
|
||||
OPENAI: config.openaiApiKey,
|
||||
GROQ: config.groqApiKey,
|
||||
ANTHROPIC: config.anthropicApiKey,
|
||||
GEMINI: config.geminiApiKey,
|
||||
},
|
||||
SEARCH_ENGINE_BACKENDS: config.searchEngineBackends ? {
|
||||
SEARCH: config.searchEngineBackends.search,
|
||||
IMAGE: config.searchEngineBackends.image,
|
||||
VIDEO: config.searchEngineBackends.video,
|
||||
NEWS: config.searchEngineBackends.news,
|
||||
} : undefined,
|
||||
SEARCH_ENGINES: {
|
||||
GOOGLE: {
|
||||
API_KEY: config.googleApiKey,
|
||||
CSE_ID: config.googleCseId,
|
||||
},
|
||||
SEARXNG: {
|
||||
ENDPOINT: config.searxngEndpoint,
|
||||
},
|
||||
BING: {
|
||||
SUBSCRIPTION_KEY: config.bingSubscriptionKey,
|
||||
},
|
||||
BRAVE: {
|
||||
API_KEY: config.braveApiKey,
|
||||
},
|
||||
YACY: {
|
||||
ENDPOINT: config.yacyEndpoint,
|
||||
},
|
||||
API_ENDPOINTS: {
|
||||
OLLAMA: config.ollamaApiUrl,
|
||||
},
|
||||
};
|
||||
|
||||
|
@ -1,125 +1,59 @@
|
||||
import express from 'express';
|
||||
import { searchSearxng } from '../lib/searchEngines/searxng';
|
||||
import { searchGooglePSE } from '../lib/searchEngines/google_pse';
|
||||
import { searchBraveAPI } from '../lib/searchEngines/brave';
|
||||
import { searchYaCy } from '../lib/searchEngines/yacy';
|
||||
import { searchBingAPI } from '../lib/searchEngines/bing';
|
||||
import { getNewsSearchEngineBackend } from '../config';
|
||||
import { searchSearxng } from '../lib/searxng';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
async function performSearch(query: string, site: string) {
|
||||
const searchEngine = getNewsSearchEngineBackend();
|
||||
switch (searchEngine) {
|
||||
case 'google': {
|
||||
const googleResult = await searchGooglePSE(query);
|
||||
|
||||
return googleResult.originalres.map((item) => {
|
||||
const imageSources = [
|
||||
item.pagemap?.cse_image?.[0]?.src,
|
||||
item.pagemap?.cse_thumbnail?.[0]?.src,
|
||||
item.pagemap?.metatags?.[0]?.['og:image'],
|
||||
item.pagemap?.metatags?.[0]?.['twitter:image'],
|
||||
item.pagemap?.metatags?.[0]?.['image'],
|
||||
].filter(Boolean); // Remove undefined values
|
||||
|
||||
return {
|
||||
title: item.title,
|
||||
url: item.link,
|
||||
content: item.snippet,
|
||||
thumbnail: imageSources[0], // First available image
|
||||
img_src: imageSources[0], // Same as thumbnail for consistency
|
||||
iframe_src: null,
|
||||
author: item.pagemap?.metatags?.[0]?.['og:site_name'] || site,
|
||||
publishedDate:
|
||||
item.pagemap?.metatags?.[0]?.['article:published_time'],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
case 'searxng': {
|
||||
const searxResult = await searchSearxng(query, {
|
||||
engines: ['bing news'],
|
||||
pageno: 1,
|
||||
});
|
||||
return searxResult.results;
|
||||
}
|
||||
|
||||
case 'brave': {
|
||||
const braveResult = await searchBraveAPI(query);
|
||||
return braveResult.results.map((item) => ({
|
||||
title: item.title,
|
||||
url: item.url,
|
||||
content: item.content,
|
||||
thumbnail: item.img_src,
|
||||
img_src: item.img_src,
|
||||
iframe_src: null,
|
||||
author: item.meta?.fetched || site,
|
||||
publishedDate: item.meta?.lastCrawled,
|
||||
}));
|
||||
}
|
||||
|
||||
case 'yacy': {
|
||||
const yacyResult = await searchYaCy(query);
|
||||
return yacyResult.results.map((item) => ({
|
||||
title: item.title,
|
||||
url: item.url,
|
||||
content: item.content,
|
||||
thumbnail: item.img_src,
|
||||
img_src: item.img_src,
|
||||
iframe_src: null,
|
||||
author: item?.host || site,
|
||||
publishedDate: item?.pubDate,
|
||||
}));
|
||||
}
|
||||
|
||||
case 'bing': {
|
||||
const bingResult = await searchBingAPI(query);
|
||||
return bingResult.results.map((item) => ({
|
||||
title: item.title,
|
||||
url: item.url,
|
||||
content: item.content,
|
||||
thumbnail: item.img_src,
|
||||
img_src: item.img_src,
|
||||
iframe_src: null,
|
||||
author: item?.publisher || site,
|
||||
publishedDate: item?.datePublished,
|
||||
}));
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`Unknown search engine ${searchEngine}`);
|
||||
}
|
||||
}
|
||||
|
||||
router.get('/', async (req, res) => {
|
||||
try {
|
||||
const queries = [
|
||||
{ site: 'businessinsider.com', topic: 'AI' },
|
||||
{ site: 'www.exchangewire.com', topic: 'AI' },
|
||||
{ site: 'yahoo.com', topic: 'AI' },
|
||||
{ site: 'businessinsider.com', topic: 'tech' },
|
||||
{ site: 'www.exchangewire.com', topic: 'tech' },
|
||||
{ site: 'yahoo.com', topic: 'tech' },
|
||||
];
|
||||
|
||||
// Example: Searching UAE-based news sites for "AI" & "Tech"
|
||||
const data = (
|
||||
await Promise.all(
|
||||
queries.map(async ({ site, topic }) => {
|
||||
try {
|
||||
const query = `site:${site} ${topic}`;
|
||||
return await performSearch(query, site);
|
||||
} catch (error) {
|
||||
logger.error(`Error searching ${site}: ${error.message}`);
|
||||
return [];
|
||||
}
|
||||
await Promise.all([
|
||||
// Gulf News
|
||||
searchSearxng('site:gulfnews.com AI', {
|
||||
engines: ['bing news'],
|
||||
pageno: 1,
|
||||
}),
|
||||
)
|
||||
searchSearxng('site:gulfnews.com Tech', {
|
||||
engines: ['bing news'],
|
||||
pageno: 1,
|
||||
}),
|
||||
|
||||
// Khaleej Times
|
||||
searchSearxng('site:khaleejtimes.com AI', {
|
||||
engines: ['bing news'],
|
||||
pageno: 1,
|
||||
}),
|
||||
searchSearxng('site:khaleejtimes.com Tech', {
|
||||
engines: ['bing news'],
|
||||
pageno: 1,
|
||||
}),
|
||||
|
||||
// The National
|
||||
searchSearxng('site:thenationalnews.com AI', {
|
||||
engines: ['bing news'],
|
||||
pageno: 1,
|
||||
}),
|
||||
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'],
|
||||
pageno: 1,
|
||||
}),
|
||||
])
|
||||
)
|
||||
.map((result) => result.results)
|
||||
.flat()
|
||||
.sort(() => Math.random() - 0.5)
|
||||
.filter((item) => item.title && item.url && item.content);
|
||||
// Randomize the order
|
||||
.sort(() => Math.random() - 0.5);
|
||||
|
||||
return res.json({ blogs: data });
|
||||
} catch (err: any) {
|
||||
|
@ -5,17 +5,14 @@ import { getAvailableChatModelProviders } from '../lib/providers';
|
||||
import { HumanMessage, AIMessage } from '@langchain/core/messages';
|
||||
import logger from '../utils/logger';
|
||||
import { ChatOpenAI } from '@langchain/openai';
|
||||
import {
|
||||
getCustomOpenaiApiKey,
|
||||
getCustomOpenaiApiUrl,
|
||||
getCustomOpenaiModelName,
|
||||
} from '../config';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
interface ChatModel {
|
||||
provider: string;
|
||||
model: string;
|
||||
customOpenAIBaseURL?: string;
|
||||
customOpenAIKey?: string;
|
||||
}
|
||||
|
||||
interface ImageSearchBody {
|
||||
@ -47,12 +44,21 @@ router.post('/', async (req, res) => {
|
||||
let llm: BaseChatModel | undefined;
|
||||
|
||||
if (body.chatModel?.provider === 'custom_openai') {
|
||||
if (
|
||||
!body.chatModel?.customOpenAIBaseURL ||
|
||||
!body.chatModel?.customOpenAIKey
|
||||
) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ message: 'Missing custom OpenAI base URL or key' });
|
||||
}
|
||||
|
||||
llm = new ChatOpenAI({
|
||||
modelName: getCustomOpenaiModelName(),
|
||||
openAIApiKey: getCustomOpenaiApiKey(),
|
||||
modelName: body.chatModel.model,
|
||||
openAIApiKey: body.chatModel.customOpenAIKey,
|
||||
temperature: 0.7,
|
||||
configuration: {
|
||||
baseURL: getCustomOpenaiApiUrl(),
|
||||
baseURL: body.chatModel.customOpenAIBaseURL,
|
||||
},
|
||||
}) as unknown as BaseChatModel;
|
||||
} else if (
|
||||
|
@ -21,4 +21,5 @@ router.use('/search', searchRouter);
|
||||
router.use('/discover', discoverRouter);
|
||||
router.use('/uploads', uploadsRouter);
|
||||
|
||||
|
||||
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 logger from '../utils/logger';
|
||||
import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
||||
@ -10,19 +188,14 @@ import {
|
||||
import { searchHandlers } from '../websocket/messageHandler';
|
||||
import { AIMessage, BaseMessage, HumanMessage } from '@langchain/core/messages';
|
||||
import { MetaSearchAgentType } from '../search/metaSearchAgent';
|
||||
import {
|
||||
getCustomOpenaiApiKey,
|
||||
getCustomOpenaiApiUrl,
|
||||
getCustomOpenaiModelName,
|
||||
} from '../config';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
interface chatModel {
|
||||
provider: string;
|
||||
model: string;
|
||||
customOpenAIKey?: string;
|
||||
customOpenAIBaseURL?: string;
|
||||
customOpenAIKey?: string;
|
||||
}
|
||||
|
||||
interface embeddingModel {
|
||||
@ -83,14 +256,21 @@ router.post('/', async (req, res) => {
|
||||
let embeddings: Embeddings | undefined;
|
||||
|
||||
if (body.chatModel?.provider === 'custom_openai') {
|
||||
if (
|
||||
!body.chatModel?.customOpenAIBaseURL ||
|
||||
!body.chatModel?.customOpenAIKey
|
||||
) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ message: 'Missing custom OpenAI base URL or key' });
|
||||
}
|
||||
|
||||
llm = new ChatOpenAI({
|
||||
modelName: body.chatModel?.model || getCustomOpenaiModelName(),
|
||||
openAIApiKey:
|
||||
body.chatModel?.customOpenAIKey || getCustomOpenaiApiKey(),
|
||||
modelName: body.chatModel.model,
|
||||
openAIApiKey: body.chatModel.customOpenAIKey,
|
||||
temperature: 0.7,
|
||||
configuration: {
|
||||
baseURL:
|
||||
body.chatModel?.customOpenAIBaseURL || getCustomOpenaiApiUrl(),
|
||||
baseURL: body.chatModel.customOpenAIBaseURL,
|
||||
},
|
||||
}) as unknown as BaseChatModel;
|
||||
} else if (
|
||||
@ -155,4 +335,4 @@ router.post('/', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
export default router;
|
@ -5,17 +5,14 @@ import { getAvailableChatModelProviders } from '../lib/providers';
|
||||
import { HumanMessage, AIMessage } from '@langchain/core/messages';
|
||||
import logger from '../utils/logger';
|
||||
import { ChatOpenAI } from '@langchain/openai';
|
||||
import {
|
||||
getCustomOpenaiApiKey,
|
||||
getCustomOpenaiApiUrl,
|
||||
getCustomOpenaiModelName,
|
||||
} from '../config';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
interface ChatModel {
|
||||
provider: string;
|
||||
model: string;
|
||||
customOpenAIBaseURL?: string;
|
||||
customOpenAIKey?: string;
|
||||
}
|
||||
|
||||
interface SuggestionsBody {
|
||||
@ -46,12 +43,21 @@ router.post('/', async (req, res) => {
|
||||
let llm: BaseChatModel | undefined;
|
||||
|
||||
if (body.chatModel?.provider === 'custom_openai') {
|
||||
if (
|
||||
!body.chatModel?.customOpenAIBaseURL ||
|
||||
!body.chatModel?.customOpenAIKey
|
||||
) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ message: 'Missing custom OpenAI base URL or key' });
|
||||
}
|
||||
|
||||
llm = new ChatOpenAI({
|
||||
modelName: getCustomOpenaiModelName(),
|
||||
openAIApiKey: getCustomOpenaiApiKey(),
|
||||
modelName: body.chatModel.model,
|
||||
openAIApiKey: body.chatModel.customOpenAIKey,
|
||||
temperature: 0.7,
|
||||
configuration: {
|
||||
baseURL: getCustomOpenaiApiUrl(),
|
||||
baseURL: body.chatModel.customOpenAIBaseURL,
|
||||
},
|
||||
}) as unknown as BaseChatModel;
|
||||
} else if (
|
||||
|
@ -5,17 +5,14 @@ import { HumanMessage, AIMessage } from '@langchain/core/messages';
|
||||
import logger from '../utils/logger';
|
||||
import handleVideoSearch from '../chains/videoSearchAgent';
|
||||
import { ChatOpenAI } from '@langchain/openai';
|
||||
import {
|
||||
getCustomOpenaiApiKey,
|
||||
getCustomOpenaiApiUrl,
|
||||
getCustomOpenaiModelName,
|
||||
} from '../config';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
interface ChatModel {
|
||||
provider: string;
|
||||
model: string;
|
||||
customOpenAIBaseURL?: string;
|
||||
customOpenAIKey?: string;
|
||||
}
|
||||
|
||||
interface VideoSearchBody {
|
||||
@ -47,12 +44,21 @@ router.post('/', async (req, res) => {
|
||||
let llm: BaseChatModel | undefined;
|
||||
|
||||
if (body.chatModel?.provider === 'custom_openai') {
|
||||
if (
|
||||
!body.chatModel?.customOpenAIBaseURL ||
|
||||
!body.chatModel?.customOpenAIKey
|
||||
) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ message: 'Missing custom OpenAI base URL or key' });
|
||||
}
|
||||
|
||||
llm = new ChatOpenAI({
|
||||
modelName: getCustomOpenaiModelName(),
|
||||
openAIApiKey: getCustomOpenaiApiKey(),
|
||||
modelName: body.chatModel.model,
|
||||
openAIApiKey: body.chatModel.customOpenAIKey,
|
||||
temperature: 0.7,
|
||||
configuration: {
|
||||
baseURL: getCustomOpenaiApiUrl(),
|
||||
baseURL: body.chatModel.customOpenAIBaseURL,
|
||||
},
|
||||
}) as unknown as BaseChatModel;
|
||||
} else if (
|
||||
|
@ -17,12 +17,7 @@ import LineListOutputParser from '../lib/outputParsers/listLineOutputParser';
|
||||
import LineOutputParser from '../lib/outputParsers/lineOutputParser';
|
||||
import { getDocumentsFromLinks } from '../utils/documents';
|
||||
import { Document } from 'langchain/document';
|
||||
import { searchSearxng } from '../lib/searchEngines/searxng';
|
||||
import { searchGooglePSE } from '../lib/searchEngines/google_pse';
|
||||
import { searchBingAPI } from '../lib/searchEngines/bing';
|
||||
import { searchBraveAPI } from '../lib/searchEngines/brave';
|
||||
import { searchYaCy } from '../lib/searchEngines/yacy';
|
||||
import { getSearchEngineBackend } from '../config';
|
||||
import { searchSearxng } from '../lib/searxng';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import computeSimilarity from '../utils/computeSimilarity';
|
||||
@ -30,6 +25,7 @@ import formatChatHistoryAsString from '../utils/formatHistory';
|
||||
import eventEmitter from 'events';
|
||||
import { StreamEvent } from '@langchain/core/tracers/log_stream';
|
||||
import { IterableReadableStream } from '@langchain/core/utils/stream';
|
||||
import logger from '../utils/logger'; // Winston logger
|
||||
|
||||
export interface MetaSearchAgentType {
|
||||
searchAndAnswer: (
|
||||
@ -41,7 +37,7 @@ export interface MetaSearchAgentType {
|
||||
fileIds: string[],
|
||||
) => Promise<eventEmitter>;
|
||||
}
|
||||
|
||||
// twst
|
||||
interface Config {
|
||||
searchWeb: boolean;
|
||||
rerank: boolean;
|
||||
@ -63,20 +59,24 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||
|
||||
constructor(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) {
|
||||
(llm as unknown as ChatOpenAI).temperature = 0;
|
||||
logger.info('createSearchRetrieverChain: LLM temperature set to 0');
|
||||
|
||||
return RunnableSequence.from([
|
||||
PromptTemplate.fromTemplate(this.config.queryGeneratorPrompt),
|
||||
llm,
|
||||
this.strParser,
|
||||
RunnableLambda.from(async (input: string) => {
|
||||
logger.info(`Parsed query: ${input}`);
|
||||
|
||||
const linksOutputParser = new LineListOutputParser({
|
||||
key: 'links',
|
||||
});
|
||||
|
||||
const questionOutputParser = new LineOutputParser({
|
||||
key: 'question',
|
||||
});
|
||||
@ -86,21 +86,25 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||
? await questionOutputParser.parse(input)
|
||||
: input;
|
||||
|
||||
logger.info(`Links found: ${JSON.stringify(links, null, 2)}`);
|
||||
logger.info(`Question parsed: ${question}`);
|
||||
|
||||
if (question === 'not_needed') {
|
||||
logger.info('No question needed ("not_needed"), returning empty docs.');
|
||||
return { query: '', docs: [] };
|
||||
}
|
||||
|
||||
if (links.length > 0) {
|
||||
logger.info('Handling user-provided links...');
|
||||
if (question.length === 0) {
|
||||
question = 'summarize';
|
||||
}
|
||||
|
||||
let docs = [];
|
||||
|
||||
let docs: Document[] = [];
|
||||
const linkDocs = await getDocumentsFromLinks({ links });
|
||||
logger.info(`Fetched ${linkDocs.length} documents from user links.`);
|
||||
|
||||
const docGroups: Document[] = [];
|
||||
|
||||
linkDocs.map((doc) => {
|
||||
const URLDocExists = docGroups.find(
|
||||
(d) =>
|
||||
@ -134,65 +138,8 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||
await Promise.all(
|
||||
docGroups.map(async (doc) => {
|
||||
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
|
||||
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.
|
||||
`);
|
||||
... // Summarizer prompt ...
|
||||
`);
|
||||
|
||||
const document = new Document({
|
||||
pageContent: res.content as string,
|
||||
@ -205,40 +152,16 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||
docs.push(document);
|
||||
}),
|
||||
);
|
||||
logger.info('Docs after summarizing user-provided links: ', docs);
|
||||
|
||||
return { query: question, docs: docs };
|
||||
return { query: question, docs };
|
||||
} else {
|
||||
const searchEngine = getSearchEngineBackend();
|
||||
|
||||
let res;
|
||||
switch (searchEngine) {
|
||||
case 'searxng':
|
||||
res = await searchSearxng(question, {
|
||||
language: 'en',
|
||||
engines: this.config.activeEngines,
|
||||
});
|
||||
break;
|
||||
case 'google':
|
||||
res = await searchGooglePSE(question);
|
||||
break;
|
||||
case 'bing':
|
||||
res = await searchBingAPI(question);
|
||||
break;
|
||||
case 'brave':
|
||||
res = await searchBraveAPI(question);
|
||||
break;
|
||||
case 'yacy':
|
||||
res = await searchYaCy(question);
|
||||
break;
|
||||
default:
|
||||
throw new Error(`Unknown search engine ${searchEngine}`);
|
||||
}
|
||||
|
||||
if (!res?.results) {
|
||||
throw new Error(
|
||||
`No results found for search engine: ${searchEngine}`,
|
||||
);
|
||||
}
|
||||
logger.info(`No links specified, searching via Searxng on query: "${question}"`);
|
||||
const res = await searchSearxng(question, {
|
||||
language: 'en',
|
||||
engines: this.config.activeEngines,
|
||||
});
|
||||
logger.info(`Searxng returned ${res.results.length} results.`);
|
||||
|
||||
const documents = res.results.map(
|
||||
(result) =>
|
||||
@ -247,7 +170,7 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||
result.content ||
|
||||
(this.config.activeEngines.includes('youtube')
|
||||
? result.title
|
||||
: '') /* Todo: Implement transcript grabbing using Youtubei (source: https://www.npmjs.com/package/youtubei) */,
|
||||
: ''),
|
||||
metadata: {
|
||||
title: result.title,
|
||||
url: result.url,
|
||||
@ -268,15 +191,15 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||
embeddings: Embeddings,
|
||||
optimizationMode: 'speed' | 'balanced' | 'quality',
|
||||
) {
|
||||
logger.info(`Creating answering chain. Optimization mode: ${optimizationMode}`);
|
||||
return RunnableSequence.from([
|
||||
RunnableMap.from({
|
||||
query: (input: BasicChainInput) => input.query,
|
||||
chat_history: (input: BasicChainInput) => input.chat_history,
|
||||
date: () => new Date().toISOString(),
|
||||
context: RunnableLambda.from(async (input: BasicChainInput) => {
|
||||
const processedHistory = formatChatHistoryAsString(
|
||||
input.chat_history,
|
||||
);
|
||||
logger.info('Retrieving final source documents...');
|
||||
const processedHistory = formatChatHistoryAsString(input.chat_history);
|
||||
|
||||
let docs: Document[] | null = null;
|
||||
let query = input.query;
|
||||
@ -292,6 +215,7 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||
|
||||
query = searchRetrieverResult.query;
|
||||
docs = searchRetrieverResult.docs;
|
||||
logger.info(`Got ${docs.length} docs from searchRetriever.`);
|
||||
}
|
||||
|
||||
const sortedDocs = await this.rerankDocs(
|
||||
@ -301,6 +225,7 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||
embeddings,
|
||||
optimizationMode,
|
||||
);
|
||||
logger.info(`Sorted docs length: ${sortedDocs?.length ?? 0}`);
|
||||
|
||||
return sortedDocs;
|
||||
})
|
||||
@ -328,7 +253,9 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||
embeddings: Embeddings,
|
||||
optimizationMode: 'speed' | 'balanced' | 'quality',
|
||||
) {
|
||||
logger.info(`Reranking. Query="${query}", initial docs=${docs.length}, fileIds=${fileIds.length}`);
|
||||
if (docs.length === 0 && fileIds.length === 0) {
|
||||
logger.info('No docs or fileIds to rerank. Returning empty.');
|
||||
return docs;
|
||||
}
|
||||
|
||||
@ -339,32 +266,34 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||
const contentPath = filePath + '-extracted.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 embeddings = JSON.parse(fs.readFileSync(embeddingsPath, 'utf8'));
|
||||
const fileEmbeddings = JSON.parse(fs.readFileSync(embeddingsPath, 'utf8'));
|
||||
|
||||
const fileSimilaritySearchObject = content.contents.map(
|
||||
(c: string, i) => {
|
||||
return {
|
||||
fileName: content.title,
|
||||
content: c,
|
||||
embeddings: embeddings.embeddings[i],
|
||||
};
|
||||
},
|
||||
(c: string, i: number) => ({
|
||||
fileName: content.title,
|
||||
content: c,
|
||||
embeddings: fileEmbeddings.embeddings[i],
|
||||
}),
|
||||
);
|
||||
|
||||
return fileSimilaritySearchObject;
|
||||
})
|
||||
.flat();
|
||||
|
||||
// If only summarizing, just return top docs
|
||||
if (query.toLocaleLowerCase() === 'summarize') {
|
||||
logger.info(`Query is "summarize". Returning top 15 docs from web sources.`);
|
||||
return docs.slice(0, 15);
|
||||
}
|
||||
|
||||
const docsWithContent = docs.filter(
|
||||
(doc) => doc.pageContent && doc.pageContent.length > 0,
|
||||
);
|
||||
const docsWithContent = docs.filter((doc) => doc.pageContent && doc.pageContent.length > 0);
|
||||
|
||||
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) {
|
||||
const [queryEmbedding] = await Promise.all([
|
||||
embeddings.embedQuery(query),
|
||||
@ -375,14 +304,13 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||
pageContent: fileData.content,
|
||||
metadata: {
|
||||
title: fileData.fileName,
|
||||
url: `File`,
|
||||
url: 'File',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const similarity = filesData.map((fileData, i) => {
|
||||
const sim = computeSimilarity(queryEmbedding, fileData.embeddings);
|
||||
|
||||
return {
|
||||
index: i,
|
||||
similarity: sim,
|
||||
@ -390,28 +318,23 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||
});
|
||||
|
||||
let sortedDocs = similarity
|
||||
.filter(
|
||||
(sim) => sim.similarity > (this.config.rerankThreshold ?? 0.3),
|
||||
)
|
||||
.filter((sim) => sim.similarity > (this.config.rerankThreshold ?? 0.3))
|
||||
.sort((a, b) => b.similarity - a.similarity)
|
||||
.slice(0, 15)
|
||||
.map((sim) => fileDocs[sim.index]);
|
||||
|
||||
sortedDocs =
|
||||
docsWithContent.length > 0 ? sortedDocs.slice(0, 8) : sortedDocs;
|
||||
|
||||
return [
|
||||
...sortedDocs,
|
||||
...docsWithContent.slice(0, 15 - sortedDocs.length),
|
||||
];
|
||||
sortedDocs = docsWithContent.length > 0 ? sortedDocs.slice(0, 8) : sortedDocs;
|
||||
logger.info(`Final sorted docs in 'speed' mode: ${sortedDocs.length}`);
|
||||
|
||||
return [...sortedDocs, ...docsWithContent.slice(0, 15 - sortedDocs.length)];
|
||||
} else {
|
||||
logger.info('No file data, returning top 15 from docsWithContent.');
|
||||
return docsWithContent.slice(0, 15);
|
||||
}
|
||||
} else if (optimizationMode === 'balanced') {
|
||||
logger.info('Reranking in balanced mode.');
|
||||
const [docEmbeddings, queryEmbedding] = await Promise.all([
|
||||
embeddings.embedDocuments(
|
||||
docsWithContent.map((doc) => doc.pageContent),
|
||||
),
|
||||
embeddings.embedDocuments(docsWithContent.map((doc) => doc.pageContent)),
|
||||
embeddings.embedQuery(query),
|
||||
]);
|
||||
|
||||
@ -421,7 +344,7 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||
pageContent: fileData.content,
|
||||
metadata: {
|
||||
title: fileData.fileName,
|
||||
url: `File`,
|
||||
url: 'File',
|
||||
},
|
||||
});
|
||||
}),
|
||||
@ -431,7 +354,6 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||
|
||||
const similarity = docEmbeddings.map((docEmbedding, i) => {
|
||||
const sim = computeSimilarity(queryEmbedding, docEmbedding);
|
||||
|
||||
return {
|
||||
index: i,
|
||||
similarity: sim,
|
||||
@ -444,8 +366,13 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||
.slice(0, 15)
|
||||
.map((sim) => docsWithContent[sim.index]);
|
||||
|
||||
logger.info(`Final sorted docs in 'balanced' mode: ${sortedDocs.length}`);
|
||||
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[]) {
|
||||
@ -461,12 +388,16 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||
stream: IterableReadableStream<StreamEvent>,
|
||||
emitter: eventEmitter,
|
||||
) {
|
||||
logger.info('Starting to stream chain events...');
|
||||
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 (
|
||||
event.event === 'on_chain_end' &&
|
||||
event.name === 'FinalSourceRetriever'
|
||||
) {
|
||||
``;
|
||||
logger.info('FinalSourceRetriever ended, sending docs to front-end...');
|
||||
emitter.emit(
|
||||
'data',
|
||||
JSON.stringify({ type: 'sources', data: event.data.output }),
|
||||
@ -476,6 +407,7 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||
event.event === 'on_chain_stream' &&
|
||||
event.name === 'FinalResponseGenerator'
|
||||
) {
|
||||
logger.info('Response chunk received, streaming to client...');
|
||||
emitter.emit(
|
||||
'data',
|
||||
JSON.stringify({ type: 'response', data: event.data.chunk }),
|
||||
@ -485,9 +417,11 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||
event.event === 'on_chain_end' &&
|
||||
event.name === 'FinalResponseGenerator'
|
||||
) {
|
||||
logger.info('FinalResponseGenerator ended, signaling end of stream.');
|
||||
emitter.emit('end');
|
||||
}
|
||||
}
|
||||
logger.info('Finished streaming chain events.');
|
||||
}
|
||||
|
||||
async searchAndAnswer(
|
||||
@ -500,6 +434,11 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||
) {
|
||||
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(
|
||||
llm,
|
||||
fileIds,
|
||||
@ -507,17 +446,17 @@ class MetaSearchAgent implements MetaSearchAgentType {
|
||||
optimizationMode,
|
||||
);
|
||||
|
||||
const stream = answeringChain.streamEvents(
|
||||
{
|
||||
chat_history: history,
|
||||
query: message,
|
||||
},
|
||||
{
|
||||
version: 'v1',
|
||||
},
|
||||
);
|
||||
|
||||
this.handleStream(stream, emitter);
|
||||
// .streamEvents(...) can throw, so a try/catch can help you catch/log errors
|
||||
try {
|
||||
const stream = answeringChain.streamEvents(
|
||||
{ chat_history: history, query: message },
|
||||
{ version: 'v1' },
|
||||
);
|
||||
this.handleStream(stream, emitter);
|
||||
} catch (error: any) {
|
||||
logger.error(`Error in searchAndAnswer streaming: ${error.message}`);
|
||||
emitter.emit('error', error);
|
||||
}
|
||||
|
||||
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';
|
||||
|
||||
const { combine, timestamp, printf, colorize } = winston.format;
|
||||
|
||||
const logFormat = printf(({ timestamp, level, message }) => {
|
||||
return `${timestamp} [${level.toUpperCase()}]: ${message}`;
|
||||
});
|
||||
|
||||
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: [
|
||||
new winston.transports.Console({
|
||||
format: winston.format.combine(
|
||||
winston.format.colorize(),
|
||||
winston.format.simple(),
|
||||
),
|
||||
}),
|
||||
new winston.transports.File({
|
||||
filename: 'app.log',
|
||||
format: winston.format.combine(
|
||||
winston.format.timestamp(),
|
||||
winston.format.json(),
|
||||
),
|
||||
}),
|
||||
// Console transport ensures Docker sees logs on stdout
|
||||
new winston.transports.Console(),
|
||||
new winston.transports.File({ filename: 'app.log' }),
|
||||
|
||||
// Optional: file transport if you also want to persist logs on the container’s filesystem
|
||||
// new winston.transports.File({ filename: 'app.log' }),
|
||||
],
|
||||
});
|
||||
|
||||
logger.info("✅ Winston logger active, logging to console!");
|
||||
|
||||
export default logger;
|
||||
|
@ -9,17 +9,14 @@ import type { Embeddings } from '@langchain/core/embeddings';
|
||||
import type { IncomingMessage } from 'http';
|
||||
import logger from '../utils/logger';
|
||||
import { ChatOpenAI } from '@langchain/openai';
|
||||
import {
|
||||
getCustomOpenaiApiKey,
|
||||
getCustomOpenaiApiUrl,
|
||||
getCustomOpenaiModelName,
|
||||
} from '../config';
|
||||
|
||||
export const handleConnection = async (
|
||||
ws: WebSocket,
|
||||
request: IncomingMessage,
|
||||
) => {
|
||||
try {
|
||||
logger.info(`🔗 New WebSocket connection from ${request.socket.remoteAddress}`);
|
||||
|
||||
const searchParams = new URL(request.url, `http://${request.headers.host}`)
|
||||
.searchParams;
|
||||
|
||||
@ -28,9 +25,11 @@ export const handleConnection = async (
|
||||
getAvailableEmbeddingModelProviders(),
|
||||
]);
|
||||
|
||||
// Retrieve query parameters
|
||||
const chatModelProvider =
|
||||
searchParams.get('chatModelProvider') ||
|
||||
Object.keys(chatModelProviders)[0];
|
||||
|
||||
const chatModel =
|
||||
searchParams.get('chatModel') ||
|
||||
Object.keys(chatModelProviders[chatModelProvider])[0];
|
||||
@ -38,47 +37,52 @@ export const handleConnection = async (
|
||||
const embeddingModelProvider =
|
||||
searchParams.get('embeddingModelProvider') ||
|
||||
Object.keys(embeddingModelProviders)[0];
|
||||
|
||||
const embeddingModel =
|
||||
searchParams.get('embeddingModel') ||
|
||||
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 embeddings: Embeddings | undefined;
|
||||
|
||||
// Handle model selection
|
||||
if (
|
||||
chatModelProviders[chatModelProvider] &&
|
||||
chatModelProviders[chatModelProvider][chatModel] &&
|
||||
chatModelProvider != 'custom_openai'
|
||||
chatModelProvider !== 'custom_openai'
|
||||
) {
|
||||
llm = chatModelProviders[chatModelProvider][chatModel]
|
||||
.model as unknown as BaseChatModel | undefined;
|
||||
} else if (chatModelProvider == 'custom_openai') {
|
||||
const customOpenaiApiKey = getCustomOpenaiApiKey();
|
||||
const customOpenaiApiUrl = getCustomOpenaiApiUrl();
|
||||
const customOpenaiModelName = getCustomOpenaiModelName();
|
||||
|
||||
if (customOpenaiApiKey && customOpenaiApiUrl && customOpenaiModelName) {
|
||||
llm = new ChatOpenAI({
|
||||
modelName: customOpenaiModelName,
|
||||
openAIApiKey: customOpenaiApiKey,
|
||||
temperature: 0.7,
|
||||
configuration: {
|
||||
baseURL: customOpenaiApiUrl,
|
||||
},
|
||||
}) as unknown as BaseChatModel;
|
||||
}
|
||||
} else if (chatModelProvider === 'custom_openai') {
|
||||
logger.info(`🛠 Using custom OpenAI model: ${chatModel}`);
|
||||
llm = new ChatOpenAI({
|
||||
modelName: chatModel,
|
||||
openAIApiKey: searchParams.get('openAIApiKey'),
|
||||
temperature: 0.7,
|
||||
configuration: {
|
||||
baseURL: searchParams.get('openAIBaseURL'),
|
||||
},
|
||||
}) as unknown as BaseChatModel;
|
||||
}
|
||||
|
||||
if (
|
||||
embeddingModelProviders[embeddingModelProvider] &&
|
||||
embeddingModelProviders[embeddingModelProvider][embeddingModel]
|
||||
) {
|
||||
embeddings = embeddingModelProviders[embeddingModelProvider][
|
||||
embeddingModel
|
||||
].model as Embeddings | undefined;
|
||||
embeddings = embeddingModelProviders[embeddingModelProvider][embeddingModel]
|
||||
.model as Embeddings | undefined;
|
||||
}
|
||||
|
||||
if (!llm || !embeddings) {
|
||||
logger.error(`❌ Invalid LLM or embeddings model selection!`);
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: 'error',
|
||||
@ -87,10 +91,15 @@ export const handleConnection = async (
|
||||
}),
|
||||
);
|
||||
ws.close();
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info(`✅ WebSocket setup complete - Ready for messages`);
|
||||
|
||||
// Send an initial "open" signal once connection is ready
|
||||
const interval = setInterval(() => {
|
||||
if (ws.readyState === ws.OPEN) {
|
||||
logger.debug(`📡 Sending initial 'open' signal to client`);
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: 'signal',
|
||||
@ -101,14 +110,19 @@ export const handleConnection = async (
|
||||
}
|
||||
}, 5);
|
||||
|
||||
ws.on(
|
||||
'message',
|
||||
async (message) =>
|
||||
await handleMessage(message.toString(), ws, llm, embeddings),
|
||||
);
|
||||
// Handle incoming messages
|
||||
ws.on('message', async (message) => {
|
||||
logger.info(`📩 Received message from client: ${message.toString()}`);
|
||||
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) {
|
||||
logger.error(`❌ WebSocket error: ${err.message}`);
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: 'error',
|
||||
@ -117,6 +131,5 @@ export const handleConnection = async (
|
||||
}),
|
||||
);
|
||||
ws.close();
|
||||
logger.error(err);
|
||||
}
|
||||
};
|
||||
|
@ -134,6 +134,8 @@ const handleEmitterEvents = (
|
||||
});
|
||||
emitter.on('error', (data) => {
|
||||
const parsedData = JSON.parse(data);
|
||||
logger.debug(`📡 Emitter received data: ${JSON.stringify(parsedData)}`);
|
||||
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: 'error',
|
||||
@ -151,6 +153,7 @@ export const handleMessage = async (
|
||||
embeddings: Embeddings,
|
||||
) => {
|
||||
try {
|
||||
logger.debug('Handling message...');
|
||||
const parsedWSMessage = JSON.parse(message) as WSMessage;
|
||||
const parsedMessage = parsedWSMessage.message;
|
||||
|
||||
|
@ -14,9 +14,9 @@ const montserrat = Montserrat({
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Perplexica - Chat with the internet',
|
||||
title: 'gochat247 - aibot - Chat with the internet',
|
||||
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({
|
||||
|
@ -2,7 +2,7 @@ import { Metadata } from 'next';
|
||||
import React from 'react';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Library - Perplexica',
|
||||
title: 'Library - gochat247 - aibot',
|
||||
};
|
||||
|
||||
const Layout = ({ children }: { children: React.ReactNode }) => {
|
||||
|
@ -3,8 +3,8 @@ import { Metadata } from 'next';
|
||||
import { Suspense } from 'react';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Chat - Perplexica',
|
||||
description: 'Chat with the internet, chat with Perplexica.',
|
||||
title: 'Chat - gochat247 - aibot',
|
||||
description: 'Chat with the internet, chat with gochat247 - aibot.',
|
||||
};
|
||||
|
||||
const Home = () => {
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -10,7 +10,7 @@ import { toast } from 'sonner';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { getSuggestions } from '@/lib/actions';
|
||||
import { Settings } from 'lucide-react';
|
||||
import Link from 'next/link';
|
||||
import SettingsDialog from './SettingsDialog';
|
||||
import NextError from 'next/error';
|
||||
|
||||
export type Message = {
|
||||
@ -40,7 +40,6 @@ const useSocket = (
|
||||
const isCleaningUpRef = useRef(false);
|
||||
const MAX_RETRIES = 3;
|
||||
const INITIAL_BACKOFF = 1000; // 1 second
|
||||
const isConnectionErrorRef = useRef(false);
|
||||
|
||||
const getBackoffDelay = (retryCount: number) => {
|
||||
return Math.min(INITIAL_BACKOFF * Math.pow(2, retryCount), 10000); // Cap at 10 seconds
|
||||
@ -59,17 +58,14 @@ const useSocket = (
|
||||
let embeddingModelProvider = localStorage.getItem(
|
||||
'embeddingModelProvider',
|
||||
);
|
||||
|
||||
const autoImageSearch = localStorage.getItem('autoImageSearch');
|
||||
const autoVideoSearch = localStorage.getItem('autoVideoSearch');
|
||||
|
||||
if (!autoImageSearch) {
|
||||
localStorage.setItem('autoImageSearch', 'true');
|
||||
}
|
||||
|
||||
if (!autoVideoSearch) {
|
||||
localStorage.setItem('autoVideoSearch', 'false');
|
||||
}
|
||||
let openAIBaseURL =
|
||||
chatModelProvider === 'custom_openai'
|
||||
? localStorage.getItem('openAIBaseURL')
|
||||
: null;
|
||||
let openAIPIKey =
|
||||
chatModelProvider === 'custom_openai'
|
||||
? localStorage.getItem('openAIApiKey')
|
||||
: null;
|
||||
|
||||
const providers = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/models`,
|
||||
@ -98,13 +94,21 @@ const useSocket = (
|
||||
chatModelProvider =
|
||||
chatModelProvider || Object.keys(chatModelProviders)[0];
|
||||
|
||||
chatModel = Object.keys(chatModelProviders[chatModelProvider])[0];
|
||||
if (chatModelProvider === 'custom_openai') {
|
||||
toast.error(
|
||||
'Seems like you are using the custom OpenAI provider, please open the settings and enter a model name to use.',
|
||||
);
|
||||
setError(true);
|
||||
return;
|
||||
} else {
|
||||
chatModel = Object.keys(chatModelProviders[chatModelProvider])[0];
|
||||
|
||||
if (
|
||||
!chatModelProviders ||
|
||||
Object.keys(chatModelProviders).length === 0
|
||||
)
|
||||
return toast.error('No chat models available');
|
||||
if (
|
||||
!chatModelProviders ||
|
||||
Object.keys(chatModelProviders).length === 0
|
||||
)
|
||||
return toast.error('No chat models available');
|
||||
}
|
||||
}
|
||||
|
||||
if (!embeddingModel || !embeddingModelProvider) {
|
||||
@ -135,7 +139,9 @@ const useSocket = (
|
||||
|
||||
if (
|
||||
Object.keys(chatModelProviders).length > 0 &&
|
||||
!chatModelProviders[chatModelProvider]
|
||||
(((!openAIBaseURL || !openAIPIKey) &&
|
||||
chatModelProvider === 'custom_openai') ||
|
||||
!chatModelProviders[chatModelProvider])
|
||||
) {
|
||||
const chatModelProvidersKeys = Object.keys(chatModelProviders);
|
||||
chatModelProvider =
|
||||
@ -143,11 +149,23 @@ const useSocket = (
|
||||
(key) => Object.keys(chatModelProviders[key]).length > 0,
|
||||
) || chatModelProvidersKeys[0];
|
||||
|
||||
if (
|
||||
chatModelProvider === 'custom_openai' &&
|
||||
(!openAIBaseURL || !openAIPIKey)
|
||||
) {
|
||||
toast.error(
|
||||
'Seems like you are using the custom OpenAI provider, please open the settings and configure the API key and base URL',
|
||||
);
|
||||
setError(true);
|
||||
return;
|
||||
}
|
||||
|
||||
localStorage.setItem('chatModelProvider', chatModelProvider);
|
||||
}
|
||||
|
||||
if (
|
||||
chatModelProvider &&
|
||||
(!openAIBaseURL || !openAIPIKey) &&
|
||||
!chatModelProviders[chatModelProvider][chatModel]
|
||||
) {
|
||||
chatModel = Object.keys(
|
||||
@ -233,8 +251,6 @@ const useSocket = (
|
||||
console.debug(new Date(), 'ws:connected');
|
||||
}
|
||||
if (data.type === 'error') {
|
||||
isConnectionErrorRef.current = true;
|
||||
setError(true);
|
||||
toast.error(data.data);
|
||||
}
|
||||
});
|
||||
@ -249,7 +265,7 @@ const useSocket = (
|
||||
clearTimeout(timeoutId);
|
||||
setIsWSReady(false);
|
||||
console.debug(new Date(), 'ws:disconnected');
|
||||
if (!isCleaningUpRef.current && !isConnectionErrorRef.current) {
|
||||
if (!isCleaningUpRef.current) {
|
||||
toast.error('Connection lost. Attempting to reconnect...');
|
||||
attemptReconnect();
|
||||
}
|
||||
@ -579,17 +595,6 @@ const ChatWindow = ({ id }: { id?: string }) => {
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const autoImageSearch = localStorage.getItem('autoImageSearch');
|
||||
const autoVideoSearch = localStorage.getItem('autoVideoSearch');
|
||||
|
||||
if (autoImageSearch === 'true') {
|
||||
document.getElementById('search-images')?.click();
|
||||
}
|
||||
|
||||
if (autoVideoSearch === 'true') {
|
||||
document.getElementById('search-videos')?.click();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@ -624,15 +629,17 @@ const ChatWindow = ({ id }: { id?: string }) => {
|
||||
return (
|
||||
<div className="relative">
|
||||
<div className="absolute w-full flex flex-row items-center justify-end mr-5 mt-5">
|
||||
<Link href="/settings">
|
||||
<Settings className="cursor-pointer lg:hidden" />
|
||||
</Link>
|
||||
<Settings
|
||||
className="cursor-pointer lg:hidden"
|
||||
onClick={() => setIsSettingsOpen(true)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col items-center justify-center min-h-screen">
|
||||
<p className="dark:text-white/70 text-black/70 text-sm">
|
||||
Failed to connect to the server. Please try again later.
|
||||
</p>
|
||||
</div>
|
||||
<SettingsDialog isOpen={isSettingsOpen} setIsOpen={setIsSettingsOpen} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
@ -1,8 +1,8 @@
|
||||
import { Settings } from 'lucide-react';
|
||||
import EmptyChatMessageInput from './EmptyChatMessageInput';
|
||||
import SettingsDialog from './SettingsDialog';
|
||||
import { useState } from 'react';
|
||||
import { File } from './ChatWindow';
|
||||
import Link from 'next/link';
|
||||
|
||||
const EmptyChat = ({
|
||||
sendMessage,
|
||||
@ -29,14 +29,16 @@ const EmptyChat = ({
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<SettingsDialog isOpen={isSettingsOpen} setIsOpen={setIsSettingsOpen} />
|
||||
<div className="absolute w-full flex flex-row items-center justify-end mr-5 mt-5">
|
||||
<Link href="/settings">
|
||||
<Settings className="cursor-pointer lg:hidden" />
|
||||
</Link>
|
||||
<Settings
|
||||
className="cursor-pointer lg:hidden"
|
||||
onClick={() => setIsSettingsOpen(true)}
|
||||
/>
|
||||
</div>
|
||||
<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">
|
||||
Research begins here.
|
||||
gochat247 - aibot : knowledge with some privacy
|
||||
</h2>
|
||||
<EmptyChatMessageInput
|
||||
sendMessage={sendMessage}
|
||||
|
@ -68,13 +68,7 @@ const MessageBox = ({
|
||||
return (
|
||||
<div>
|
||||
{message.role === 'user' && (
|
||||
<div
|
||||
className={cn(
|
||||
'w-full',
|
||||
messageIndex === 0 ? 'pt-16' : 'pt-8',
|
||||
'break-words',
|
||||
)}
|
||||
>
|
||||
<div className={cn('w-full', messageIndex === 0 ? 'pt-16' : 'pt-8')}>
|
||||
<h2 className="text-black dark:text-white font-medium text-3xl lg:w-9/12">
|
||||
{message.content}
|
||||
</h2>
|
||||
|
@ -110,7 +110,7 @@ const Attach = ({
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileInputRef.current.click()}
|
||||
className="flex flex-row items-center space-x-1 text-black/70 dark:text-white/70 hover:text-black hover:dark:text-white transition duration-200"
|
||||
className="flex flex-row items-center space-x-1 text-white/70 hover:text-white transition duration-200"
|
||||
>
|
||||
<input
|
||||
type="file"
|
||||
@ -128,7 +128,7 @@ const Attach = ({
|
||||
setFiles([]);
|
||||
setFileIds([]);
|
||||
}}
|
||||
className="flex flex-row items-center space-x-1 text-black/70 dark:text-white/70 hover:text-black hover:dark:text-white transition duration-200"
|
||||
className="flex flex-row items-center space-x-1 text-white/70 hover:text-white transition duration-200"
|
||||
>
|
||||
<Trash size={14} />
|
||||
<p className="text-xs">Clear</p>
|
||||
@ -145,7 +145,7 @@ const Attach = ({
|
||||
<div className="bg-dark-100 flex items-center justify-center w-10 h-10 rounded-md">
|
||||
<File size={16} className="text-white/70" />
|
||||
</div>
|
||||
<p className="text-black/70 dark:text-white/70 text-sm">
|
||||
<p className="text-white/70 text-sm">
|
||||
{file.fileName.length > 25
|
||||
? file.fileName.replace(/\.\w+$/, '').substring(0, 25) +
|
||||
'...' +
|
||||
|
@ -82,7 +82,7 @@ const AttachSmall = ({
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileInputRef.current.click()}
|
||||
className="flex flex-row items-center space-x-1 text-black/70 dark:text-white/70 hover:text-black hover:dark:text-white transition duration-200"
|
||||
className="flex flex-row items-center space-x-1 text-white/70 hover:text-white transition duration-200"
|
||||
>
|
||||
<input
|
||||
type="file"
|
||||
@ -100,7 +100,7 @@ const AttachSmall = ({
|
||||
setFiles([]);
|
||||
setFileIds([]);
|
||||
}}
|
||||
className="flex flex-row items-center space-x-1 text-black/70 dark:text-white/70 hover:text-black hover:dark:text-white transition duration-200"
|
||||
className="flex flex-row items-center space-x-1 text-white/70 hover:text-white transition duration-200"
|
||||
>
|
||||
<Trash size={14} />
|
||||
<p className="text-xs">Clear</p>
|
||||
@ -117,7 +117,7 @@ const AttachSmall = ({
|
||||
<div className="bg-dark-100 flex items-center justify-center w-10 h-10 rounded-md">
|
||||
<File size={16} className="text-white/70" />
|
||||
</div>
|
||||
<p className="text-black/70 dark:text-white/70 text-sm">
|
||||
<p className="text-white/70 text-sm">
|
||||
{file.fileName.length > 25
|
||||
? file.fileName.replace(/\.\w+$/, '').substring(0, 25) +
|
||||
'...' +
|
||||
|
@ -27,7 +27,6 @@ const SearchImages = ({
|
||||
<>
|
||||
{!loading && images === null && (
|
||||
<button
|
||||
id="search-images"
|
||||
onClick={async () => {
|
||||
setLoading(true);
|
||||
|
||||
|
@ -42,7 +42,6 @@ const Searchvideos = ({
|
||||
<>
|
||||
{!loading && videos === null && (
|
||||
<button
|
||||
id="search-videos"
|
||||
onClick={async () => {
|
||||
setLoading(true);
|
||||
|
||||
|
528
ui/components/SettingsDialog.tsx
Normal file
528
ui/components/SettingsDialog.tsx
Normal file
@ -0,0 +1,528 @@
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
Dialog,
|
||||
DialogPanel,
|
||||
DialogTitle,
|
||||
Transition,
|
||||
TransitionChild,
|
||||
} from '@headlessui/react';
|
||||
import { CloudUpload, RefreshCcw, RefreshCw } from 'lucide-react';
|
||||
import React, {
|
||||
Fragment,
|
||||
useEffect,
|
||||
useState,
|
||||
type SelectHTMLAttributes,
|
||||
} from 'react';
|
||||
import ThemeSwitcher from './theme/Switcher';
|
||||
|
||||
interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {}
|
||||
|
||||
const Input = ({ className, ...restProps }: InputProps) => {
|
||||
return (
|
||||
<input
|
||||
{...restProps}
|
||||
className={cn(
|
||||
'bg-light-secondary dark:bg-dark-secondary px-3 py-2 flex items-center overflow-hidden border border-light-200 dark:border-dark-200 dark:text-white rounded-lg text-sm',
|
||||
className,
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
interface SelectProps extends SelectHTMLAttributes<HTMLSelectElement> {
|
||||
options: { value: string; label: string; disabled?: boolean }[];
|
||||
}
|
||||
|
||||
export const Select = ({ className, options, ...restProps }: SelectProps) => {
|
||||
return (
|
||||
<select
|
||||
{...restProps}
|
||||
className={cn(
|
||||
'bg-light-secondary dark:bg-dark-secondary px-3 py-2 flex items-center overflow-hidden border border-light-200 dark:border-dark-200 dark:text-white rounded-lg text-sm',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{options.map(({ label, value, disabled }) => {
|
||||
return (
|
||||
<option key={value} value={value} disabled={disabled}>
|
||||
{label}
|
||||
</option>
|
||||
);
|
||||
})}
|
||||
</select>
|
||||
);
|
||||
};
|
||||
|
||||
interface SettingsType {
|
||||
chatModelProviders: {
|
||||
[key: string]: [Record<string, any>];
|
||||
};
|
||||
embeddingModelProviders: {
|
||||
[key: string]: [Record<string, any>];
|
||||
};
|
||||
openaiApiKey: string;
|
||||
groqApiKey: string;
|
||||
anthropicApiKey: string;
|
||||
geminiApiKey: string;
|
||||
ollamaApiUrl: string;
|
||||
}
|
||||
|
||||
const SettingsDialog = ({
|
||||
isOpen,
|
||||
setIsOpen,
|
||||
}: {
|
||||
isOpen: boolean;
|
||||
setIsOpen: (isOpen: boolean) => void;
|
||||
}) => {
|
||||
const [config, setConfig] = useState<SettingsType | null>(null);
|
||||
const [chatModels, setChatModels] = useState<Record<string, any>>({});
|
||||
const [embeddingModels, setEmbeddingModels] = useState<Record<string, any>>(
|
||||
{},
|
||||
);
|
||||
const [selectedChatModelProvider, setSelectedChatModelProvider] = useState<
|
||||
string | null
|
||||
>(null);
|
||||
const [selectedChatModel, setSelectedChatModel] = useState<string | null>(
|
||||
null,
|
||||
);
|
||||
const [selectedEmbeddingModelProvider, setSelectedEmbeddingModelProvider] =
|
||||
useState<string | null>(null);
|
||||
const [selectedEmbeddingModel, setSelectedEmbeddingModel] = useState<
|
||||
string | null
|
||||
>(null);
|
||||
const [customOpenAIApiKey, setCustomOpenAIApiKey] = useState<string>('');
|
||||
const [customOpenAIBaseURL, setCustomOpenAIBaseURL] = useState<string>('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isUpdating, setIsUpdating] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
const fetchConfig = async () => {
|
||||
setIsLoading(true);
|
||||
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/config`, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
const data = (await res.json()) as SettingsType;
|
||||
setConfig(data);
|
||||
|
||||
const chatModelProvidersKeys = Object.keys(
|
||||
data.chatModelProviders || {},
|
||||
);
|
||||
const embeddingModelProvidersKeys = Object.keys(
|
||||
data.embeddingModelProviders || {},
|
||||
);
|
||||
|
||||
const defaultChatModelProvider =
|
||||
chatModelProvidersKeys.length > 0 ? chatModelProvidersKeys[0] : '';
|
||||
const defaultEmbeddingModelProvider =
|
||||
embeddingModelProvidersKeys.length > 0
|
||||
? embeddingModelProvidersKeys[0]
|
||||
: '';
|
||||
|
||||
const chatModelProvider =
|
||||
localStorage.getItem('chatModelProvider') ||
|
||||
defaultChatModelProvider ||
|
||||
'';
|
||||
const chatModel =
|
||||
localStorage.getItem('chatModel') ||
|
||||
(data.chatModelProviders &&
|
||||
data.chatModelProviders[chatModelProvider]?.length > 0
|
||||
? data.chatModelProviders[chatModelProvider][0].name
|
||||
: undefined) ||
|
||||
'';
|
||||
const embeddingModelProvider =
|
||||
localStorage.getItem('embeddingModelProvider') ||
|
||||
defaultEmbeddingModelProvider ||
|
||||
'';
|
||||
const embeddingModel =
|
||||
localStorage.getItem('embeddingModel') ||
|
||||
(data.embeddingModelProviders &&
|
||||
data.embeddingModelProviders[embeddingModelProvider]?.[0].name) ||
|
||||
'';
|
||||
|
||||
setSelectedChatModelProvider(chatModelProvider);
|
||||
setSelectedChatModel(chatModel);
|
||||
setSelectedEmbeddingModelProvider(embeddingModelProvider);
|
||||
setSelectedEmbeddingModel(embeddingModel);
|
||||
setCustomOpenAIApiKey(localStorage.getItem('openAIApiKey') || '');
|
||||
setCustomOpenAIBaseURL(localStorage.getItem('openAIBaseURL') || '');
|
||||
setChatModels(data.chatModelProviders || {});
|
||||
setEmbeddingModels(data.embeddingModelProviders || {});
|
||||
setIsLoading(false);
|
||||
};
|
||||
|
||||
fetchConfig();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isOpen]);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
setIsUpdating(true);
|
||||
|
||||
try {
|
||||
await fetch(`${process.env.NEXT_PUBLIC_API_URL}/config`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(config),
|
||||
});
|
||||
|
||||
localStorage.setItem('chatModelProvider', selectedChatModelProvider!);
|
||||
localStorage.setItem('chatModel', selectedChatModel!);
|
||||
localStorage.setItem(
|
||||
'embeddingModelProvider',
|
||||
selectedEmbeddingModelProvider!,
|
||||
);
|
||||
localStorage.setItem('embeddingModel', selectedEmbeddingModel!);
|
||||
localStorage.setItem('openAIApiKey', customOpenAIApiKey!);
|
||||
localStorage.setItem('openAIBaseURL', customOpenAIBaseURL!);
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
} finally {
|
||||
setIsUpdating(false);
|
||||
setIsOpen(false);
|
||||
|
||||
window.location.reload();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Transition appear show={isOpen} as={Fragment}>
|
||||
<Dialog
|
||||
as="div"
|
||||
className="relative z-50"
|
||||
onClose={() => setIsOpen(false)}
|
||||
>
|
||||
<TransitionChild
|
||||
as={Fragment}
|
||||
enter="ease-out duration-300"
|
||||
enterFrom="opacity-0"
|
||||
enterTo="opacity-100"
|
||||
leave="ease-in duration-200"
|
||||
leaveFrom="opacity-100"
|
||||
leaveTo="opacity-0"
|
||||
>
|
||||
<div className="fixed inset-0 bg-white/50 dark:bg-black/50" />
|
||||
</TransitionChild>
|
||||
<div className="fixed inset-0 overflow-y-auto">
|
||||
<div className="flex min-h-full items-center justify-center p-4 text-center">
|
||||
<TransitionChild
|
||||
as={Fragment}
|
||||
enter="ease-out duration-200"
|
||||
enterFrom="opacity-0 scale-95"
|
||||
enterTo="opacity-100 scale-100"
|
||||
leave="ease-in duration-100"
|
||||
leaveFrom="opacity-100 scale-200"
|
||||
leaveTo="opacity-0 scale-95"
|
||||
>
|
||||
<DialogPanel className="w-full max-w-md transform rounded-2xl bg-light-secondary dark:bg-dark-secondary border border-light-200 dark:border-dark-200 p-6 text-left align-middle shadow-xl transition-all">
|
||||
<DialogTitle className="text-xl font-medium leading-6 dark:text-white">
|
||||
Settings
|
||||
</DialogTitle>
|
||||
{config && !isLoading && (
|
||||
<div className="flex flex-col space-y-4 mt-6">
|
||||
<div className="flex flex-col space-y-1">
|
||||
<p className="text-black/70 dark:text-white/70 text-sm">
|
||||
Theme
|
||||
</p>
|
||||
<ThemeSwitcher />
|
||||
</div>
|
||||
{config.chatModelProviders && (
|
||||
<div className="flex flex-col space-y-1">
|
||||
<p className="text-black/70 dark:text-white/70 text-sm">
|
||||
Chat model Provider
|
||||
</p>
|
||||
<Select
|
||||
value={selectedChatModelProvider ?? undefined}
|
||||
onChange={(e) => {
|
||||
setSelectedChatModelProvider(e.target.value);
|
||||
if (e.target.value === 'custom_openai') {
|
||||
setSelectedChatModel('');
|
||||
} else {
|
||||
setSelectedChatModel(
|
||||
config.chatModelProviders[e.target.value][0]
|
||||
.name,
|
||||
);
|
||||
}
|
||||
}}
|
||||
options={Object.keys(config.chatModelProviders).map(
|
||||
(provider) => ({
|
||||
value: provider,
|
||||
label:
|
||||
provider.charAt(0).toUpperCase() +
|
||||
provider.slice(1),
|
||||
}),
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{selectedChatModelProvider &&
|
||||
selectedChatModelProvider != 'custom_openai' && (
|
||||
<div className="flex flex-col space-y-1">
|
||||
<p className="text-black/70 dark:text-white/70 text-sm">
|
||||
Chat Model
|
||||
</p>
|
||||
<Select
|
||||
value={selectedChatModel ?? undefined}
|
||||
onChange={(e) =>
|
||||
setSelectedChatModel(e.target.value)
|
||||
}
|
||||
options={(() => {
|
||||
const chatModelProvider =
|
||||
config.chatModelProviders[
|
||||
selectedChatModelProvider
|
||||
];
|
||||
|
||||
return chatModelProvider
|
||||
? chatModelProvider.length > 0
|
||||
? chatModelProvider.map((model) => ({
|
||||
value: model.name,
|
||||
label: model.displayName,
|
||||
}))
|
||||
: [
|
||||
{
|
||||
value: '',
|
||||
label: 'No models available',
|
||||
disabled: true,
|
||||
},
|
||||
]
|
||||
: [
|
||||
{
|
||||
value: '',
|
||||
label:
|
||||
'Invalid provider, please check backend logs',
|
||||
disabled: true,
|
||||
},
|
||||
];
|
||||
})()}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{selectedChatModelProvider &&
|
||||
selectedChatModelProvider === 'custom_openai' && (
|
||||
<>
|
||||
<div className="flex flex-col space-y-1">
|
||||
<p className="text-black/70 dark:text-white/70 text-sm">
|
||||
Model name
|
||||
</p>
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Model name"
|
||||
defaultValue={selectedChatModel!}
|
||||
onChange={(e) =>
|
||||
setSelectedChatModel(e.target.value)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col space-y-1">
|
||||
<p className="text-black/70 dark:text-white/70 text-sm">
|
||||
Custom OpenAI API Key
|
||||
</p>
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Custom OpenAI API Key"
|
||||
defaultValue={customOpenAIApiKey!}
|
||||
onChange={(e) =>
|
||||
setCustomOpenAIApiKey(e.target.value)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col space-y-1">
|
||||
<p className="text-black/70 dark:text-white/70 text-sm">
|
||||
Custom OpenAI Base URL
|
||||
</p>
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Custom OpenAI Base URL"
|
||||
defaultValue={customOpenAIBaseURL!}
|
||||
onChange={(e) =>
|
||||
setCustomOpenAIBaseURL(e.target.value)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{/* Embedding models */}
|
||||
{config.embeddingModelProviders && (
|
||||
<div className="flex flex-col space-y-1">
|
||||
<p className="text-black/70 dark:text-white/70 text-sm">
|
||||
Embedding model Provider
|
||||
</p>
|
||||
<Select
|
||||
value={selectedEmbeddingModelProvider ?? undefined}
|
||||
onChange={(e) => {
|
||||
setSelectedEmbeddingModelProvider(e.target.value);
|
||||
setSelectedEmbeddingModel(
|
||||
config.embeddingModelProviders[e.target.value][0]
|
||||
.name,
|
||||
);
|
||||
}}
|
||||
options={Object.keys(
|
||||
config.embeddingModelProviders,
|
||||
).map((provider) => ({
|
||||
label:
|
||||
provider.charAt(0).toUpperCase() +
|
||||
provider.slice(1),
|
||||
value: provider,
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{selectedEmbeddingModelProvider && (
|
||||
<div className="flex flex-col space-y-1">
|
||||
<p className="text-black/70 dark:text-white/70 text-sm">
|
||||
Embedding Model
|
||||
</p>
|
||||
<Select
|
||||
value={selectedEmbeddingModel ?? undefined}
|
||||
onChange={(e) =>
|
||||
setSelectedEmbeddingModel(e.target.value)
|
||||
}
|
||||
options={(() => {
|
||||
const embeddingModelProvider =
|
||||
config.embeddingModelProviders[
|
||||
selectedEmbeddingModelProvider
|
||||
];
|
||||
|
||||
return embeddingModelProvider
|
||||
? embeddingModelProvider.length > 0
|
||||
? embeddingModelProvider.map((model) => ({
|
||||
label: model.displayName,
|
||||
value: model.name,
|
||||
}))
|
||||
: [
|
||||
{
|
||||
label: 'No embedding models available',
|
||||
value: '',
|
||||
disabled: true,
|
||||
},
|
||||
]
|
||||
: [
|
||||
{
|
||||
label:
|
||||
'Invalid provider, please check backend logs',
|
||||
value: '',
|
||||
disabled: true,
|
||||
},
|
||||
];
|
||||
})()}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-col space-y-1">
|
||||
<p className="text-black/70 dark:text-white/70 text-sm">
|
||||
OpenAI API Key
|
||||
</p>
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="OpenAI API Key"
|
||||
defaultValue={config.openaiApiKey}
|
||||
onChange={(e) =>
|
||||
setConfig({
|
||||
...config,
|
||||
openaiApiKey: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col space-y-1">
|
||||
<p className="text-black/70 dark:text-white/70 text-sm">
|
||||
Ollama API URL
|
||||
</p>
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Ollama API URL"
|
||||
defaultValue={config.ollamaApiUrl}
|
||||
onChange={(e) =>
|
||||
setConfig({
|
||||
...config,
|
||||
ollamaApiUrl: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col space-y-1">
|
||||
<p className="text-black/70 dark:text-white/70 text-sm">
|
||||
GROQ API Key
|
||||
</p>
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="GROQ API Key"
|
||||
defaultValue={config.groqApiKey}
|
||||
onChange={(e) =>
|
||||
setConfig({
|
||||
...config,
|
||||
groqApiKey: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col space-y-1">
|
||||
<p className="text-black/70 dark:text-white/70 text-sm">
|
||||
Anthropic API Key
|
||||
</p>
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Anthropic API key"
|
||||
defaultValue={config.anthropicApiKey}
|
||||
onChange={(e) =>
|
||||
setConfig({
|
||||
...config,
|
||||
anthropicApiKey: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col space-y-1">
|
||||
<p className="text-black/70 dark:text-white/70 text-sm">
|
||||
Gemini API Key
|
||||
</p>
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Gemini API key"
|
||||
defaultValue={config.geminiApiKey}
|
||||
onChange={(e) =>
|
||||
setConfig({
|
||||
...config,
|
||||
geminiApiKey: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{isLoading && (
|
||||
<div className="w-full flex items-center justify-center mt-6 text-black/70 dark:text-white/70 py-6">
|
||||
<RefreshCcw className="animate-spin" />
|
||||
</div>
|
||||
)}
|
||||
<div className="w-full mt-6 space-y-2">
|
||||
<p className="text-xs text-black/50 dark:text-white/50">
|
||||
We'll refresh the page after updating the settings.
|
||||
</p>
|
||||
<button
|
||||
onClick={handleSubmit}
|
||||
className="bg-[#24A0ED] flex flex-row items-center space-x-2 text-white disabled:text-white/50 hover:bg-opacity-85 transition duration-100 disabled:bg-[#ececec21] rounded-full px-4 py-2"
|
||||
disabled={isLoading || isUpdating}
|
||||
>
|
||||
{isUpdating ? (
|
||||
<RefreshCw size={20} className="animate-spin" />
|
||||
) : (
|
||||
<CloudUpload size={20} />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</DialogPanel>
|
||||
</TransitionChild>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
</Transition>
|
||||
);
|
||||
};
|
||||
|
||||
export default SettingsDialog;
|
@ -6,6 +6,7 @@ import Link from 'next/link';
|
||||
import { useSelectedLayoutSegments } from 'next/navigation';
|
||||
import React, { useState, type ReactNode } from 'react';
|
||||
import Layout from './Layout';
|
||||
import SettingsDialog from './SettingsDialog';
|
||||
|
||||
const VerticalIconContainer = ({ children }: { children: ReactNode }) => {
|
||||
return (
|
||||
@ -66,9 +67,15 @@ const Sidebar = ({ children }: { children: React.ReactNode }) => {
|
||||
))}
|
||||
</VerticalIconContainer>
|
||||
|
||||
<Link href="/settings">
|
||||
<Settings className="cursor-pointer" />
|
||||
</Link>
|
||||
<Settings
|
||||
onClick={() => setIsSettingsOpen(!isSettingsOpen)}
|
||||
className="cursor-pointer"
|
||||
/>
|
||||
|
||||
<SettingsDialog
|
||||
isOpen={isSettingsOpen}
|
||||
setIsOpen={setIsSettingsOpen}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
@ -1,7 +1,8 @@
|
||||
'use client';
|
||||
import { useTheme } from 'next-themes';
|
||||
import { SunIcon, MoonIcon, MonitorIcon } from 'lucide-react';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import Select from '../ui/Select';
|
||||
import { Select } from '../SettingsDialog';
|
||||
|
||||
type Theme = 'dark' | 'light' | 'system';
|
||||
|
||||
|
@ -1,28 +0,0 @@
|
||||
import { cn } from '@/lib/utils';
|
||||
import { SelectHTMLAttributes } from 'react';
|
||||
|
||||
interface SelectProps extends SelectHTMLAttributes<HTMLSelectElement> {
|
||||
options: { value: string; label: string; disabled?: boolean }[];
|
||||
}
|
||||
|
||||
export const Select = ({ className, options, ...restProps }: SelectProps) => {
|
||||
return (
|
||||
<select
|
||||
{...restProps}
|
||||
className={cn(
|
||||
'bg-light-secondary dark:bg-dark-secondary px-3 py-2 flex items-center overflow-hidden border border-light-200 dark:border-dark-200 dark:text-white rounded-lg text-sm',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{options.map(({ label, value, disabled }) => {
|
||||
return (
|
||||
<option key={value} value={value} disabled={disabled}>
|
||||
{label}
|
||||
</option>
|
||||
);
|
||||
})}
|
||||
</select>
|
||||
);
|
||||
};
|
||||
|
||||
export default Select;
|
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "perplexica-frontend",
|
||||
"version": "1.10.0-rc3",
|
||||
"version": "1.10.0-rc2",
|
||||
"license": "MIT",
|
||||
"author": "ItzCrazyKns",
|
||||
"scripts": {
|
||||
|
Reference in New Issue
Block a user