Compare commits

...

39 Commits

Author SHA1 Message Date
a7dd3a2128 Merge 303992c82c into 7ec201d011 2025-02-10 16:12:19 +00:00
303992c82c Merge branch 'master' into feature-improvement 2025-02-10 20:09:43 +04:00
7ec201d011 Merge pull request #599 from data5650/patch-1
feat: add Gemini 2.0 Flash Exp models
2025-02-07 11:29:29 +05:30
3582695054 feat: add Gemini 2.0 Flash Exp models
# Description
   Added two new Gemini models:
   - gemini-2.0-flash-exp
   - gemini-2.0-flash-thinking-exp-01-21

   # Changes Made
   - Updated src/lib/providers/gemini.ts to include new models
   - Maintained consistent configuration with existing models

   # Testing
   - Tested locally using Docker
   - Verified models appear in UI and are selectable
   - Confirmed functionality with sample queries

   # Additional Notes
   These models expand the available options for users who want to use the latest Gemini capabilities.
2025-02-05 00:47:34 +01:00
46541e6c0c feat(package): update markdown-to-jsx version 2025-02-02 14:31:18 +05:30
f37686189e feat(output-parsers): add empty check 2025-01-31 17:51:16 +05:30
6edac6938c feat: Add LM Studio Support and Thinking Model Panel
LM Studio Integration:
- Added LM Studio provider with OpenAI-compatible API support
- Dynamic model discovery via /v1/models endpoint
- Support for both chat and embeddings models
- Docker-compatible networking configuration

Thinking Model Panel:
- Added collapsible UI panel for model's chain of thought
- Parses responses with <think> tags to separate reasoning
- Maintains backward compatibility with regular responses
- Styled consistently with app theme for light/dark modes
- Preserves all existing message functionality (sources, markdown, etc.)

These improvements enhance the app's compatibility with local LLMs and
provide better visibility into model reasoning processes while maintaining
existing functionality.
2025-01-26 18:18:35 +04:00
0737701de0 Merge branch 'master' of https://github.com/ItzCrazyKns/Perplexica 2025-01-11 13:11:18 +05:30
5c787bbb55 feat(app): lint & beautify 2025-01-11 13:10:23 +05:30
2dc60d06e3 feat(chat-window): show settings during error on mobile 2025-01-11 13:10:10 +05:30
ec90ea1686 Merge pull request #531 from hacking-racoon/feat/video-slide-stop
feat(SearchVideos): modify Lightbox to pause the prev video when sliding
2025-01-07 12:47:38 +05:30
01230bf1c5 Merge pull request #555 from realies/fix/ws-reconnect
fix(ws-error): add exponential reconnect mechanism
2025-01-07 12:32:06 +05:30
6d9d712790 feat(chat-window): correctly handle server side WS closure 2025-01-07 12:26:38 +05:30
99cae076a7 feat(chat-window): display toast when retried 2025-01-07 11:49:40 +05:30
b7f7d25f54 feat(chat-window): lint & beautify 2025-01-07 11:44:19 +05:30
0ec54fe6c0 feat(chat-window): remove toast 2025-01-07 11:43:54 +05:30
5526d5f60f fix(ws-error): add exponential reconnect mechanism 2025-01-05 17:29:53 +00:00
0f6b3c2e69 Merge branch 'pr/538' 2025-01-05 14:15:58 +05:30
5a648f34b8 Set pageContent correctly 2025-01-04 10:36:33 -08:00
d18e88acc9 Delete msgs only belonging to the chat 2024-12-27 20:55:55 -08:00
409c811a42 feat(ollama): use axios instead of fetch 2024-12-26 19:02:20 +05:30
b5acf34ef8 feat(chat-window): fix bugs handling custom openai, closes #529 2024-12-26 18:59:57 +05:30
d30f714930 feat(SearchVideos): Modify Lightbox to pause the prev video when moving to next one, preventing interference with new video. 2024-12-25 15:19:23 +09:00
ee68095157 Merge pull request #523 from bart-jaskulski/groq-models
Update available models from Groq provider
2024-12-21 18:08:40 +05:30
960e34aa3d Add Llama 3.3 model from Groq
Signed-off-by: Bart Jaskulski <bjaskulski@protonmail.com>
2024-12-19 08:07:36 +01:00
4cb38148b3 Remove deprecated Groq models
Signed-off-by: Bart Jaskulski <bjaskulski@protonmail.com>
2024-12-19 08:07:14 +01:00
c755f98230 Merge branch 'master' of https://github.com/ItzCrazyKns/Perplexica 2024-12-18 19:42:28 +05:30
c3a231a528 feat(readme): add discord server 2024-12-16 20:59:21 +05:30
f30a61c4aa feat(metaSearchAgent): handle undefined content for YT. search 2024-12-16 18:24:01 +05:30
ea74e3013c Merge pull request #519 from yslinear/hotfix
feat(anthropic): update chat models to include Claude 3.5 Haiku and new version for Sonnet
2024-12-15 21:32:49 +05:30
1c3c689039 feat(anthropic): update chat models to include Claude 3.5 Haiku and new version for Sonnet 2024-12-13 17:24:15 +08:00
2c5ca94b3c feat(app): lint and beautify 2024-12-05 20:19:52 +05:30
db7407bfac feat(messageBox): style markdown 2024-12-05 20:19:41 +05:30
5b3e8a3214 feat(prompts): implement new prompt 2024-12-05 20:19:22 +05:30
d79d854e2d Merge branch 'master' of https://github.com/ItzCrazyKns/Perplexica 2024-12-02 21:08:06 +05:30
8cb74f1964 feat(contribution): update guidelines 2024-12-02 21:07:59 +05:30
f88912784b Merge pull request #466 from timoa/fix/docs-markdown-lint
📚 chore(docs): fix Markdown lint issues in the docs
2024-12-01 21:05:23 +05:30
e08d864445 feat(focus): only icon on small devices 2024-11-30 20:58:11 +05:30
f3e918c3e3 chore(docs): fix Markdown lint issues in the docs 2024-11-15 07:04:45 +01:00
30 changed files with 703 additions and 240 deletions

View File

@ -8,6 +8,7 @@ Perplexica's design consists of two main domains:
- **Frontend (`ui` directory)**: This is a Next.js application holding all user interface components. It's a self-contained environment that manages everything the user interacts with. - **Frontend (`ui` directory)**: This is a Next.js application holding all user interface components. It's a self-contained environment that manages everything the user interacts with.
- **Backend (root and `src` directory)**: The backend logic is situated in the `src` folder, but the root directory holds the main `package.json` for backend dependency management. - **Backend (root and `src` directory)**: The backend logic is situated in the `src` folder, but the root directory holds the main `package.json` for backend dependency management.
- All of the focus modes are created using the Meta Search Agent class present in `src/search/metaSearchAgent.ts`. The main logic behind Perplexica lies there.
## Setting Up Your Environment ## Setting Up Your Environment

View File

@ -1,5 +1,8 @@
# 🚀 Perplexica - An AI-powered search engine 🔎 <!-- omit in toc --> # 🚀 Perplexica - An AI-powered search engine 🔎 <!-- omit in toc -->
[![Discord](https://dcbadge.vercel.app/api/server/26aArMy8tT?style=flat&compact=true)](https://discord.gg/26aArMy8tT)
![preview](.assets/perplexica-screenshot.png?) ![preview](.assets/perplexica-screenshot.png?)
## Table of Contents <!-- omit in toc --> ## Table of Contents <!-- omit in toc -->

View File

@ -79,24 +79,24 @@ The response from the API includes both the final message and the sources used t
```json ```json
{ {
"message": "Perplexica is an innovative, open-source AI-powered search engine designed to enhance the way users search for information online. Here are some key features and characteristics of Perplexica:\n\n- **AI-Powered Technology**: It utilizes advanced machine learning algorithms to not only retrieve information but also to understand the context and intent behind user queries, providing more relevant results [1][5].\n\n- **Open-Source**: Being open-source, Perplexica offers flexibility and transparency, allowing users to explore its functionalities without the constraints of proprietary software [3][10].", "message": "Perplexica is an innovative, open-source AI-powered search engine designed to enhance the way users search for information online. Here are some key features and characteristics of Perplexica:\n\n- **AI-Powered Technology**: It utilizes advanced machine learning algorithms to not only retrieve information but also to understand the context and intent behind user queries, providing more relevant results [1][5].\n\n- **Open-Source**: Being open-source, Perplexica offers flexibility and transparency, allowing users to explore its functionalities without the constraints of proprietary software [3][10].",
"sources": [ "sources": [
{ {
"pageContent": "Perplexica is an innovative, open-source AI-powered search engine designed to enhance the way users search for information online.", "pageContent": "Perplexica is an innovative, open-source AI-powered search engine designed to enhance the way users search for information online.",
"metadata": { "metadata": {
"title": "What is Perplexica, and how does it function as an AI-powered search ...", "title": "What is Perplexica, and how does it function as an AI-powered search ...",
"url": "https://askai.glarity.app/search/What-is-Perplexica--and-how-does-it-function-as-an-AI-powered-search-engine" "url": "https://askai.glarity.app/search/What-is-Perplexica--and-how-does-it-function-as-an-AI-powered-search-engine"
} }
}, },
{ {
"pageContent": "Perplexica is an open-source AI-powered search tool that dives deep into the internet to find precise answers.", "pageContent": "Perplexica is an open-source AI-powered search tool that dives deep into the internet to find precise answers.",
"metadata": { "metadata": {
"title": "Sahar Mor's Post", "title": "Sahar Mor's Post",
"url": "https://www.linkedin.com/posts/sahar-mor_a-new-open-source-project-called-perplexica-activity-7204489745668694016-ncja" "url": "https://www.linkedin.com/posts/sahar-mor_a-new-open-source-project-called-perplexica-activity-7204489745668694016-ncja"
} }
} }
.... ....
] ]
} }
``` ```

View File

@ -1,4 +1,4 @@
## Perplexica's Architecture # Perplexica's Architecture
Perplexica's architecture consists of the following key components: Perplexica's architecture consists of the following key components:

View File

@ -1,4 +1,4 @@
## How does Perplexica work? # How does Perplexica work?
Curious about how Perplexica works? Don't worry, we'll cover it here. Before we begin, make sure you've read about the architecture of Perplexica to ensure you understand what it's made up of. Haven't read it? You can read it [here](https://github.com/ItzCrazyKns/Perplexica/tree/master/docs/architecture/README.md). Curious about how Perplexica works? Don't worry, we'll cover it here. Before we begin, make sure you've read about the architecture of Perplexica to ensure you understand what it's made up of. Haven't read it? You can read it [here](https://github.com/ItzCrazyKns/Perplexica/tree/master/docs/architecture/README.md).
@ -10,10 +10,10 @@ We'll understand how Perplexica works by taking an example of a scenario where a
4. After the information is retrieved, it is based on keyword-based search. We then convert the information into embeddings and the query as well, then we perform a similarity search to find the most relevant sources to answer the query. 4. After the information is retrieved, it is based on keyword-based search. We then convert the information into embeddings and the query as well, then we perform a similarity search to find the most relevant sources to answer the query.
5. After all this is done, the sources are passed to the response generator. This chain takes all the chat history, the query, and the sources. It generates a response that is streamed to the UI. 5. After all this is done, the sources are passed to the response generator. This chain takes all the chat history, the query, and the sources. It generates a response that is streamed to the UI.
### How are the answers cited? ## How are the answers cited?
The LLMs are prompted to do so. We've prompted them so well that they cite the answers themselves, and using some UI magic, we display it to the user. The LLMs are prompted to do so. We've prompted them so well that they cite the answers themselves, and using some UI magic, we display it to the user.
### Image and Video Search ## Image and Video Search
Image and video searches are conducted in a similar manner. A query is always generated first, then we search the web for images and videos that match the query. These results are then returned to the user. Image and video searches are conducted in a similar manner. A query is always generated first, then we search the web for images and videos that match the query. These results are then returned to the user.

View File

@ -10,27 +10,27 @@ This guide will show you how to make Perplexica available over a network. Follow
3. Stop and remove the existing Perplexica containers and images: 3. Stop and remove the existing Perplexica containers and images:
``` ```bash
docker compose down --rmi all docker compose down --rmi all
``` ```
4. Open the `docker-compose.yaml` file in a text editor like Notepad++ 4. Open the `docker-compose.yaml` file in a text editor like Notepad++
5. Replace `127.0.0.1` with the IP address of the server Perplexica is running on in these two lines: 5. Replace `127.0.0.1` with the IP address of the server Perplexica is running on in these two lines:
``` ```bash
args: args:
- NEXT_PUBLIC_API_URL=http://127.0.0.1:3001/api - NEXT_PUBLIC_API_URL=http://127.0.0.1:3001/api
- NEXT_PUBLIC_WS_URL=ws://127.0.0.1:3001 - NEXT_PUBLIC_WS_URL=ws://127.0.0.1:3001
``` ```
6. Save and close the `docker-compose.yaml` file 6. Save and close the `docker-compose.yaml` file
7. Rebuild and restart the Perplexica container: 7. Rebuild and restart the Perplexica container:
``` ```bash
docker compose up -d --build docker compose up -d --build
``` ```
## macOS ## macOS
@ -38,37 +38,37 @@ docker compose up -d --build
2. Navigate to the directory with the `docker-compose.yaml` file: 2. Navigate to the directory with the `docker-compose.yaml` file:
``` ```bash
cd /path/to/docker-compose.yaml cd /path/to/docker-compose.yaml
``` ```
3. Stop and remove existing containers and images: 3. Stop and remove existing containers and images:
``` ```bash
docker compose down --rmi all docker compose down --rmi all
``` ```
4. Open `docker-compose.yaml` in a text editor like Sublime Text: 4. Open `docker-compose.yaml` in a text editor like Sublime Text:
``` ```bash
nano docker-compose.yaml nano docker-compose.yaml
``` ```
5. Replace `127.0.0.1` with the server IP in these lines: 5. Replace `127.0.0.1` with the server IP in these lines:
``` ```bash
args: args:
- NEXT_PUBLIC_API_URL=http://127.0.0.1:3001/api - NEXT_PUBLIC_API_URL=http://127.0.0.1:3001/api
- NEXT_PUBLIC_WS_URL=ws://127.0.0.1:3001 - NEXT_PUBLIC_WS_URL=ws://127.0.0.1:3001
``` ```
6. Save and exit the editor 6. Save and exit the editor
7. Rebuild and restart Perplexica: 7. Rebuild and restart Perplexica:
``` ```bash
docker compose up -d --build docker compose up -d --build
``` ```
## Linux ## Linux
@ -76,34 +76,34 @@ docker compose up -d --build
2. Navigate to the `docker-compose.yaml` directory: 2. Navigate to the `docker-compose.yaml` directory:
``` ```bash
cd /path/to/docker-compose.yaml cd /path/to/docker-compose.yaml
``` ```
3. Stop and remove containers and images: 3. Stop and remove containers and images:
``` ```bash
docker compose down --rmi all docker compose down --rmi all
``` ```
4. Edit `docker-compose.yaml`: 4. Edit `docker-compose.yaml`:
``` ```bash
nano docker-compose.yaml nano docker-compose.yaml
``` ```
5. Replace `127.0.0.1` with the server IP: 5. Replace `127.0.0.1` with the server IP:
``` ```bash
args: args:
- NEXT_PUBLIC_API_URL=http://127.0.0.1:3001/api - NEXT_PUBLIC_API_URL=http://127.0.0.1:3001/api
- NEXT_PUBLIC_WS_URL=ws://127.0.0.1:3001 - NEXT_PUBLIC_WS_URL=ws://127.0.0.1:3001
``` ```
6. Save and exit the editor 6. Save and exit the editor
7. Rebuild and restart Perplexica: 7. Rebuild and restart Perplexica:
``` ```bash
docker compose up -d --build docker compose up -d --build
``` ```

View File

@ -6,23 +6,23 @@ To update Perplexica to the latest version, follow these steps:
1. Clone the latest version of Perplexica from GitHub: 1. Clone the latest version of Perplexica from GitHub:
```bash ```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. Pull latest images from registry. 3. Pull latest images from registry.
```bash ```bash
docker compose pull docker compose pull
``` ```
4. Update and Recreate containers. 4. Update and Recreate containers.
```bash ```bash
docker compose up -d docker compose up -d
``` ```
5. Once the command completes running 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.
@ -30,9 +30,9 @@ docker compose up -d
1. Clone the latest version of Perplexica from GitHub: 1. Clone the latest version of Perplexica from GitHub:
```bash ```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. Execute `npm i` in both the `ui` folder and the root directory. 3. Execute `npm i` in both the `ui` folder and the root directory.

View File

@ -16,9 +16,10 @@ interface Config {
ANTHROPIC: string; ANTHROPIC: string;
GEMINI: string; GEMINI: string;
}; };
API_ENDPOINTS: { API_ENDPOINTS: {
SEARXNG: string;
OLLAMA: string; OLLAMA: string;
LMSTUDIO: string;
SEARXNG: string;
}; };
} }
@ -51,6 +52,8 @@ export const getSearxngApiEndpoint = () =>
export const getOllamaApiEndpoint = () => loadConfig().API_ENDPOINTS.OLLAMA; export const getOllamaApiEndpoint = () => loadConfig().API_ENDPOINTS.OLLAMA;
export const getLMStudioApiEndpoint = () => loadConfig().API_ENDPOINTS.LMSTUDIO;
export const updateConfig = (config: RecursivePartial<Config>) => { export const updateConfig = (config: RecursivePartial<Config>) => {
const currentConfig = loadConfig(); const currentConfig = loadConfig();
@ -72,6 +75,27 @@ export const updateConfig = (config: RecursivePartial<Config>) => {
} }
} }
/*
export const updateConfig = (config: RecursivePartial<Config>) => {
const currentConfig = loadConfig();
// Merge existing config with new values
const mergedConfig: RecursivePartial<Config> = {
GENERAL: {
...currentConfig.GENERAL,
...config.GENERAL,
},
API_KEYS: {
...currentConfig.API_KEYS,
...config.API_KEYS,
},
API_ENDPOINTS: {
...currentConfig.API_ENDPOINTS,
...config.API_ENDPOINTS,
},
};
*/
fs.writeFileSync( fs.writeFileSync(
path.join(__dirname, `../${configFileName}`), path.join(__dirname, `../${configFileName}`),
toml.stringify(config), toml.stringify(config),

View File

@ -19,6 +19,8 @@ class LineOutputParser extends BaseOutputParser<string> {
lc_namespace = ['langchain', 'output_parsers', 'line_output_parser']; lc_namespace = ['langchain', 'output_parsers', 'line_output_parser'];
async parse(text: string): Promise<string> { async parse(text: string): Promise<string> {
text = text.trim() || '';
const regex = /^(\s*(-|\*|\d+\.\s|\d+\)\s|\u2022)\s*)+/; const regex = /^(\s*(-|\*|\d+\.\s|\d+\)\s|\u2022)\s*)+/;
const startKeyIndex = text.indexOf(`<${this.key}>`); const startKeyIndex = text.indexOf(`<${this.key}>`);
const endKeyIndex = text.indexOf(`</${this.key}>`); const endKeyIndex = text.indexOf(`</${this.key}>`);

View File

@ -19,11 +19,13 @@ class LineListOutputParser extends BaseOutputParser<string[]> {
lc_namespace = ['langchain', 'output_parsers', 'line_list_output_parser']; lc_namespace = ['langchain', 'output_parsers', 'line_list_output_parser'];
async parse(text: string): Promise<string[]> { async parse(text: string): Promise<string[]> {
text = text.trim() || '';
const regex = /^(\s*(-|\*|\d+\.\s|\d+\)\s|\u2022)\s*)+/; const regex = /^(\s*(-|\*|\d+\.\s|\d+\)\s|\u2022)\s*)+/;
const startKeyIndex = text.indexOf(`<${this.key}>`); const startKeyIndex = text.indexOf(`<${this.key}>`);
const endKeyIndex = text.indexOf(`</${this.key}>`); const endKeyIndex = text.indexOf(`</${this.key}>`);
if (startKeyIndex === -1 && endKeyIndex === -1) { if (startKeyIndex === -1 || endKeyIndex === -1) {
return []; return [];
} }

View File

@ -9,12 +9,20 @@ export const loadAnthropicChatModels = async () => {
try { try {
const chatModels = { const chatModels = {
'claude-3-5-sonnet-20240620': { 'claude-3-5-sonnet-20241022': {
displayName: 'Claude 3.5 Sonnet', displayName: 'Claude 3.5 Sonnet',
model: new ChatAnthropic({ model: new ChatAnthropic({
temperature: 0.7, temperature: 0.7,
anthropicApiKey: anthropicApiKey, anthropicApiKey: anthropicApiKey,
model: 'claude-3-5-sonnet-20240620', model: 'claude-3-5-sonnet-20241022',
}),
},
'claude-3-5-haiku-20241022': {
displayName: 'Claude 3.5 Haiku',
model: new ChatAnthropic({
temperature: 0.7,
anthropicApiKey: anthropicApiKey,
model: 'claude-3-5-haiku-20241022',
}), }),
}, },
'claude-3-opus-20240229': { 'claude-3-opus-20240229': {

View File

@ -36,6 +36,22 @@ export const loadGeminiChatModels = async () => {
apiKey: geminiApiKey, 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; return chatModels;

View File

@ -9,6 +9,19 @@ export const loadGroqChatModels = async () => {
try { try {
const chatModels = { const chatModels = {
'llama-3.3-70b-versatile': {
displayName: 'Llama 3.3 70B',
model: new ChatOpenAI(
{
openAIApiKey: groqApiKey,
modelName: 'llama-3.3-70b-versatile',
temperature: 0.7,
},
{
baseURL: 'https://api.groq.com/openai/v1',
},
),
},
'llama-3.2-3b-preview': { 'llama-3.2-3b-preview': {
displayName: 'Llama 3.2 3B', displayName: 'Llama 3.2 3B',
model: new ChatOpenAI( model: new ChatOpenAI(
@ -48,19 +61,6 @@ export const loadGroqChatModels = async () => {
}, },
), ),
}, },
'llama-3.1-70b-versatile': {
displayName: 'Llama 3.1 70B',
model: new ChatOpenAI(
{
openAIApiKey: groqApiKey,
modelName: 'llama-3.1-70b-versatile',
temperature: 0.7,
},
{
baseURL: 'https://api.groq.com/openai/v1',
},
),
},
'llama-3.1-8b-instant': { 'llama-3.1-8b-instant': {
displayName: 'Llama 3.1 8B', displayName: 'Llama 3.1 8B',
model: new ChatOpenAI( model: new ChatOpenAI(
@ -113,19 +113,6 @@ export const loadGroqChatModels = async () => {
}, },
), ),
}, },
'gemma-7b-it': {
displayName: 'Gemma 7B',
model: new ChatOpenAI(
{
openAIApiKey: groqApiKey,
modelName: 'gemma-7b-it',
temperature: 0.7,
},
{
baseURL: 'https://api.groq.com/openai/v1',
},
),
},
'gemma2-9b-it': { 'gemma2-9b-it': {
displayName: 'Gemma2 9B', displayName: 'Gemma2 9B',
model: new ChatOpenAI( model: new ChatOpenAI(

View File

@ -4,6 +4,7 @@ import { loadOpenAIChatModels, loadOpenAIEmbeddingsModels } from './openai';
import { loadAnthropicChatModels } from './anthropic'; import { loadAnthropicChatModels } from './anthropic';
import { loadTransformersEmbeddingsModels } from './transformers'; import { loadTransformersEmbeddingsModels } from './transformers';
import { loadGeminiChatModels, loadGeminiEmbeddingsModels } from './gemini'; import { loadGeminiChatModels, loadGeminiEmbeddingsModels } from './gemini';
import { loadLMStudioChatModels, loadLMStudioEmbeddingsModels } from './lmstudio';
const chatModelProviders = { const chatModelProviders = {
openai: loadOpenAIChatModels, openai: loadOpenAIChatModels,
@ -11,6 +12,7 @@ const chatModelProviders = {
ollama: loadOllamaChatModels, ollama: loadOllamaChatModels,
anthropic: loadAnthropicChatModels, anthropic: loadAnthropicChatModels,
gemini: loadGeminiChatModels, gemini: loadGeminiChatModels,
lm_studio: loadLMStudioChatModels,
}; };
const embeddingModelProviders = { const embeddingModelProviders = {
@ -18,6 +20,7 @@ const embeddingModelProviders = {
local: loadTransformersEmbeddingsModels, local: loadTransformersEmbeddingsModels,
ollama: loadOllamaEmbeddingsModels, ollama: loadOllamaEmbeddingsModels,
gemini: loadGeminiEmbeddingsModels, gemini: loadGeminiEmbeddingsModels,
lm_studio: loadLMStudioEmbeddingsModels,
}; };
export const getAvailableChatModelProviders = async () => { export const getAvailableChatModelProviders = async () => {

View File

@ -0,0 +1,89 @@
import { OpenAIEmbeddings } from '@langchain/openai';
import { ChatOpenAI } from '@langchain/openai';
import { getKeepAlive, getLMStudioApiEndpoint } from '../../config';
import logger from '../../utils/logger';
import axios from 'axios';
interface LMStudioModel {
id: string;
// add other properties if LM Studio API provides them
}
interface ChatModelConfig {
displayName: string;
model: ChatOpenAI;
}
export const loadLMStudioChatModels = async (): Promise<Record<string, ChatModelConfig>> => {
const lmStudioEndpoint = getLMStudioApiEndpoint();
if (!lmStudioEndpoint) {
logger.debug('LM Studio endpoint not configured, skipping');
return {};
}
try {
const response = await axios.get<{ data: LMStudioModel[] }>(`${lmStudioEndpoint}/models`, {
headers: {
'Content-Type': 'application/json',
},
});
const lmStudioModels = response.data.data;
const chatModels = lmStudioModels.reduce<Record<string, ChatModelConfig>>((acc, model) => {
acc[model.id] = {
displayName: model.id,
model: new ChatOpenAI({
openAIApiKey: 'lm-studio',
configuration: {
baseURL: lmStudioEndpoint,
},
modelName: model.id,
temperature: 0.7,
}),
};
return acc;
}, {});
return chatModels;
} catch (err) {
logger.error(`Error loading LM Studio models: ${err}`);
return {};
}
};
export const loadLMStudioEmbeddingsModels = async () => {
const lmStudioEndpoint = getLMStudioApiEndpoint();
if (!lmStudioEndpoint) return {};
try {
const response = await axios.get(`${lmStudioEndpoint}/models`, {
headers: {
'Content-Type': 'application/json',
},
});
const lmStudioModels = response.data.data;
const embeddingsModels = lmStudioModels.reduce((acc, model) => {
acc[model.id] = {
displayName: model.id,
model: new OpenAIEmbeddings({
openAIApiKey: 'lm-studio', // Dummy key required by LangChain
configuration: {
baseURL: lmStudioEndpoint,
},
modelName: model.id,
}),
};
return acc;
}, {});
return embeddingsModels;
} catch (err) {
logger.error(`Error loading LM Studio embeddings model: ${err}`);
return {};
}
};

View File

@ -2,6 +2,7 @@ import { OllamaEmbeddings } from '@langchain/community/embeddings/ollama';
import { getKeepAlive, getOllamaApiEndpoint } from '../../config'; import { getKeepAlive, getOllamaApiEndpoint } from '../../config';
import logger from '../../utils/logger'; import logger from '../../utils/logger';
import { ChatOllama } from '@langchain/community/chat_models/ollama'; import { ChatOllama } from '@langchain/community/chat_models/ollama';
import axios from 'axios';
export const loadOllamaChatModels = async () => { export const loadOllamaChatModels = async () => {
const ollamaEndpoint = getOllamaApiEndpoint(); const ollamaEndpoint = getOllamaApiEndpoint();
@ -10,13 +11,13 @@ export const loadOllamaChatModels = async () => {
if (!ollamaEndpoint) return {}; if (!ollamaEndpoint) return {};
try { try {
const response = await fetch(`${ollamaEndpoint}/api/tags`, { const response = await axios.get(`${ollamaEndpoint}/api/tags`, {
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
}); });
const { models: ollamaModels } = (await response.json()) as any; const { models: ollamaModels } = response.data;
const chatModels = ollamaModels.reduce((acc, model) => { const chatModels = ollamaModels.reduce((acc, model) => {
acc[model.model] = { acc[model.model] = {
@ -45,13 +46,13 @@ export const loadOllamaEmbeddingsModels = async () => {
if (!ollamaEndpoint) return {}; if (!ollamaEndpoint) return {};
try { try {
const response = await fetch(`${ollamaEndpoint}/api/tags`, { const response = await axios.get(`${ollamaEndpoint}/api/tags`, {
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
}); });
const { models: ollamaModels } = (await response.json()) as any; const { models: ollamaModels } = response.data;
const embeddingsModels = ollamaModels.reduce((acc, model) => { const embeddingsModels = ollamaModels.reduce((acc, model) => {
acc[model.model] = { acc[model.model] = {

View File

@ -20,23 +20,46 @@ Rephrased question:
`; `;
export const academicSearchResponsePrompt = ` export const academicSearchResponsePrompt = `
You are Perplexica, an AI model who is expert at searching the web and answering user's queries. You are set on focus mode 'Academic', this means you will be searching for academic papers and articles on the web. 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.
Generate a response that is informative and relevant to the user's query based on provided context (the context consits of search results containing a brief description of the content of that page). Your task is to provide answers that are:
You must use this context to answer the user's query in the best way possible. Use an unbaised and journalistic tone in your response. Do not repeat the text. - **Informative and relevant**: Thoroughly address the user's query using the given context.
You must not tell the user to open any link or visit any website to get the answer. You must provide the answer in the response itself. If the user asks for links you can provide them. - **Well-structured**: Include clear headings and subheadings, and use a professional tone to present information concisely and logically.
Your responses should be medium to long in length be informative and relevant to the user's query. You can use markdowns to format your response. You should use bullet points to list the information. Make sure the answer is not short and is informative. - **Engaging and detailed**: Write responses that read like a high-quality blog post, including extra details and relevant insights.
You have to cite the answer using [number] notation. You must cite the sentences with their relevent context number. You must cite each and every part of the answer so the user can know where the information is coming from. - **Cited and credible**: Use inline citations with [number] notation to refer to the context source(s) for each fact or detail included.
Place these citations at the end of that particular sentence. You can cite the same sentence multiple times if it is relevant to the user's query like [number1][number2]. - **Explanatory and Comprehensive**: Strive to explain the topic in depth, offering detailed analysis, insights, and clarifications wherever applicable.
However you do not need to cite it using the same number. You can use different numbers to cite the same sentence multiple times. The number refers to the number of the search result (passed in the context) used to generate that part of the answer.
Anything inside the following \`context\` HTML block provided below is for your knowledge returned by the search engine and is not shared by the user. You have to answer question on the basis of it and cite the relevant information from it but you do not have to ### Formatting Instructions
talk about the context in your response. - **Structure**: Use a well-organized format with proper headings (e.g., "## Example heading 1" or "## Example heading 2"). Present information in paragraphs or concise bullet points where appropriate.
- **Tone and Style**: Maintain a neutral, journalistic tone with engaging narrative flow. Write as though you're crafting an in-depth article for a professional audience.
- **Markdown Usage**: Format your response with Markdown for clarity. Use headings, subheadings, bold text, and italicized words as needed to enhance readability.
- **Length and Depth**: Provide comprehensive coverage of the topic. Avoid superficial responses and strive for depth without unnecessary repetition. Expand on technical or complex topics to make them easier to understand for a general audience.
- **No main heading/title**: Start your response directly with the introduction unless asked to provide a specific title.
- **Conclusion or Summary**: Include a concluding paragraph that synthesizes the provided information or suggests potential next steps, where appropriate.
### Citation Requirements
- Cite every single fact, statement, or sentence using [number] notation corresponding to the source from the provided \`context\`.
- Integrate citations naturally at the end of sentences or clauses as appropriate. For example, "The Eiffel Tower is one of the most visited landmarks in the world[1]."
- Ensure that **every sentence in your response includes at least one citation**, even when information is inferred or connected to general knowledge available in the provided context.
- Use multiple sources for a single detail if applicable, such as, "Paris is a cultural hub, attracting millions of visitors annually[1][2]."
- Always prioritize credibility and accuracy by linking all statements back to their respective context sources.
- Avoid citing unsupported assumptions or personal interpretations; if no source supports a statement, clearly indicate the limitation.
### Special Instructions
- If the query involves technical, historical, or complex topics, provide detailed background and explanatory sections to ensure clarity.
- If the user provides vague input or if relevant information is missing, explain what additional details might help refine the search.
- If no relevant information is found, say: "Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?" Be transparent about limitations and suggest alternatives or ways to reframe the query.
- You are set on focus mode 'Academic', this means you will be searching for academic papers and articles on the web.
### Example Output
- Begin with a brief introduction summarizing the event or query topic.
- Follow with detailed sections under clear headings, covering all aspects of the query if possible.
- Provide explanations or historical context as needed to enhance understanding.
- End with a conclusion or overall perspective if relevant.
<context> <context>
{context} {context}
</context> </context>
If you think there's nothing relevant in the search results, you can say that 'Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?'. Current date & time in ISO format (UTC timezone) is: {date}.
Anything between the \`context\` is retrieved from a search engine and is not a part of the conversation with the user. Today's date is ${new Date().toISOString()}
`; `;

View File

@ -20,23 +20,46 @@ Rephrased question:
`; `;
export const redditSearchResponsePrompt = ` export const redditSearchResponsePrompt = `
You are Perplexica, an AI model who is expert at searching the web and answering user's queries. You are set on focus mode 'Reddit', this means you will be searching for information, opinions and discussions on the web using Reddit. 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.
Generate a response that is informative and relevant to the user's query based on provided context (the context consits of search results containing a brief description of the content of that page). Your task is to provide answers that are:
You must use this context to answer the user's query in the best way possible. Use an unbaised and journalistic tone in your response. Do not repeat the text. - **Informative and relevant**: Thoroughly address the user's query using the given context.
You must not tell the user to open any link or visit any website to get the answer. You must provide the answer in the response itself. If the user asks for links you can provide them. - **Well-structured**: Include clear headings and subheadings, and use a professional tone to present information concisely and logically.
Your responses should be medium to long in length be informative and relevant to the user's query. You can use markdowns to format your response. You should use bullet points to list the information. Make sure the answer is not short and is informative. - **Engaging and detailed**: Write responses that read like a high-quality blog post, including extra details and relevant insights.
You have to cite the answer using [number] notation. You must cite the sentences with their relevent context number. You must cite each and every part of the answer so the user can know where the information is coming from. - **Cited and credible**: Use inline citations with [number] notation to refer to the context source(s) for each fact or detail included.
Place these citations at the end of that particular sentence. You can cite the same sentence multiple times if it is relevant to the user's query like [number1][number2]. - **Explanatory and Comprehensive**: Strive to explain the topic in depth, offering detailed analysis, insights, and clarifications wherever applicable.
However you do not need to cite it using the same number. You can use different numbers to cite the same sentence multiple times. The number refers to the number of the search result (passed in the context) used to generate that part of the answer.
Anything inside the following \`context\` HTML block provided below is for your knowledge returned by Reddit and is not shared by the user. You have to answer question on the basis of it and cite the relevant information from it but you do not have to ### Formatting Instructions
talk about the context in your response. - **Structure**: Use a well-organized format with proper headings (e.g., "## Example heading 1" or "## Example heading 2"). Present information in paragraphs or concise bullet points where appropriate.
- **Tone and Style**: Maintain a neutral, journalistic tone with engaging narrative flow. Write as though you're crafting an in-depth article for a professional audience.
- **Markdown Usage**: Format your response with Markdown for clarity. Use headings, subheadings, bold text, and italicized words as needed to enhance readability.
- **Length and Depth**: Provide comprehensive coverage of the topic. Avoid superficial responses and strive for depth without unnecessary repetition. Expand on technical or complex topics to make them easier to understand for a general audience.
- **No main heading/title**: Start your response directly with the introduction unless asked to provide a specific title.
- **Conclusion or Summary**: Include a concluding paragraph that synthesizes the provided information or suggests potential next steps, where appropriate.
### Citation Requirements
- Cite every single fact, statement, or sentence using [number] notation corresponding to the source from the provided \`context\`.
- Integrate citations naturally at the end of sentences or clauses as appropriate. For example, "The Eiffel Tower is one of the most visited landmarks in the world[1]."
- Ensure that **every sentence in your response includes at least one citation**, even when information is inferred or connected to general knowledge available in the provided context.
- Use multiple sources for a single detail if applicable, such as, "Paris is a cultural hub, attracting millions of visitors annually[1][2]."
- Always prioritize credibility and accuracy by linking all statements back to their respective context sources.
- Avoid citing unsupported assumptions or personal interpretations; if no source supports a statement, clearly indicate the limitation.
### Special Instructions
- If the query involves technical, historical, or complex topics, provide detailed background and explanatory sections to ensure clarity.
- If the user provides vague input or if relevant information is missing, explain what additional details might help refine the search.
- If no relevant information is found, say: "Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?" Be transparent about limitations and suggest alternatives or ways to reframe the query.
- You are set on focus mode 'Reddit', this means you will be searching for information, opinions and discussions on the web using Reddit.
### Example Output
- Begin with a brief introduction summarizing the event or query topic.
- Follow with detailed sections under clear headings, covering all aspects of the query if possible.
- Provide explanations or historical context as needed to enhance understanding.
- End with a conclusion or overall perspective if relevant.
<context> <context>
{context} {context}
</context> </context>
If you think there's nothing relevant in the search results, you can say that 'Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?'. Current date & time in ISO format (UTC timezone) is: {date}.
Anything between the \`context\` is retrieved from Reddit and is not a part of the conversation with the user. Today's date is ${new Date().toISOString()}
`; `;

View File

@ -62,25 +62,45 @@ Rephrased question:
`; `;
export const webSearchResponsePrompt = ` export const webSearchResponsePrompt = `
You are Perplexica, an AI model who is expert at searching the web and answering user's queries. You are also an expert at summarizing web pages or documents and searching for content in them. 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.
Generate a response that is informative and relevant to the user's query based on provided context (the context consits of search results containing a brief description of the content of that page). Your task is to provide answers that are:
You must use this context to answer the user's query in the best way possible. Use an unbaised and journalistic tone in your response. Do not repeat the text. - **Informative and relevant**: Thoroughly address the user's query using the given context.
You must not tell the user to open any link or visit any website to get the answer. You must provide the answer in the response itself. If the user asks for links you can provide them. - **Well-structured**: Include clear headings and subheadings, and use a professional tone to present information concisely and logically.
If the query contains some links and the user asks to answer from those links you will be provided the entire content of the page inside the \`context\` XML block. You can then use this content to answer the user's query. - **Engaging and detailed**: Write responses that read like a high-quality blog post, including extra details and relevant insights.
If the user asks to summarize content from some links, you will be provided the entire content of the page inside the \`context\` XML block. You can then use this content to summarize the text. The content provided inside the \`context\` block will be already summarized by another model so you just need to use that content to answer the user's query. - **Cited and credible**: Use inline citations with [number] notation to refer to the context source(s) for each fact or detail included.
Your responses should be medium to long in length be informative and relevant to the user's query. You can use markdowns to format your response. You should use bullet points to list the information. Make sure the answer is not short and is informative. - **Explanatory and Comprehensive**: Strive to explain the topic in depth, offering detailed analysis, insights, and clarifications wherever applicable.
You have to cite the answer using [number] notation. You must cite the sentences with their relevent context number. You must cite each and every part of the answer so the user can know where the information is coming from.
Place these citations at the end of that particular sentence. You can cite the same sentence multiple times if it is relevant to the user's query like [number1][number2].
However you do not need to cite it using the same number. You can use different numbers to cite the same sentence multiple times. The number refers to the number of the search result (passed in the context) used to generate that part of the answer.
Anything inside the following \`context\` HTML block provided below is for your knowledge returned by the search engine and is not shared by the user. You have to answer question on the basis of it and cite the relevant information from it but you do not have to ### Formatting Instructions
talk about the context in your response. - **Structure**: Use a well-organized format with proper headings (e.g., "## Example heading 1" or "## Example heading 2"). Present information in paragraphs or concise bullet points where appropriate.
- **Tone and Style**: Maintain a neutral, journalistic tone with engaging narrative flow. Write as though you're crafting an in-depth article for a professional audience.
- **Markdown Usage**: Format your response with Markdown for clarity. Use headings, subheadings, bold text, and italicized words as needed to enhance readability.
- **Length and Depth**: Provide comprehensive coverage of the topic. Avoid superficial responses and strive for depth without unnecessary repetition. Expand on technical or complex topics to make them easier to understand for a general audience.
- **No main heading/title**: Start your response directly with the introduction unless asked to provide a specific title.
- **Conclusion or Summary**: Include a concluding paragraph that synthesizes the provided information or suggests potential next steps, where appropriate.
### Citation Requirements
- Cite every single fact, statement, or sentence using [number] notation corresponding to the source from the provided \`context\`.
- Integrate citations naturally at the end of sentences or clauses as appropriate. For example, "The Eiffel Tower is one of the most visited landmarks in the world[1]."
- Ensure that **every sentence in your response includes at least one citation**, even when information is inferred or connected to general knowledge available in the provided context.
- Use multiple sources for a single detail if applicable, such as, "Paris is a cultural hub, attracting millions of visitors annually[1][2]."
- Always prioritize credibility and accuracy by linking all statements back to their respective context sources.
- Avoid citing unsupported assumptions or personal interpretations; if no source supports a statement, clearly indicate the limitation.
### Special Instructions
- If the query involves technical, historical, or complex topics, provide detailed background and explanatory sections to ensure clarity.
- If the user provides vague input or if relevant information is missing, explain what additional details might help refine the search.
- If no relevant information is found, say: "Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?" Be transparent about limitations and suggest alternatives or ways to reframe the query.
### Example Output
- Begin with a brief introduction summarizing the event or query topic.
- Follow with detailed sections under clear headings, covering all aspects of the query if possible.
- Provide explanations or historical context as needed to enhance understanding.
- End with a conclusion or overall perspective if relevant.
<context> <context>
{context} {context}
</context> </context>
If you think there's nothing relevant in the search results, you can say that 'Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?'. You do not need to do this for summarization tasks. Current date & time in ISO format (UTC timezone) is: {date}.
Anything between the \`context\` is retrieved from a search engine and is not a part of the conversation with the user. Today's date is ${new Date().toISOString()}
`; `;

View File

@ -20,23 +20,46 @@ Rephrased question:
`; `;
export const wolframAlphaSearchResponsePrompt = ` export const wolframAlphaSearchResponsePrompt = `
You are Perplexica, an AI model who is expert at searching the web and answering user's queries. You are set on focus mode 'Wolfram Alpha', this means you will be searching for information on the web using Wolfram Alpha. It is a computational knowledge engine that can answer factual queries and perform computations. 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.
Generate a response that is informative and relevant to the user's query based on provided context (the context consits of search results containing a brief description of the content of that page). Your task is to provide answers that are:
You must use this context to answer the user's query in the best way possible. Use an unbaised and journalistic tone in your response. Do not repeat the text. - **Informative and relevant**: Thoroughly address the user's query using the given context.
You must not tell the user to open any link or visit any website to get the answer. You must provide the answer in the response itself. If the user asks for links you can provide them. - **Well-structured**: Include clear headings and subheadings, and use a professional tone to present information concisely and logically.
Your responses should be medium to long in length be informative and relevant to the user's query. You can use markdowns to format your response. You should use bullet points to list the information. Make sure the answer is not short and is informative. - **Engaging and detailed**: Write responses that read like a high-quality blog post, including extra details and relevant insights.
You have to cite the answer using [number] notation. You must cite the sentences with their relevent context number. You must cite each and every part of the answer so the user can know where the information is coming from. - **Cited and credible**: Use inline citations with [number] notation to refer to the context source(s) for each fact or detail included.
Place these citations at the end of that particular sentence. You can cite the same sentence multiple times if it is relevant to the user's query like [number1][number2]. - **Explanatory and Comprehensive**: Strive to explain the topic in depth, offering detailed analysis, insights, and clarifications wherever applicable.
However you do not need to cite it using the same number. You can use different numbers to cite the same sentence multiple times. The number refers to the number of the search result (passed in the context) used to generate that part of the answer.
Anything inside the following \`context\` HTML block provided below is for your knowledge returned by Wolfram Alpha and is not shared by the user. You have to answer question on the basis of it and cite the relevant information from it but you do not have to ### Formatting Instructions
talk about the context in your response. - **Structure**: Use a well-organized format with proper headings (e.g., "## Example heading 1" or "## Example heading 2"). Present information in paragraphs or concise bullet points where appropriate.
- **Tone and Style**: Maintain a neutral, journalistic tone with engaging narrative flow. Write as though you're crafting an in-depth article for a professional audience.
- **Markdown Usage**: Format your response with Markdown for clarity. Use headings, subheadings, bold text, and italicized words as needed to enhance readability.
- **Length and Depth**: Provide comprehensive coverage of the topic. Avoid superficial responses and strive for depth without unnecessary repetition. Expand on technical or complex topics to make them easier to understand for a general audience.
- **No main heading/title**: Start your response directly with the introduction unless asked to provide a specific title.
- **Conclusion or Summary**: Include a concluding paragraph that synthesizes the provided information or suggests potential next steps, where appropriate.
### Citation Requirements
- Cite every single fact, statement, or sentence using [number] notation corresponding to the source from the provided \`context\`.
- Integrate citations naturally at the end of sentences or clauses as appropriate. For example, "The Eiffel Tower is one of the most visited landmarks in the world[1]."
- Ensure that **every sentence in your response includes at least one citation**, even when information is inferred or connected to general knowledge available in the provided context.
- Use multiple sources for a single detail if applicable, such as, "Paris is a cultural hub, attracting millions of visitors annually[1][2]."
- Always prioritize credibility and accuracy by linking all statements back to their respective context sources.
- Avoid citing unsupported assumptions or personal interpretations; if no source supports a statement, clearly indicate the limitation.
### Special Instructions
- If the query involves technical, historical, or complex topics, provide detailed background and explanatory sections to ensure clarity.
- If the user provides vague input or if relevant information is missing, explain what additional details might help refine the search.
- If no relevant information is found, say: "Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?" Be transparent about limitations and suggest alternatives or ways to reframe the query.
- You are set on focus mode 'Wolfram Alpha', this means you will be searching for information on the web using Wolfram Alpha. It is a computational knowledge engine that can answer factual queries and perform computations.
### Example Output
- Begin with a brief introduction summarizing the event or query topic.
- Follow with detailed sections under clear headings, covering all aspects of the query if possible.
- Provide explanations or historical context as needed to enhance understanding.
- End with a conclusion or overall perspective if relevant.
<context> <context>
{context} {context}
</context> </context>
If you think there's nothing relevant in the search results, you can say that 'Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?'. Current date & time in ISO format (UTC timezone) is: {date}.
Anything between the \`context\` is retrieved from Wolfram Alpha and is not a part of the conversation with the user. Today's date is ${new Date().toISOString()}
`; `;

View File

@ -20,23 +20,46 @@ Rephrased question:
`; `;
export const youtubeSearchResponsePrompt = ` export const youtubeSearchResponsePrompt = `
You are Perplexica, an AI model who is expert at searching the web and answering user's queries. You are set on focus mode 'Youtube', this means you will be searching for videos on the web using Youtube and providing information based on the video's transcript. 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.
Generate a response that is informative and relevant to the user's query based on provided context (the context consits of search results containing a brief description of the content of that page). Your task is to provide answers that are:
You must use this context to answer the user's query in the best way possible. Use an unbaised and journalistic tone in your response. Do not repeat the text. - **Informative and relevant**: Thoroughly address the user's query using the given context.
You must not tell the user to open any link or visit any website to get the answer. You must provide the answer in the response itself. If the user asks for links you can provide them. - **Well-structured**: Include clear headings and subheadings, and use a professional tone to present information concisely and logically.
Your responses should be medium to long in length be informative and relevant to the user's query. You can use markdowns to format your response. You should use bullet points to list the information. Make sure the answer is not short and is informative. - **Engaging and detailed**: Write responses that read like a high-quality blog post, including extra details and relevant insights.
You have to cite the answer using [number] notation. You must cite the sentences with their relevent context number. You must cite each and every part of the answer so the user can know where the information is coming from. - **Cited and credible**: Use inline citations with [number] notation to refer to the context source(s) for each fact or detail included.
Place these citations at the end of that particular sentence. You can cite the same sentence multiple times if it is relevant to the user's query like [number1][number2]. - **Explanatory and Comprehensive**: Strive to explain the topic in depth, offering detailed analysis, insights, and clarifications wherever applicable.
However you do not need to cite it using the same number. You can use different numbers to cite the same sentence multiple times. The number refers to the number of the search result (passed in the context) used to generate that part of the answer.
Anything inside the following \`context\` HTML block provided below is for your knowledge returned by Youtube and is not shared by the user. You have to answer question on the basis of it and cite the relevant information from it but you do not have to ### Formatting Instructions
talk about the context in your response. - **Structure**: Use a well-organized format with proper headings (e.g., "## Example heading 1" or "## Example heading 2"). Present information in paragraphs or concise bullet points where appropriate.
- **Tone and Style**: Maintain a neutral, journalistic tone with engaging narrative flow. Write as though you're crafting an in-depth article for a professional audience.
- **Markdown Usage**: Format your response with Markdown for clarity. Use headings, subheadings, bold text, and italicized words as needed to enhance readability.
- **Length and Depth**: Provide comprehensive coverage of the topic. Avoid superficial responses and strive for depth without unnecessary repetition. Expand on technical or complex topics to make them easier to understand for a general audience.
- **No main heading/title**: Start your response directly with the introduction unless asked to provide a specific title.
- **Conclusion or Summary**: Include a concluding paragraph that synthesizes the provided information or suggests potential next steps, where appropriate.
### Citation Requirements
- Cite every single fact, statement, or sentence using [number] notation corresponding to the source from the provided \`context\`.
- Integrate citations naturally at the end of sentences or clauses as appropriate. For example, "The Eiffel Tower is one of the most visited landmarks in the world[1]."
- Ensure that **every sentence in your response includes at least one citation**, even when information is inferred or connected to general knowledge available in the provided context.
- Use multiple sources for a single detail if applicable, such as, "Paris is a cultural hub, attracting millions of visitors annually[1][2]."
- Always prioritize credibility and accuracy by linking all statements back to their respective context sources.
- Avoid citing unsupported assumptions or personal interpretations; if no source supports a statement, clearly indicate the limitation.
### Special Instructions
- If the query involves technical, historical, or complex topics, provide detailed background and explanatory sections to ensure clarity.
- If the user provides vague input or if relevant information is missing, explain what additional details might help refine the search.
- If no relevant information is found, say: "Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?" Be transparent about limitations and suggest alternatives or ways to reframe the query.
- You are set on focus mode 'Youtube', this means you will be searching for videos on the web using Youtube and providing information based on the video's transcrip
### Example Output
- Begin with a brief introduction summarizing the event or query topic.
- Follow with detailed sections under clear headings, covering all aspects of the query if possible.
- Provide explanations or historical context as needed to enhance understanding.
- End with a conclusion or overall perspective if relevant.
<context> <context>
{context} {context}
</context> </context>
If you think there's nothing relevant in the search results, you can say that 'Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?'. Current date & time in ISO format (UTC timezone) is: {date}.
Anything between the \`context\` is retrieved from Youtube and is not a part of the conversation with the user. Today's date is ${new Date().toISOString()}
`; `;

View File

@ -6,6 +6,7 @@ import {
import { import {
getGroqApiKey, getGroqApiKey,
getOllamaApiEndpoint, getOllamaApiEndpoint,
getLMStudioApiEndpoint,
getAnthropicApiKey, getAnthropicApiKey,
getGeminiApiKey, getGeminiApiKey,
getOpenaiApiKey, getOpenaiApiKey,
@ -51,10 +52,11 @@ router.get('/', async (_, res) => {
config['openaiApiKey'] = getOpenaiApiKey(); config['openaiApiKey'] = getOpenaiApiKey();
config['ollamaApiUrl'] = getOllamaApiEndpoint(); config['ollamaApiUrl'] = getOllamaApiEndpoint();
config['lmStudioApiUrl'] = getLMStudioApiEndpoint();
config['anthropicApiKey'] = getAnthropicApiKey(); config['anthropicApiKey'] = getAnthropicApiKey();
config['groqApiKey'] = getGroqApiKey(); config['groqApiKey'] = getGroqApiKey();
config['geminiApiKey'] = getGeminiApiKey(); config['geminiApiKey'] = getGeminiApiKey();
res.status(200).json(config); res.status(200).json(config);
} catch (err: any) { } catch (err: any) {
res.status(500).json({ message: 'An error has occurred.' }); res.status(500).json({ message: 'An error has occurred.' });
@ -74,6 +76,7 @@ router.post('/', async (req, res) => {
}, },
API_ENDPOINTS: { API_ENDPOINTS: {
OLLAMA: config.ollamaApiUrl, OLLAMA: config.ollamaApiUrl,
LMSTUDIO: config.lmStudioApiUrl,
}, },
}; };

View File

@ -211,7 +211,11 @@ class MetaSearchAgent implements MetaSearchAgentType {
const documents = res.results.map( const documents = res.results.map(
(result) => (result) =>
new Document({ new Document({
pageContent: result.content, pageContent:
result.content ||
(this.config.activeEngines.includes('youtube')
? result.title
: '') /* Todo: Implement transcript grabbing using Youtubei (source: https://www.npmjs.com/package/youtubei) */,
metadata: { metadata: {
title: result.title, title: result.title,
url: result.url, url: result.url,
@ -236,6 +240,7 @@ class MetaSearchAgent implements MetaSearchAgentType {
RunnableMap.from({ RunnableMap.from({
query: (input: BasicChainInput) => input.query, query: (input: BasicChainInput) => input.query,
chat_history: (input: BasicChainInput) => input.chat_history, chat_history: (input: BasicChainInput) => input.chat_history,
date: () => new Date().toISOString(),
context: RunnableLambda.from(async (input: BasicChainInput) => { context: RunnableLambda.from(async (input: BasicChainInput) => {
const processedHistory = formatChatHistoryAsString( const processedHistory = formatChatHistoryAsString(
input.chat_history, input.chat_history,
@ -413,7 +418,10 @@ class MetaSearchAgent implements MetaSearchAgentType {
private processDocs(docs: Document[]) { private processDocs(docs: Document[]) {
return docs return docs
.map((_, index) => `${index + 1}. ${docs[index].pageContent}`) .map(
(_, index) =>
`${index + 1}. ${docs[index].metadata.title} ${docs[index].pageContent}`,
)
.join('\n'); .join('\n');
} }

View File

@ -5,7 +5,7 @@ import type { Embeddings } from '@langchain/core/embeddings';
import logger from '../utils/logger'; import logger from '../utils/logger';
import db from '../db'; import db from '../db';
import { chats, messages as messagesSchema } from '../db/schema'; import { chats, messages as messagesSchema } from '../db/schema';
import { eq, asc, gt } from 'drizzle-orm'; import { eq, asc, gt, and } from 'drizzle-orm';
import crypto from 'crypto'; import crypto from 'crypto';
import { getFileDetails } from '../utils/files'; import { getFileDetails } from '../utils/files';
import MetaSearchAgent, { import MetaSearchAgent, {
@ -238,7 +238,12 @@ export const handleMessage = async (
} else { } else {
await db await db
.delete(messagesSchema) .delete(messagesSchema)
.where(gt(messagesSchema.id, messageExists.id)) .where(
and(
gt(messagesSchema.id, messageExists.id),
eq(messagesSchema.chatId, parsedMessage.chatId),
),
)
.execute(); .execute();
} }
} catch (err) { } catch (err) {

View File

@ -9,7 +9,9 @@ import crypto from 'crypto';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { useSearchParams } from 'next/navigation'; import { useSearchParams } from 'next/navigation';
import { getSuggestions } from '@/lib/actions'; import { getSuggestions } from '@/lib/actions';
import Error from 'next/error'; import { Settings } from 'lucide-react';
import SettingsDialog from './SettingsDialog';
import NextError from 'next/error';
export type Message = { export type Message = {
messageId: string; messageId: string;
@ -32,17 +34,38 @@ const useSocket = (
setIsWSReady: (ready: boolean) => void, setIsWSReady: (ready: boolean) => void,
setError: (error: boolean) => void, setError: (error: boolean) => void,
) => { ) => {
const [ws, setWs] = useState<WebSocket | null>(null); const wsRef = useRef<WebSocket | null>(null);
const reconnectTimeoutRef = useRef<NodeJS.Timeout>();
const retryCountRef = useRef(0);
const isCleaningUpRef = useRef(false);
const MAX_RETRIES = 3;
const INITIAL_BACKOFF = 1000; // 1 second
const getBackoffDelay = (retryCount: number) => {
return Math.min(INITIAL_BACKOFF * Math.pow(2, retryCount), 10000); // Cap at 10 seconds
};
useEffect(() => { useEffect(() => {
if (!ws) { const connectWs = async () => {
const connectWs = async () => { if (wsRef.current?.readyState === WebSocket.OPEN) {
wsRef.current.close();
}
try {
let chatModel = localStorage.getItem('chatModel'); let chatModel = localStorage.getItem('chatModel');
let chatModelProvider = localStorage.getItem('chatModelProvider'); let chatModelProvider = localStorage.getItem('chatModelProvider');
let embeddingModel = localStorage.getItem('embeddingModel'); let embeddingModel = localStorage.getItem('embeddingModel');
let embeddingModelProvider = localStorage.getItem( let embeddingModelProvider = localStorage.getItem(
'embeddingModelProvider', 'embeddingModelProvider',
); );
let openAIBaseURL =
chatModelProvider === 'custom_openai'
? localStorage.getItem('openAIBaseURL')
: null;
let openAIPIKey =
chatModelProvider === 'custom_openai'
? localStorage.getItem('openAIApiKey')
: null;
const providers = await fetch( const providers = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/models`, `${process.env.NEXT_PUBLIC_API_URL}/models`,
@ -51,7 +74,13 @@ const useSocket = (
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
}, },
).then(async (res) => await res.json()); ).then(async (res) => {
if (!res.ok)
throw new Error(
`Failed to fetch models: ${res.status} ${res.statusText}`,
);
return res.json();
});
if ( if (
!chatModel || !chatModel ||
@ -62,16 +91,18 @@ const useSocket = (
if (!chatModel || !chatModelProvider) { if (!chatModel || !chatModelProvider) {
const chatModelProviders = providers.chatModelProviders; const chatModelProviders = providers.chatModelProviders;
chatModelProvider = Object.keys(chatModelProviders)[0]; chatModelProvider =
chatModelProvider || Object.keys(chatModelProviders)[0];
if (chatModelProvider === 'custom_openai') { if (chatModelProvider === 'custom_openai') {
toast.error( toast.error(
'Seems like you are using the custom OpenAI provider, please open the settings and configure the API key and base URL', 'Seems like you are using the custom OpenAI provider, please open the settings and enter a model name to use.',
); );
setError(true); setError(true);
return; return;
} else { } else {
chatModel = Object.keys(chatModelProviders[chatModelProvider])[0]; chatModel = Object.keys(chatModelProviders[chatModelProvider])[0];
if ( if (
!chatModelProviders || !chatModelProviders ||
Object.keys(chatModelProviders).length === 0 Object.keys(chatModelProviders).length === 0
@ -108,18 +139,42 @@ const useSocket = (
if ( if (
Object.keys(chatModelProviders).length > 0 && Object.keys(chatModelProviders).length > 0 &&
!chatModelProviders[chatModelProvider] (((!openAIBaseURL || !openAIPIKey) &&
chatModelProvider === 'custom_openai') ||
!chatModelProviders[chatModelProvider])
) { ) {
chatModelProvider = Object.keys(chatModelProviders)[0]; const chatModelProvidersKeys = Object.keys(chatModelProviders);
chatModelProvider =
chatModelProvidersKeys.find(
(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); localStorage.setItem('chatModelProvider', chatModelProvider);
} }
if ( if (
chatModelProvider && chatModelProvider &&
chatModelProvider != 'custom_openai' && (!openAIBaseURL || !openAIPIKey) &&
!chatModelProviders[chatModelProvider][chatModel] !chatModelProviders[chatModelProvider][chatModel]
) { ) {
chatModel = Object.keys(chatModelProviders[chatModelProvider])[0]; chatModel = Object.keys(
chatModelProviders[
Object.keys(chatModelProviders[chatModelProvider]).length > 0
? chatModelProvider
: Object.keys(chatModelProviders)[0]
],
)[0];
localStorage.setItem('chatModel', chatModel); localStorage.setItem('chatModel', chatModel);
} }
@ -168,6 +223,7 @@ const useSocket = (
wsURL.search = searchParams.toString(); wsURL.search = searchParams.toString();
const ws = new WebSocket(wsURL.toString()); const ws = new WebSocket(wsURL.toString());
wsRef.current = ws;
const timeoutId = setTimeout(() => { const timeoutId = setTimeout(() => {
if (ws.readyState !== 1) { if (ws.readyState !== 1) {
@ -183,11 +239,16 @@ const useSocket = (
const interval = setInterval(() => { const interval = setInterval(() => {
if (ws.readyState === 1) { if (ws.readyState === 1) {
setIsWSReady(true); setIsWSReady(true);
setError(false);
if (retryCountRef.current > 0) {
toast.success('Connection restored.');
}
retryCountRef.current = 0;
clearInterval(interval); clearInterval(interval);
} }
}, 5); }, 5);
clearTimeout(timeoutId); clearTimeout(timeoutId);
console.log('[DEBUG] opened'); console.debug(new Date(), 'ws:connected');
} }
if (data.type === 'error') { if (data.type === 'error') {
toast.error(data.data); toast.error(data.data);
@ -196,24 +257,68 @@ const useSocket = (
ws.onerror = () => { ws.onerror = () => {
clearTimeout(timeoutId); clearTimeout(timeoutId);
setError(true); setIsWSReady(false);
toast.error('WebSocket connection error.'); toast.error('WebSocket connection error.');
}; };
ws.onclose = () => { ws.onclose = () => {
clearTimeout(timeoutId); clearTimeout(timeoutId);
setError(true); setIsWSReady(false);
console.log('[DEBUG] closed'); console.debug(new Date(), 'ws:disconnected');
if (!isCleaningUpRef.current) {
toast.error('Connection lost. Attempting to reconnect...');
attemptReconnect();
}
}; };
} catch (error) {
console.debug(new Date(), 'ws:error', error);
setIsWSReady(false);
attemptReconnect();
}
};
setWs(ws); const attemptReconnect = () => {
}; retryCountRef.current += 1;
connectWs(); if (retryCountRef.current > MAX_RETRIES) {
} console.debug(new Date(), 'ws:max_retries');
}, [ws, url, setIsWSReady, setError]); setError(true);
toast.error(
'Unable to connect to server after multiple attempts. Please refresh the page to try again.',
);
return;
}
return ws; const backoffDelay = getBackoffDelay(retryCountRef.current);
console.debug(
new Date(),
`ws:retry attempt=${retryCountRef.current}/${MAX_RETRIES} delay=${backoffDelay}ms`,
);
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current);
}
reconnectTimeoutRef.current = setTimeout(() => {
connectWs();
}, backoffDelay);
};
connectWs();
return () => {
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current);
}
if (wsRef.current?.readyState === WebSocket.OPEN) {
wsRef.current.close();
isCleaningUpRef.current = true;
console.debug(new Date(), 'ws:cleanup');
}
};
}, [url, setIsWSReady, setError]);
return wsRef.current;
}; };
const loadMessages = async ( const loadMessages = async (
@ -257,7 +362,7 @@ const loadMessages = async (
return [msg.role, msg.content]; return [msg.role, msg.content];
}) as [string, string][]; }) as [string, string][];
console.log('[DEBUG] messages loaded'); console.debug(new Date(), 'app:messages_loaded');
document.title = messages[0].content; document.title = messages[0].content;
@ -310,6 +415,8 @@ const ChatWindow = ({ id }: { id?: string }) => {
const [notFound, setNotFound] = useState(false); const [notFound, setNotFound] = useState(false);
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
useEffect(() => { useEffect(() => {
if ( if (
chatId && chatId &&
@ -339,7 +446,7 @@ const ChatWindow = ({ id }: { id?: string }) => {
return () => { return () => {
if (ws?.readyState === 1) { if (ws?.readyState === 1) {
ws.close(); ws.close();
console.log('[DEBUG] closed'); console.debug(new Date(), 'ws:cleanup');
} }
}; };
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
@ -354,12 +461,18 @@ const ChatWindow = ({ id }: { id?: string }) => {
useEffect(() => { useEffect(() => {
if (isMessagesLoaded && isWSReady) { if (isMessagesLoaded && isWSReady) {
setIsReady(true); setIsReady(true);
console.log('[DEBUG] ready'); console.debug(new Date(), 'app:ready');
} else {
setIsReady(false);
} }
}, [isMessagesLoaded, isWSReady]); }, [isMessagesLoaded, isWSReady]);
const sendMessage = async (message: string, messageId?: string) => { const sendMessage = async (message: string, messageId?: string) => {
if (loading) return; if (loading) return;
if (!ws || ws.readyState !== WebSocket.OPEN) {
toast.error('Cannot send message while disconnected');
return;
}
setLoading(true); setLoading(true);
setMessageAppeared(false); setMessageAppeared(false);
@ -370,7 +483,7 @@ const ChatWindow = ({ id }: { id?: string }) => {
messageId = messageId ?? crypto.randomBytes(7).toString('hex'); messageId = messageId ?? crypto.randomBytes(7).toString('hex');
ws?.send( ws.send(
JSON.stringify({ JSON.stringify({
type: 'message', type: 'message',
message: { message: {
@ -514,17 +627,26 @@ const ChatWindow = ({ id }: { id?: string }) => {
if (hasError) { if (hasError) {
return ( return (
<div className="flex flex-col items-center justify-center min-h-screen"> <div className="relative">
<p className="dark:text-white/70 text-black/70 text-sm"> <div className="absolute w-full flex flex-row items-center justify-end mr-5 mt-5">
Failed to connect to the server. Please try again later. <Settings
</p> 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> </div>
); );
} }
return isReady ? ( return isReady ? (
notFound ? ( notFound ? (
<Error statusCode={404} /> <NextError statusCode={404} />
) : ( ) : (
<div> <div>
{messages.length > 0 ? ( {messages.length > 0 ? (

View File

@ -11,6 +11,8 @@ import {
StopCircle, StopCircle,
Layers3, Layers3,
Plus, Plus,
Brain,
ChevronDown,
} from 'lucide-react'; } from 'lucide-react';
import Markdown from 'markdown-to-jsx'; import Markdown from 'markdown-to-jsx';
import Copy from './MessageActions/Copy'; import Copy from './MessageActions/Copy';
@ -41,26 +43,48 @@ const MessageBox = ({
}) => { }) => {
const [parsedMessage, setParsedMessage] = useState(message.content); const [parsedMessage, setParsedMessage] = useState(message.content);
const [speechMessage, setSpeechMessage] = useState(message.content); const [speechMessage, setSpeechMessage] = useState(message.content);
const [thinking, setThinking] = useState<string>('');
const [answer, setAnswer] = useState<string>('');
const [isThinkingExpanded, setIsThinkingExpanded] = useState(false);
useEffect(() => { useEffect(() => {
const regex = /\[(\d+)\]/g; const regex = /\[(\d+)\]/g;
if ( // First check for thinking content
message.role === 'assistant' && const match = message.content.match(/<think>(.*?)<\/think>(.*)/s);
message?.sources && if (match) {
message.sources.length > 0 const [_, thinkingContent, answerContent] = match;
) { setThinking(thinkingContent.trim());
return setParsedMessage( setAnswer(answerContent.trim());
message.content.replace(
regex,
(_, number) =>
`<a href="${message.sources?.[number - 1]?.metadata?.url}" target="_blank" className="bg-light-secondary dark:bg-dark-secondary px-1 rounded ml-1 no-underline text-xs text-black/70 dark:text-white/70 relative">${number}</a>`,
),
);
}
setSpeechMessage(message.content.replace(regex, '')); // Process the answer part for sources if needed
setParsedMessage(message.content); if (message.role === 'assistant' && message?.sources && message.sources.length > 0) {
setParsedMessage(
answerContent.trim().replace(
regex,
(_, number) =>
`<a href="${message.sources?.[number - 1]?.metadata?.url}" target="_blank" className="bg-light-secondary dark:bg-dark-secondary px-1 rounded ml-1 no-underline text-xs text-black/70 dark:text-white/70 relative">${number}</a>`,
),
);
} else {
setParsedMessage(answerContent.trim());
}
setSpeechMessage(answerContent.trim().replace(regex, ''));
} else {
// No thinking content - process as before
if (message.role === 'assistant' && message?.sources && message.sources.length > 0) {
setParsedMessage(
message.content.replace(
regex,
(_, number) =>
`<a href="${message.sources?.[number - 1]?.metadata?.url}" target="_blank" className="bg-light-secondary dark:bg-dark-secondary px-1 rounded ml-1 no-underline text-xs text-black/70 dark:text-white/70 relative">${number}</a>`,
),
);
} else {
setParsedMessage(message.content);
}
setSpeechMessage(message.content.replace(regex, ''));
}
}, [message.content, message.sources, message.role]); }, [message.content, message.sources, message.role]);
const { speechStatus, start, stop } = useSpeech({ text: speechMessage }); const { speechStatus, start, stop } = useSpeech({ text: speechMessage });
@ -81,6 +105,37 @@ const MessageBox = ({
ref={dividerRef} ref={dividerRef}
className="flex flex-col space-y-6 w-full lg:w-9/12" className="flex flex-col space-y-6 w-full lg:w-9/12"
> >
{thinking && (
<div className="flex flex-col space-y-2 mb-4">
<button
onClick={() => setIsThinkingExpanded(!isThinkingExpanded)}
className="flex flex-row items-center space-x-2 group text-black/70 dark:text-white/70 hover:text-black dark:hover:text-white transition duration-200"
>
<Brain size={20} />
<h3 className="font-medium text-xl">View Thinking</h3>
<ChevronDown
size={16}
className={cn(
"transition-transform duration-200",
isThinkingExpanded ? "rotate-180" : ""
)}
/>
</button>
{isThinkingExpanded && (
<div className="rounded-lg bg-light-secondary/50 dark:bg-dark-secondary/50 p-4">
<Markdown
className={cn(
'prose dark:prose-invert text-sm leading-relaxed',
'max-w-none break-words'
)}
>
{thinking}
</Markdown>
</div>
)}
</div>
)}
{message.sources && message.sources.length > 0 && ( {message.sources && message.sources.length > 0 && (
<div className="flex flex-col space-y-2"> <div className="flex flex-col space-y-2">
<div className="flex flex-row items-center space-x-2"> <div className="flex flex-row items-center space-x-2">
@ -107,8 +162,8 @@ const MessageBox = ({
</div> </div>
<Markdown <Markdown
className={cn( className={cn(
'prose dark:prose-invert prose-p:leading-relaxed prose-pre:p-0', 'prose prose-h1:mb-3 prose-h2:mb-2 prose-h2:mt-6 prose-h2:font-[800] prose-h3:mt-4 prose-h3:mb-1.5 prose-h3:font-[600] dark:prose-invert prose-p:leading-relaxed prose-pre:p-0 font-[400]',
'max-w-none break-words text-black dark:text-white text-sm md:text-base font-medium', 'max-w-none break-words text-black dark:text-white',
)} )}
> >
{parsedMessage} {parsedMessage}
@ -199,4 +254,3 @@ const MessageBox = ({
); );
}; };
export default MessageBox;

View File

@ -83,7 +83,7 @@ const Focus = ({
{focusMode !== 'webSearch' ? ( {focusMode !== 'webSearch' ? (
<div className="flex flex-row items-center space-x-1"> <div className="flex flex-row items-center space-x-1">
{focusModes.find((mode) => mode.key === focusMode)?.icon} {focusModes.find((mode) => mode.key === focusMode)?.icon}
<p className="text-xs font-medium"> <p className="text-xs font-medium hidden lg:block">
{focusModes.find((mode) => mode.key === focusMode)?.title} {focusModes.find((mode) => mode.key === focusMode)?.title}
</p> </p>
<ChevronDown size={20} className="-translate-x-1" /> <ChevronDown size={20} className="-translate-x-1" />
@ -91,7 +91,7 @@ const Focus = ({
) : ( ) : (
<div className="flex flex-row items-center space-x-1"> <div className="flex flex-row items-center space-x-1">
<ScanEye size={20} /> <ScanEye size={20} />
<p className="text-xs font-medium">Focus</p> <p className="text-xs font-medium hidden lg:block">Focus</p>
</div> </div>
)} )}
</PopoverButton> </PopoverButton>

View File

@ -1,6 +1,6 @@
/* eslint-disable @next/next/no-img-element */ /* eslint-disable @next/next/no-img-element */
import { PlayCircle, PlayIcon, PlusIcon, VideoIcon } from 'lucide-react'; import { PlayCircle, PlayIcon, PlusIcon, VideoIcon } from 'lucide-react';
import { useState } from 'react'; import { useRef, useState } from 'react';
import Lightbox, { GenericSlide, VideoSlide } from 'yet-another-react-lightbox'; import Lightbox, { GenericSlide, VideoSlide } from 'yet-another-react-lightbox';
import 'yet-another-react-lightbox/styles.css'; import 'yet-another-react-lightbox/styles.css';
import { Message } from './ChatWindow'; import { Message } from './ChatWindow';
@ -35,6 +35,8 @@ const Searchvideos = ({
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [slides, setSlides] = useState<VideoSlide[]>([]); const [slides, setSlides] = useState<VideoSlide[]>([]);
const [currentIndex, setCurrentIndex] = useState(0);
const videoRefs = useRef<(HTMLIFrameElement | null)[]>([]);
return ( return (
<> <>
@ -182,18 +184,39 @@ const Searchvideos = ({
open={open} open={open}
close={() => setOpen(false)} close={() => setOpen(false)}
slides={slides} slides={slides}
index={currentIndex}
on={{
view: ({ index }) => {
const previousIframe = videoRefs.current[currentIndex];
if (previousIframe?.contentWindow) {
previousIframe.contentWindow.postMessage(
'{"event":"command","func":"pauseVideo","args":""}',
'*',
);
}
setCurrentIndex(index);
},
}}
render={{ render={{
slide: ({ slide }) => slide: ({ slide }) => {
slide.type === 'video-slide' ? ( const index = slides.findIndex((s) => s === slide);
return slide.type === 'video-slide' ? (
<div className="h-full w-full flex flex-row items-center justify-center"> <div className="h-full w-full flex flex-row items-center justify-center">
<iframe <iframe
src={slide.iframe_src} src={`${slide.iframe_src}${slide.iframe_src.includes('?') ? '&' : '?'}enablejsapi=1`}
ref={(el) => {
if (el) {
videoRefs.current[index] = el;
}
}}
className="aspect-video max-h-[95vh] w-[95vw] rounded-2xl md:w-[80vw]" className="aspect-video max-h-[95vh] w-[95vw] rounded-2xl md:w-[80vw]"
allowFullScreen allowFullScreen
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
/> />
</div> </div>
) : null, ) : null;
},
}} }}
/> />
</> </>

View File

@ -18,7 +18,7 @@
"clsx": "^2.1.0", "clsx": "^2.1.0",
"langchain": "^0.1.30", "langchain": "^0.1.30",
"lucide-react": "^0.363.0", "lucide-react": "^0.363.0",
"markdown-to-jsx": "^7.6.2", "markdown-to-jsx": "^7.7.2",
"next": "14.1.4", "next": "14.1.4",
"next-themes": "^0.3.0", "next-themes": "^0.3.0",
"react": "^18", "react": "^18",

View File

@ -2210,10 +2210,10 @@ lucide-react@^0.363.0:
resolved "https://registry.yarnpkg.com/lucide-react/-/lucide-react-0.363.0.tgz#2bb1f9d09b830dda86f5118fcd097f87247fe0e3" resolved "https://registry.yarnpkg.com/lucide-react/-/lucide-react-0.363.0.tgz#2bb1f9d09b830dda86f5118fcd097f87247fe0e3"
integrity sha512-AlsfPCsXQyQx7wwsIgzcKOL9LwC498LIMAo+c0Es5PkHJa33xwmYAkkSoKoJWWWSYQEStqu58/jT4tL2gi32uQ== integrity sha512-AlsfPCsXQyQx7wwsIgzcKOL9LwC498LIMAo+c0Es5PkHJa33xwmYAkkSoKoJWWWSYQEStqu58/jT4tL2gi32uQ==
markdown-to-jsx@^7.6.2: markdown-to-jsx@^7.7.2:
version "7.6.2" version "7.7.2"
resolved "https://registry.yarnpkg.com/markdown-to-jsx/-/markdown-to-jsx-7.6.2.tgz#254cbf7d412a37073486c0a2dd52266d2191a793" resolved "https://registry.yarnpkg.com/markdown-to-jsx/-/markdown-to-jsx-7.7.2.tgz#59c1dd64f48b53719311ab140be3cd51cdabccd3"
integrity sha512-gEcyiJXzBxmId2Y/kydLbD6KRNccDiUy/Src1cFGn3s2X0LZZ/hUiEc2VisFyA5kUE3SXclTCczjQiAuqKZiFQ== integrity sha512-N3AKfYRvxNscvcIH6HDnDKILp4S8UWbebp+s92Y8SwIq0CuSbLW4Jgmrbjku3CWKjTQO0OyIMS6AhzqrwjEa3g==
md5@^2.3.0: md5@^2.3.0:
version "2.3.0" version "2.3.0"