Compare commits

..

5 Commits

Author SHA1 Message Date
ItzCrazyKns
639fbd7a15 feat(chat-window): lint & beautify 2024-08-02 19:37:20 +05:30
ItzCrazyKns
a88104434d feat(copilot): respect preferences 2024-08-02 19:36:50 +05:30
ItzCrazyKns
a1e0d368c6 feat(settings): add preferences 2024-08-02 19:36:39 +05:30
ItzCrazyKns
5779701b7d feat(sidebar): respect preferences 2024-08-02 19:35:57 +05:30
ItzCrazyKns
fdfe8d1f41 feat(app): add password auth for settings 2024-08-02 19:32:38 +05:30
57 changed files with 3542 additions and 2193 deletions

View File

@@ -1,73 +0,0 @@
name: Build & Push Docker Images
on:
push:
branches:
- master
release:
types: [published]
jobs:
build-and-push:
runs-on: ubuntu-latest
strategy:
matrix:
service: [backend, app]
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
with:
install: true
- name: Log in to DockerHub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Extract version from release tag
if: github.event_name == 'release'
id: version
run: echo "RELEASE_VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV
- name: Build and push Docker image for ${{ matrix.service }}
if: github.ref == 'refs/heads/master' && github.event_name == 'push'
run: |
docker buildx create --use
if [[ "${{ matrix.service }}" == "backend" ]]; then \
DOCKERFILE=backend.dockerfile; \
IMAGE_NAME=perplexica-backend; \
else \
DOCKERFILE=app.dockerfile; \
IMAGE_NAME=perplexica-frontend; \
fi
docker buildx build --platform linux/amd64,linux/arm64 \
--cache-from=type=registry,ref=itzcrazykns1337/${IMAGE_NAME}:main \
--cache-to=type=inline \
-f $DOCKERFILE \
-t itzcrazykns1337/${IMAGE_NAME}:main \
--push .
- name: Build and push release Docker image for ${{ matrix.service }}
if: github.event_name == 'release'
run: |
docker buildx create --use
if [[ "${{ matrix.service }}" == "backend" ]]; then \
DOCKERFILE=backend.dockerfile; \
IMAGE_NAME=perplexica-backend; \
else \
DOCKERFILE=app.dockerfile; \
IMAGE_NAME=perplexica-frontend; \
fi
docker buildx build --platform linux/amd64,linux/arm64 \
--cache-from=type=registry,ref=itzcrazykns1337/${IMAGE_NAME}:${{ env.RELEASE_VERSION }} \
--cache-to=type=inline \
-f $DOCKERFILE \
-t itzcrazykns1337/${IMAGE_NAME}:${{ env.RELEASE_VERSION }} \
--push .

1
.gitignore vendored
View File

@@ -36,4 +36,3 @@ Thumbs.db
# Db # Db
db.sqlite db.sqlite
/searxng

View File

@@ -12,8 +12,6 @@
- [Non-Docker Installation](#non-docker-installation) - [Non-Docker Installation](#non-docker-installation)
- [Ollama Connection Errors](#ollama-connection-errors) - [Ollama Connection Errors](#ollama-connection-errors)
- [Using as a Search Engine](#using-as-a-search-engine) - [Using as a Search Engine](#using-as-a-search-engine)
- [Using Perplexica's API](#using-perplexicas-api)
- [Expose Perplexica to a network](#expose-perplexica-to-network)
- [One-Click Deployment](#one-click-deployment) - [One-Click Deployment](#one-click-deployment)
- [Upcoming Features](#upcoming-features) - [Upcoming Features](#upcoming-features)
- [Support Us](#support-us) - [Support Us](#support-us)
@@ -47,7 +45,6 @@ Want to know more about its architecture and how it works? You can read it [here
- **Wolfram Alpha Search Mode:** Answers queries that need calculations or data analysis using Wolfram Alpha. - **Wolfram Alpha Search Mode:** Answers queries that need calculations or data analysis using Wolfram Alpha.
- **Reddit Search Mode:** Searches Reddit for discussions and opinions related to the query. - **Reddit Search Mode:** Searches Reddit for discussions and opinions related to the query.
- **Current Information:** Some search tools might give you outdated info because they use data from crawling bots and convert them into embeddings and store them in a index. Unlike them, Perplexica uses SearxNG, a metasearch engine to get the results and rerank and get the most relevant source out of it, ensuring you always get the latest information without the overhead of daily data updates. - **Current Information:** Some search tools might give you outdated info because they use data from crawling bots and convert them into embeddings and store them in a index. Unlike them, Perplexica uses SearxNG, a metasearch engine to get the results and rerank and get the most relevant source out of it, ensuring you always get the latest information without the overhead of daily data updates.
- **API**: Integrate Perplexica into your existing applications and make use of its capibilities.
It has many more features like image and video search. Some of the planned features are mentioned in [upcoming features](#upcoming-features). It has many more features like image and video search. Some of the planned features are mentioned in [upcoming features](#upcoming-features).
@@ -128,16 +125,6 @@ If you wish to use Perplexica as an alternative to traditional search engines li
3. Add a new site search with the following URL: `http://localhost:3000/?q=%s`. Replace `localhost` with your IP address or domain name, and `3000` with the port number if Perplexica is not hosted locally. 3. Add a new site search with the following URL: `http://localhost:3000/?q=%s`. Replace `localhost` with your IP address or domain name, and `3000` with the port number if Perplexica is not hosted locally.
4. Click the add button. Now, you can use Perplexica directly from your browser's search bar. 4. Click the add button. Now, you can use Perplexica directly from your browser's search bar.
## Using Perplexica's API
Perplexica also provides an API for developers looking to integrate its powerful search engine into their own applications. You can run searches, use multiple models and get answers to your queries.
For more details, check out the full documentation [here](https://github.com/ItzCrazyKns/Perplexica/tree/master/docs/API/SEARCH.md).
## Expose Perplexica to network
You can access Perplexica over your home network by following our networking guide [here](https://github.com/ItzCrazyKns/Perplexica/blob/master/docs/installation/NETWORKING.md).
## One-Click Deployment ## One-Click Deployment
[![Deploy to RepoCloud](https://d16t0pc4846x52.cloudfront.net/deploylobe.svg)](https://repocloud.io/details/?app_id=267) [![Deploy to RepoCloud](https://d16t0pc4846x52.cloudfront.net/deploylobe.svg)](https://repocloud.io/details/?app_id=267)
@@ -148,9 +135,8 @@ You can access Perplexica over your home network by following our networking gui
- [x] Adding support for local LLMs - [x] Adding support for local LLMs
- [x] History Saving features - [x] History Saving features
- [x] Introducing various Focus Modes - [x] Introducing various Focus Modes
- [x] Adding API support
- [x] Adding Discover
- [ ] Finalizing Copilot Mode - [ ] Finalizing Copilot Mode
- [ ] Adding Discover
## Support Us ## Support Us

View File

@@ -1,7 +1,7 @@
FROM node:alpine FROM node:alpine
ARG NEXT_PUBLIC_WS_URL=ws://127.0.0.1:3001 ARG NEXT_PUBLIC_WS_URL
ARG NEXT_PUBLIC_API_URL=http://127.0.0.1:3001/api ARG NEXT_PUBLIC_API_URL
ENV NEXT_PUBLIC_WS_URL=${NEXT_PUBLIC_WS_URL} ENV NEXT_PUBLIC_WS_URL=${NEXT_PUBLIC_WS_URL}
ENV NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL} ENV NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL}
@@ -9,7 +9,7 @@ WORKDIR /home/perplexica
COPY ui /home/perplexica/ COPY ui /home/perplexica/
RUN yarn install --frozen-lockfile RUN yarn install
RUN yarn build RUN yarn build
CMD ["yarn", "start"] CMD ["yarn", "start"]

View File

@@ -1,16 +1,21 @@
FROM node:18-slim FROM node:slim
ARG SEARXNG_API_URL
WORKDIR /home/perplexica WORKDIR /home/perplexica
COPY src /home/perplexica/src COPY src /home/perplexica/src
COPY tsconfig.json /home/perplexica/ COPY tsconfig.json /home/perplexica/
COPY config.toml /home/perplexica/
COPY drizzle.config.ts /home/perplexica/ COPY drizzle.config.ts /home/perplexica/
COPY package.json /home/perplexica/ COPY package.json /home/perplexica/
COPY yarn.lock /home/perplexica/ COPY yarn.lock /home/perplexica/
RUN sed -i "s|SEARXNG = \".*\"|SEARXNG = \"${SEARXNG_API_URL}\"|g" /home/perplexica/config.toml
RUN mkdir /home/perplexica/data RUN mkdir /home/perplexica/data
RUN yarn install --frozen-lockfile --network-timeout 600000 RUN yarn install
RUN yarn build RUN yarn build
CMD ["yarn", "start"] CMD ["yarn", "start"]

View File

@@ -13,16 +13,14 @@ services:
build: build:
context: . context: .
dockerfile: backend.dockerfile dockerfile: backend.dockerfile
image: itzcrazykns1337/perplexica-backend:main args:
environment: - SEARXNG_API_URL=http://searxng:8080
- SEARXNG_API_URL=http://searxng:8080
depends_on: depends_on:
- searxng - searxng
ports: ports:
- 3001:3001 - 3001:3001
volumes: volumes:
- backend-dbstore:/home/perplexica/data - backend-dbstore:/home/perplexica/data
- ./config.toml:/home/perplexica/config.toml
extra_hosts: extra_hosts:
- 'host.docker.internal:host-gateway' - 'host.docker.internal:host-gateway'
networks: networks:
@@ -36,7 +34,6 @@ services:
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
image: itzcrazykns1337/perplexica-frontend:main
depends_on: depends_on:
- perplexica-backend - perplexica-backend
ports: ports:

View File

@@ -1,117 +0,0 @@
# Perplexica Search API Documentation
## Overview
Perplexicas Search API makes it easy to use our AI-powered search engine. You can run different types of searches, pick the models you want to use, and get the most recent info. Follow the following headings to learn more about Perplexica's search API.
## Endpoint
### **POST** `http://localhost:3001/api/search`
**Note**: Replace `3001` with any other port if you've changed the default PORT
### Request
The API accepts a JSON object in the request body, where you define the focus mode, chat models, embedding models, and your query.
#### Request Body Structure
```json
{
"chatModel": {
"provider": "openai",
"model": "gpt-4o-mini"
},
"embeddingModel": {
"provider": "openai",
"model": "text-embedding-3-large"
},
"optimizationMode": "speed",
"focusMode": "webSearch",
"query": "What is Perplexica",
"history": [
["human", "Hi, how are you?"],
["assistant", "I am doing well, how can I help you today?"]
]
}
```
### Request Parameters
- **`chatModel`** (object, optional): Defines the chat model to be used for the query. For model details you can send a GET request at `http://localhost:3001/api/models`. Make sure to use the key value (For example "gpt-4o-mini" instead of the display name "GPT 4 omni mini").
- `provider`: Specifies the provider for the chat model (e.g., `openai`, `ollama`).
- `model`: The specific model from the chosen provider (e.g., `gpt-4o-mini`).
- Optional fields for custom OpenAI configuration:
- `customOpenAIBaseURL`: If youre using a custom OpenAI instance, provide the base URL.
- `customOpenAIKey`: The API key for a custom OpenAI instance.
- **`embeddingModel`** (object, optional): Defines the embedding model for similarity-based searching. For model details you can send a GET request at `http://localhost:3001/api/models`. Make sure to use the key value (For example "text-embedding-3-large" instead of the display name "Text Embedding 3 Large").
- `provider`: The provider for the embedding model (e.g., `openai`).
- `model`: The specific embedding model (e.g., `text-embedding-3-large`).
- **`focusMode`** (string, required): Specifies which focus mode to use. Available modes:
- `webSearch`, `academicSearch`, `writingAssistant`, `wolframAlphaSearch`, `youtubeSearch`, `redditSearch`.
- **`optimizationMode`** (string, optional): Specifies the optimization mode to control the balance between performance and quality. Available modes:
- `speed`: Prioritize speed and return the fastest answer.
- `balanced`: Provide a balanced answer with good speed and reasonable quality.
- **`query`** (string, required): The search query or question.
- **`history`** (array, optional): An array of message pairs representing the conversation history. Each pair consists of a role (either 'human' or 'assistant') and the message content. This allows the system to use the context of the conversation to refine results. Example:
```json
[
["human", "What is Perplexica?"],
["assistant", "Perplexica is an AI-powered search engine..."]
]
```
### Response
The response from the API includes both the final message and the sources used to generate that message.
#### Example Response
```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].",
"sources": [
{
"pageContent": "Perplexica is an innovative, open-source AI-powered search engine designed to enhance the way users search for information online.",
"metadata": {
"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"
}
},
{
"pageContent": "Perplexica is an open-source AI-powered search tool that dives deep into the internet to find precise answers.",
"metadata": {
"title": "Sahar Mor's Post",
"url": "https://www.linkedin.com/posts/sahar-mor_a-new-open-source-project-called-perplexica-activity-7204489745668694016-ncja"
}
}
....
]
}
```
### Fields in the Response
- **`message`** (string): The search result, generated based on the query and focus mode.
- **`sources`** (array): A list of sources that were used to generate the search result. Each source includes:
- `pageContent`: A snippet of the relevant content from the source.
- `metadata`: Metadata about the source, including:
- `title`: The title of the webpage.
- `url`: The URL of the webpage.
### Error Handling
If an error occurs during the search process, the API will return an appropriate error message with an HTTP status code.
- **400**: If the request is malformed or missing required fields (e.g., no focus mode or query).
- **500**: If an internal server error occurs during the search.

View File

@@ -10,21 +10,15 @@ To update Perplexica to the latest version, follow these steps:
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. Update and Rebuild Docker Containers:
```bash ```bash
docker compose pull docker compose up -d --build
``` ```
4. Update and Recreate containers. 4. Once the command completes running go to http://localhost:3000 and verify the latest changes.
```bash
docker compose up -d
```
5. Once the command completes running go to http://localhost:3000 and verify the latest changes.
## For non Docker users ## For non Docker users

View File

@@ -1,6 +1,6 @@
{ {
"name": "perplexica-backend", "name": "perplexica-backend",
"version": "1.9.2", "version": "1.9.0-rc1",
"license": "MIT", "license": "MIT",
"author": "ItzCrazyKns", "author": "ItzCrazyKns",
"scripts": { "scripts": {
@@ -18,7 +18,6 @@
"@types/html-to-text": "^9.0.4", "@types/html-to-text": "^9.0.4",
"@types/pdf-parse": "^1.1.4", "@types/pdf-parse": "^1.1.4",
"@types/readable-stream": "^4.0.11", "@types/readable-stream": "^4.0.11",
"@types/ws": "^8.5.12",
"drizzle-kit": "^0.22.7", "drizzle-kit": "^0.22.7",
"nodemon": "^3.1.0", "nodemon": "^3.1.0",
"prettier": "^3.2.5", "prettier": "^3.2.5",

View File

@@ -1,6 +1,10 @@
[GENERAL] [GENERAL]
PORT = 3001 # Port to run the server on PORT = 3001 # Port to run the server on
SIMILARITY_MEASURE = "cosine" # "cosine" or "dot" SIMILARITY_MEASURE = "cosine" # "cosine" or "dot"
CONFIG_PASSWORD = "lorem_ipsum" # Password to access config
DISCOVER_ENABLED = true
LIBRARY_ENABLED = true
COPILOT_ENABLED = true
[API_KEYS] [API_KEYS]
OPENAI = "" # OpenAI API key - sk-1234567890abcdef1234567890abcdef OPENAI = "" # OpenAI API key - sk-1234567890abcdef1234567890abcdef

File diff suppressed because it is too large Load Diff

View File

@@ -19,7 +19,6 @@ import formatChatHistoryAsString from '../utils/formatHistory';
import eventEmitter from 'events'; import eventEmitter from 'events';
import computeSimilarity from '../utils/computeSimilarity'; import computeSimilarity from '../utils/computeSimilarity';
import logger from '../utils/logger'; import logger from '../utils/logger';
import { IterableReadableStream } from '@langchain/core/utils/stream';
const basicAcademicSearchRetrieverPrompt = ` const basicAcademicSearchRetrieverPrompt = `
You will be given a conversation below and a follow up question. You need to rephrase the follow-up question if needed so it is a standalone question that can be used by the LLM to search the web for information. You will be given a conversation below and a follow up question. You need to rephrase the follow-up question if needed so it is a standalone question that can be used by the LLM to search the web for information.
@@ -67,7 +66,7 @@ const basicAcademicSearchResponsePrompt = `
const strParser = new StringOutputParser(); const strParser = new StringOutputParser();
const handleStream = async ( const handleStream = async (
stream: IterableReadableStream<StreamEvent>, stream: AsyncGenerator<StreamEvent, any, unknown>,
emitter: eventEmitter, emitter: eventEmitter,
) => { ) => {
for await (const event of stream) { for await (const event of stream) {
@@ -115,7 +114,12 @@ const createBasicAcademicSearchRetrieverChain = (llm: BaseChatModel) => {
const res = await searchSearxng(input, { const res = await searchSearxng(input, {
language: 'en', language: 'en',
engines: ['arxiv', 'google scholar', 'pubmed'], engines: [
'arxiv',
'google scholar',
'internetarchivescholar',
'pubmed',
],
}); });
const documents = res.results.map( const documents = res.results.map(
@@ -138,7 +142,6 @@ const createBasicAcademicSearchRetrieverChain = (llm: BaseChatModel) => {
const createBasicAcademicSearchAnsweringChain = ( const createBasicAcademicSearchAnsweringChain = (
llm: BaseChatModel, llm: BaseChatModel,
embeddings: Embeddings, embeddings: Embeddings,
optimizationMode: 'speed' | 'balanced' | 'quality',
) => { ) => {
const basicAcademicSearchRetrieverChain = const basicAcademicSearchRetrieverChain =
createBasicAcademicSearchRetrieverChain(llm); createBasicAcademicSearchRetrieverChain(llm);
@@ -164,32 +167,26 @@ const createBasicAcademicSearchAnsweringChain = (
(doc) => doc.pageContent && doc.pageContent.length > 0, (doc) => doc.pageContent && doc.pageContent.length > 0,
); );
if (optimizationMode === 'speed') { const [docEmbeddings, queryEmbedding] = await Promise.all([
return docsWithContent.slice(0, 15); embeddings.embedDocuments(docsWithContent.map((doc) => doc.pageContent)),
} else if (optimizationMode === 'balanced') { embeddings.embedQuery(query),
const [docEmbeddings, queryEmbedding] = await Promise.all([ ]);
embeddings.embedDocuments(
docsWithContent.map((doc) => doc.pageContent),
),
embeddings.embedQuery(query),
]);
const similarity = docEmbeddings.map((docEmbedding, i) => { const similarity = docEmbeddings.map((docEmbedding, i) => {
const sim = computeSimilarity(queryEmbedding, docEmbedding); const sim = computeSimilarity(queryEmbedding, docEmbedding);
return { return {
index: i, index: i,
similarity: sim, similarity: sim,
}; };
}); });
const sortedDocs = similarity const sortedDocs = similarity
.sort((a, b) => b.similarity - a.similarity) .sort((a, b) => b.similarity - a.similarity)
.slice(0, 15) .slice(0, 15)
.map((sim) => docsWithContent[sim.index]); .map((sim) => docsWithContent[sim.index]);
return sortedDocs; return sortedDocs;
}
}; };
return RunnableSequence.from([ return RunnableSequence.from([
@@ -226,17 +223,12 @@ const basicAcademicSearch = (
history: BaseMessage[], history: BaseMessage[],
llm: BaseChatModel, llm: BaseChatModel,
embeddings: Embeddings, embeddings: Embeddings,
optimizationMode: 'speed' | 'balanced' | 'quality',
) => { ) => {
const emitter = new eventEmitter(); const emitter = new eventEmitter();
try { try {
const basicAcademicSearchAnsweringChain = const basicAcademicSearchAnsweringChain =
createBasicAcademicSearchAnsweringChain( createBasicAcademicSearchAnsweringChain(llm, embeddings);
llm,
embeddings,
optimizationMode,
);
const stream = basicAcademicSearchAnsweringChain.streamEvents( const stream = basicAcademicSearchAnsweringChain.streamEvents(
{ {
@@ -265,15 +257,8 @@ const handleAcademicSearch = (
history: BaseMessage[], history: BaseMessage[],
llm: BaseChatModel, llm: BaseChatModel,
embeddings: Embeddings, embeddings: Embeddings,
optimizationMode: 'speed' | 'balanced' | 'quality',
) => { ) => {
const emitter = basicAcademicSearch( const emitter = basicAcademicSearch(message, history, llm, embeddings);
message,
history,
llm,
embeddings,
optimizationMode,
);
return emitter; return emitter;
}; };

View File

@@ -19,7 +19,6 @@ import formatChatHistoryAsString from '../utils/formatHistory';
import eventEmitter from 'events'; import eventEmitter from 'events';
import computeSimilarity from '../utils/computeSimilarity'; import computeSimilarity from '../utils/computeSimilarity';
import logger from '../utils/logger'; import logger from '../utils/logger';
import { IterableReadableStream } from '@langchain/core/utils/stream';
const basicRedditSearchRetrieverPrompt = ` const basicRedditSearchRetrieverPrompt = `
You will be given a conversation below and a follow up question. You need to rephrase the follow-up question if needed so it is a standalone question that can be used by the LLM to search the web for information. You will be given a conversation below and a follow up question. You need to rephrase the follow-up question if needed so it is a standalone question that can be used by the LLM to search the web for information.
@@ -67,7 +66,7 @@ const basicRedditSearchResponsePrompt = `
const strParser = new StringOutputParser(); const strParser = new StringOutputParser();
const handleStream = async ( const handleStream = async (
stream: IterableReadableStream<StreamEvent>, stream: AsyncGenerator<StreamEvent, any, unknown>,
emitter: eventEmitter, emitter: eventEmitter,
) => { ) => {
for await (const event of stream) { for await (const event of stream) {
@@ -138,7 +137,6 @@ const createBasicRedditSearchRetrieverChain = (llm: BaseChatModel) => {
const createBasicRedditSearchAnsweringChain = ( const createBasicRedditSearchAnsweringChain = (
llm: BaseChatModel, llm: BaseChatModel,
embeddings: Embeddings, embeddings: Embeddings,
optimizationMode: 'speed' | 'balanced' | 'quality',
) => { ) => {
const basicRedditSearchRetrieverChain = const basicRedditSearchRetrieverChain =
createBasicRedditSearchRetrieverChain(llm); createBasicRedditSearchRetrieverChain(llm);
@@ -164,33 +162,27 @@ const createBasicRedditSearchAnsweringChain = (
(doc) => doc.pageContent && doc.pageContent.length > 0, (doc) => doc.pageContent && doc.pageContent.length > 0,
); );
if (optimizationMode === 'speed') { const [docEmbeddings, queryEmbedding] = await Promise.all([
return docsWithContent.slice(0, 15); embeddings.embedDocuments(docsWithContent.map((doc) => doc.pageContent)),
} else if (optimizationMode === 'balanced') { embeddings.embedQuery(query),
const [docEmbeddings, queryEmbedding] = await Promise.all([ ]);
embeddings.embedDocuments(
docsWithContent.map((doc) => doc.pageContent),
),
embeddings.embedQuery(query),
]);
const similarity = docEmbeddings.map((docEmbedding, i) => { const similarity = docEmbeddings.map((docEmbedding, i) => {
const sim = computeSimilarity(queryEmbedding, docEmbedding); const sim = computeSimilarity(queryEmbedding, docEmbedding);
return { return {
index: i, index: i,
similarity: sim, similarity: sim,
}; };
}); });
const sortedDocs = similarity const sortedDocs = similarity
.filter((sim) => sim.similarity > 0.3) .filter((sim) => sim.similarity > 0.3)
.sort((a, b) => b.similarity - a.similarity) .sort((a, b) => b.similarity - a.similarity)
.slice(0, 15) .slice(0, 15)
.map((sim) => docsWithContent[sim.index]); .map((sim) => docsWithContent[sim.index]);
return sortedDocs; return sortedDocs;
}
}; };
return RunnableSequence.from([ return RunnableSequence.from([
@@ -227,13 +219,12 @@ const basicRedditSearch = (
history: BaseMessage[], history: BaseMessage[],
llm: BaseChatModel, llm: BaseChatModel,
embeddings: Embeddings, embeddings: Embeddings,
optimizationMode: 'speed' | 'balanced' | 'quality',
) => { ) => {
const emitter = new eventEmitter(); const emitter = new eventEmitter();
try { try {
const basicRedditSearchAnsweringChain = const basicRedditSearchAnsweringChain =
createBasicRedditSearchAnsweringChain(llm, embeddings, optimizationMode); createBasicRedditSearchAnsweringChain(llm, embeddings);
const stream = basicRedditSearchAnsweringChain.streamEvents( const stream = basicRedditSearchAnsweringChain.streamEvents(
{ {
chat_history: history, chat_history: history,
@@ -261,15 +252,8 @@ const handleRedditSearch = (
history: BaseMessage[], history: BaseMessage[],
llm: BaseChatModel, llm: BaseChatModel,
embeddings: Embeddings, embeddings: Embeddings,
optimizationMode: 'speed' | 'balanced' | 'quality',
) => { ) => {
const emitter = basicRedditSearch( const emitter = basicRedditSearch(message, history, llm, embeddings);
message,
history,
llm,
embeddings,
optimizationMode,
);
return emitter; return emitter;
}; };

View File

@@ -22,38 +22,22 @@ import logger from '../utils/logger';
import LineListOutputParser from '../lib/outputParsers/listLineOutputParser'; import LineListOutputParser from '../lib/outputParsers/listLineOutputParser';
import { getDocumentsFromLinks } from '../lib/linkDocument'; import { getDocumentsFromLinks } from '../lib/linkDocument';
import LineOutputParser from '../lib/outputParsers/lineOutputParser'; import LineOutputParser from '../lib/outputParsers/lineOutputParser';
import { IterableReadableStream } from '@langchain/core/utils/stream';
import { ChatOpenAI } from '@langchain/openai';
const basicSearchRetrieverPrompt = ` const basicSearchRetrieverPrompt = `
You are an AI question rephraser. You will be given a conversation and a follow-up question, you will have to rephrase the follow up question so it is a standalone question and can be used by another LLM to search the web for information to answer it. 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 smple writing task or a greeting (unless the greeting contains a question after it) like Hi, Hello, How are you, etc. than a question then you need to return \`not_needed\` as the response (This is because the LLM won't need to search the web for finding information on this topic). If it is a writing task or a simple hi, hello rather than a question, you need to return \`not_needed\` as the response.
If the user asks some question from some URL or wants you to summarize a PDF or a webpage (via URL) you need to return the links inside the \`links\` XML block and the question inside the \`question\` XML block. If the user wants to you to summarize the webpage or the PDF you need to return \`summarize\` inside the \`question\` XML block in place of a question and the link to summarize in the \`links\` XML block. If the question contains some links and asks to answer from those links or even if they don't you need to return the links inside 'links' XML block and the question inside 'question' XML block. If there are no links then you need to return the question without any 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. If the user asks to summarrize the content from some links you need to return \`Summarize\` as the question inside the 'question' XML block and the links inside the 'links' XML block.
There are several examples attached for your reference inside the below \`examples\` XML block Example:
1. Follow up question: What is the capital of France?
Rephrased question: \`Capital of france\`
<examples> 2. Follow up question: What is the population of New York City?
1. Follow up question: What is the capital of France Rephrased question: \`Population of New York City\`
Rephrased question:\`
<question>
Capital of france
</question>
\`
2. Hi, how are you?
Rephrased question\`
<question>
not_needed
</question>
\`
3. Follow up question: What is Docker? 3. Follow up question: What is Docker?
Rephrased question: \` Rephrased question: \`What is Docker\`
<question>
What is Docker
</question>
\`
4. Follow up question: Can you tell me what is X from https://example.com 4. Follow up question: Can you tell me what is X from https://example.com
Rephrased question: \` Rephrased question: \`
@@ -69,20 +53,16 @@ https://example.com
5. Follow up question: Summarize the content from https://example.com 5. Follow up question: Summarize the content from https://example.com
Rephrased question: \` Rephrased question: \`
<question> <question>
summarize Summarize
</question> </question>
<links> <links>
https://example.com https://example.com
</links> </links>
\` \`
</examples>
Anything below is the part of the actual conversation and you need to use conversation and the follow-up question to rephrase the follow-up question as a standalone question based on the guidelines shared above. Conversation:
<conversation>
{chat_history} {chat_history}
</conversation>
Follow up question: {query} Follow up question: {query}
Rephrased question: Rephrased question:
@@ -115,7 +95,7 @@ const basicWebSearchResponsePrompt = `
const strParser = new StringOutputParser(); const strParser = new StringOutputParser();
const handleStream = async ( const handleStream = async (
stream: IterableReadableStream<StreamEvent>, stream: AsyncGenerator<StreamEvent, any, unknown>,
emitter: eventEmitter, emitter: eventEmitter,
) => { ) => {
for await (const event of stream) { for await (const event of stream) {
@@ -152,13 +132,15 @@ type BasicChainInput = {
}; };
const createBasicWebSearchRetrieverChain = (llm: BaseChatModel) => { const createBasicWebSearchRetrieverChain = (llm: BaseChatModel) => {
(llm as unknown as ChatOpenAI).temperature = 0;
return RunnableSequence.from([ return RunnableSequence.from([
PromptTemplate.fromTemplate(basicSearchRetrieverPrompt), PromptTemplate.fromTemplate(basicSearchRetrieverPrompt),
llm, llm,
strParser, strParser,
RunnableLambda.from(async (input: string) => { RunnableLambda.from(async (input: string) => {
if (input === 'not_needed') {
return { query: '', docs: [] };
}
const linksOutputParser = new LineListOutputParser({ const linksOutputParser = new LineListOutputParser({
key: 'links', key: 'links',
}); });
@@ -170,13 +152,9 @@ const createBasicWebSearchRetrieverChain = (llm: BaseChatModel) => {
const links = await linksOutputParser.parse(input); const links = await linksOutputParser.parse(input);
let question = await questionOutputParser.parse(input); let question = await questionOutputParser.parse(input);
if (question === 'not_needed') {
return { query: '', docs: [] };
}
if (links.length > 0) { if (links.length > 0) {
if (question.length === 0) { if (question.length === 0) {
question = 'summarize'; question = 'Summarize';
} }
let docs = []; let docs = [];
@@ -216,54 +194,12 @@ const createBasicWebSearchRetrieverChain = (llm: BaseChatModel) => {
await Promise.all( await Promise.all(
docGroups.map(async (doc) => { docGroups.map(async (doc) => {
const res = await llm.invoke(` const res = await llm.invoke(`
You are a web search summarizer, tasked with summarizing a piece of text retrieved from a web search. Your job is to summarize the You are a text summarizer. You need to summarize the text provided inside the \`text\` XML block.
text into a detailed, 2-4 paragraph explanation that captures the main ideas and provides a comprehensive answer to the query. You need to summarize the text into 1 or 2 sentences capturing the main idea of the text.
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. You need to make sure that you don't miss any point while summarizing the text.
You will also be given a \`query\` XML block which will contain the query of the user. Try to answer the query in the summary from the text provided.
- **Journalistic tone**: The summary should sound professional and journalistic, not too casual or vague. If the query says Summarize then you just need to summarize the text without answering the query.
- **Thorough and detailed**: Ensure that every key point from the text is captured and that the summary directly answers the query. Only return the summarized text without any other messages, text or XML block.
- **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> <query>
${question} ${question}
@@ -290,7 +226,7 @@ const createBasicWebSearchRetrieverChain = (llm: BaseChatModel) => {
return { query: question, docs: docs }; return { query: question, docs: docs };
} else { } else {
const res = await searchSearxng(question, { const res = await searchSearxng(input, {
language: 'en', language: 'en',
}); });
@@ -306,7 +242,7 @@ const createBasicWebSearchRetrieverChain = (llm: BaseChatModel) => {
}), }),
); );
return { query: question, docs: documents }; return { query: input, docs: documents };
} }
}), }),
]); ]);
@@ -315,7 +251,6 @@ const createBasicWebSearchRetrieverChain = (llm: BaseChatModel) => {
const createBasicWebSearchAnsweringChain = ( const createBasicWebSearchAnsweringChain = (
llm: BaseChatModel, llm: BaseChatModel,
embeddings: Embeddings, embeddings: Embeddings,
optimizationMode: 'speed' | 'balanced' | 'quality',
) => { ) => {
const basicWebSearchRetrieverChain = createBasicWebSearchRetrieverChain(llm); const basicWebSearchRetrieverChain = createBasicWebSearchRetrieverChain(llm);
@@ -336,7 +271,7 @@ const createBasicWebSearchAnsweringChain = (
return docs; return docs;
} }
if (query.toLocaleLowerCase() === 'summarize') { if (query === 'Summarize') {
return docs; return docs;
} }
@@ -344,33 +279,27 @@ const createBasicWebSearchAnsweringChain = (
(doc) => doc.pageContent && doc.pageContent.length > 0, (doc) => doc.pageContent && doc.pageContent.length > 0,
); );
if (optimizationMode === 'speed') { const [docEmbeddings, queryEmbedding] = await Promise.all([
return docsWithContent.slice(0, 15); embeddings.embedDocuments(docsWithContent.map((doc) => doc.pageContent)),
} else if (optimizationMode === 'balanced') { embeddings.embedQuery(query),
const [docEmbeddings, queryEmbedding] = await Promise.all([ ]);
embeddings.embedDocuments(
docsWithContent.map((doc) => doc.pageContent),
),
embeddings.embedQuery(query),
]);
const similarity = docEmbeddings.map((docEmbedding, i) => { const similarity = docEmbeddings.map((docEmbedding, i) => {
const sim = computeSimilarity(queryEmbedding, docEmbedding); const sim = computeSimilarity(queryEmbedding, docEmbedding);
return { return {
index: i, index: i,
similarity: sim, similarity: sim,
}; };
}); });
const sortedDocs = similarity const sortedDocs = similarity
.filter((sim) => sim.similarity > 0.3) .filter((sim) => sim.similarity > 0.5)
.sort((a, b) => b.similarity - a.similarity) .sort((a, b) => b.similarity - a.similarity)
.slice(0, 15) .slice(0, 15)
.map((sim) => docsWithContent[sim.index]); .map((sim) => docsWithContent[sim.index]);
return sortedDocs; return sortedDocs;
}
}; };
return RunnableSequence.from([ return RunnableSequence.from([
@@ -407,7 +336,6 @@ const basicWebSearch = (
history: BaseMessage[], history: BaseMessage[],
llm: BaseChatModel, llm: BaseChatModel,
embeddings: Embeddings, embeddings: Embeddings,
optimizationMode: 'speed' | 'balanced' | 'quality',
) => { ) => {
const emitter = new eventEmitter(); const emitter = new eventEmitter();
@@ -415,7 +343,6 @@ const basicWebSearch = (
const basicWebSearchAnsweringChain = createBasicWebSearchAnsweringChain( const basicWebSearchAnsweringChain = createBasicWebSearchAnsweringChain(
llm, llm,
embeddings, embeddings,
optimizationMode,
); );
const stream = basicWebSearchAnsweringChain.streamEvents( const stream = basicWebSearchAnsweringChain.streamEvents(
@@ -445,15 +372,8 @@ const handleWebSearch = (
history: BaseMessage[], history: BaseMessage[],
llm: BaseChatModel, llm: BaseChatModel,
embeddings: Embeddings, embeddings: Embeddings,
optimizationMode: 'speed' | 'balanced' | 'quality',
) => { ) => {
const emitter = basicWebSearch( const emitter = basicWebSearch(message, history, llm, embeddings);
message,
history,
llm,
embeddings,
optimizationMode,
);
return emitter; return emitter;
}; };

View File

@@ -18,7 +18,6 @@ import type { Embeddings } from '@langchain/core/embeddings';
import formatChatHistoryAsString from '../utils/formatHistory'; import formatChatHistoryAsString from '../utils/formatHistory';
import eventEmitter from 'events'; import eventEmitter from 'events';
import logger from '../utils/logger'; import logger from '../utils/logger';
import { IterableReadableStream } from '@langchain/core/utils/stream';
const basicWolframAlphaSearchRetrieverPrompt = ` const basicWolframAlphaSearchRetrieverPrompt = `
You will be given a conversation below and a follow up question. You need to rephrase the follow-up question if needed so it is a standalone question that can be used by the LLM to search the web for information. You will be given a conversation below and a follow up question. You need to rephrase the follow-up question if needed so it is a standalone question that can be used by the LLM to search the web for information.
@@ -66,7 +65,7 @@ const basicWolframAlphaSearchResponsePrompt = `
const strParser = new StringOutputParser(); const strParser = new StringOutputParser();
const handleStream = async ( const handleStream = async (
stream: IterableReadableStream<StreamEvent>, stream: AsyncGenerator<StreamEvent, any, unknown>,
emitter: eventEmitter, emitter: eventEmitter,
) => { ) => {
for await (const event of stream) { for await (const event of stream) {

View File

@@ -10,7 +10,6 @@ import eventEmitter from 'events';
import type { BaseChatModel } from '@langchain/core/language_models/chat_models'; import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
import type { Embeddings } from '@langchain/core/embeddings'; import type { Embeddings } from '@langchain/core/embeddings';
import logger from '../utils/logger'; import logger from '../utils/logger';
import { IterableReadableStream } from '@langchain/core/utils/stream';
const writingAssistantPrompt = ` 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 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.
@@ -20,7 +19,7 @@ Since you are a writing assistant, you would not perform web searches. If you th
const strParser = new StringOutputParser(); const strParser = new StringOutputParser();
const handleStream = async ( const handleStream = async (
stream: IterableReadableStream<StreamEvent>, stream: AsyncGenerator<StreamEvent, any, unknown>,
emitter: eventEmitter, emitter: eventEmitter,
) => { ) => {
for await (const event of stream) { for await (const event of stream) {

View File

@@ -19,7 +19,6 @@ import formatChatHistoryAsString from '../utils/formatHistory';
import eventEmitter from 'events'; import eventEmitter from 'events';
import computeSimilarity from '../utils/computeSimilarity'; import computeSimilarity from '../utils/computeSimilarity';
import logger from '../utils/logger'; import logger from '../utils/logger';
import { IterableReadableStream } from '@langchain/core/utils/stream';
const basicYoutubeSearchRetrieverPrompt = ` const basicYoutubeSearchRetrieverPrompt = `
You will be given a conversation below and a follow up question. You need to rephrase the follow-up question if needed so it is a standalone question that can be used by the LLM to search the web for information. You will be given a conversation below and a follow up question. You need to rephrase the follow-up question if needed so it is a standalone question that can be used by the LLM to search the web for information.
@@ -67,7 +66,7 @@ const basicYoutubeSearchResponsePrompt = `
const strParser = new StringOutputParser(); const strParser = new StringOutputParser();
const handleStream = async ( const handleStream = async (
stream: IterableReadableStream<StreamEvent>, stream: AsyncGenerator<StreamEvent, any, unknown>,
emitter: eventEmitter, emitter: eventEmitter,
) => { ) => {
for await (const event of stream) { for await (const event of stream) {
@@ -138,7 +137,6 @@ const createBasicYoutubeSearchRetrieverChain = (llm: BaseChatModel) => {
const createBasicYoutubeSearchAnsweringChain = ( const createBasicYoutubeSearchAnsweringChain = (
llm: BaseChatModel, llm: BaseChatModel,
embeddings: Embeddings, embeddings: Embeddings,
optimizationMode: 'speed' | 'balanced' | 'quality',
) => { ) => {
const basicYoutubeSearchRetrieverChain = const basicYoutubeSearchRetrieverChain =
createBasicYoutubeSearchRetrieverChain(llm); createBasicYoutubeSearchRetrieverChain(llm);
@@ -164,33 +162,27 @@ const createBasicYoutubeSearchAnsweringChain = (
(doc) => doc.pageContent && doc.pageContent.length > 0, (doc) => doc.pageContent && doc.pageContent.length > 0,
); );
if (optimizationMode === 'speed') { const [docEmbeddings, queryEmbedding] = await Promise.all([
return docsWithContent.slice(0, 15); embeddings.embedDocuments(docsWithContent.map((doc) => doc.pageContent)),
} else { embeddings.embedQuery(query),
const [docEmbeddings, queryEmbedding] = await Promise.all([ ]);
embeddings.embedDocuments(
docsWithContent.map((doc) => doc.pageContent),
),
embeddings.embedQuery(query),
]);
const similarity = docEmbeddings.map((docEmbedding, i) => { const similarity = docEmbeddings.map((docEmbedding, i) => {
const sim = computeSimilarity(queryEmbedding, docEmbedding); const sim = computeSimilarity(queryEmbedding, docEmbedding);
return { return {
index: i, index: i,
similarity: sim, similarity: sim,
}; };
}); });
const sortedDocs = similarity const sortedDocs = similarity
.filter((sim) => sim.similarity > 0.3) .filter((sim) => sim.similarity > 0.3)
.sort((a, b) => b.similarity - a.similarity) .sort((a, b) => b.similarity - a.similarity)
.slice(0, 15) .slice(0, 15)
.map((sim) => docsWithContent[sim.index]); .map((sim) => docsWithContent[sim.index]);
return sortedDocs; return sortedDocs;
}
}; };
return RunnableSequence.from([ return RunnableSequence.from([
@@ -227,13 +219,12 @@ const basicYoutubeSearch = (
history: BaseMessage[], history: BaseMessage[],
llm: BaseChatModel, llm: BaseChatModel,
embeddings: Embeddings, embeddings: Embeddings,
optimizationMode: 'speed' | 'balanced' | 'quality',
) => { ) => {
const emitter = new eventEmitter(); const emitter = new eventEmitter();
try { try {
const basicYoutubeSearchAnsweringChain = const basicYoutubeSearchAnsweringChain =
createBasicYoutubeSearchAnsweringChain(llm, embeddings, optimizationMode); createBasicYoutubeSearchAnsweringChain(llm, embeddings);
const stream = basicYoutubeSearchAnsweringChain.streamEvents( const stream = basicYoutubeSearchAnsweringChain.streamEvents(
{ {
@@ -262,15 +253,8 @@ const handleYoutubeSearch = (
history: BaseMessage[], history: BaseMessage[],
llm: BaseChatModel, llm: BaseChatModel,
embeddings: Embeddings, embeddings: Embeddings,
optimizationMode: 'speed' | 'balanced' | 'quality',
) => { ) => {
const emitter = basicYoutubeSearch( const emitter = basicYoutubeSearch(message, history, llm, embeddings);
message,
history,
llm,
embeddings,
optimizationMode,
);
return emitter; return emitter;
}; };

View File

@@ -8,6 +8,10 @@ interface Config {
GENERAL: { GENERAL: {
PORT: number; PORT: number;
SIMILARITY_MEASURE: string; SIMILARITY_MEASURE: string;
CONFIG_PASSWORD: string;
DISCOVER_ENABLED: boolean;
LIBRARY_ENABLED: boolean;
COPILOT_ENABLED: boolean;
}; };
API_KEYS: { API_KEYS: {
OPENAI: string; OPENAI: string;
@@ -34,14 +38,21 @@ export const getPort = () => loadConfig().GENERAL.PORT;
export const getSimilarityMeasure = () => export const getSimilarityMeasure = () =>
loadConfig().GENERAL.SIMILARITY_MEASURE; loadConfig().GENERAL.SIMILARITY_MEASURE;
export const getConfigPassword = () => loadConfig().GENERAL.CONFIG_PASSWORD;
export const isDiscoverEnabled = () => loadConfig().GENERAL.DISCOVER_ENABLED;
export const isLibraryEnabled = () => loadConfig().GENERAL.LIBRARY_ENABLED;
export const isCopilotEnabled = () => loadConfig().GENERAL.COPILOT_ENABLED;
export const getOpenaiApiKey = () => loadConfig().API_KEYS.OPENAI; export const getOpenaiApiKey = () => loadConfig().API_KEYS.OPENAI;
export const getGroqApiKey = () => loadConfig().API_KEYS.GROQ; export const getGroqApiKey = () => loadConfig().API_KEYS.GROQ;
export const getAnthropicApiKey = () => loadConfig().API_KEYS.ANTHROPIC; export const getAnthropicApiKey = () => loadConfig().API_KEYS.ANTHROPIC;
export const getSearxngApiEndpoint = () => export const getSearxngApiEndpoint = () => loadConfig().API_ENDPOINTS.SEARXNG;
process.env.SEARXNG_API_URL || loadConfig().API_ENDPOINTS.SEARXNG;
export const getOllamaApiEndpoint = () => loadConfig().API_ENDPOINTS.OLLAMA; export const getOllamaApiEndpoint = () => loadConfig().API_ENDPOINTS.OLLAMA;
@@ -54,6 +65,7 @@ export const updateConfig = (config: RecursivePartial<Config>) => {
if (typeof currentConfig[key] === 'object' && currentConfig[key] !== null) { if (typeof currentConfig[key] === 'object' && currentConfig[key] !== null) {
for (const nestedKey in currentConfig[key]) { for (const nestedKey in currentConfig[key]) {
if ( if (
typeof config[key][nestedKey] !== 'boolean' &&
!config[key][nestedKey] && !config[key][nestedKey] &&
currentConfig[key][nestedKey] && currentConfig[key][nestedKey] &&
config[key][nestedKey] !== '' config[key][nestedKey] !== ''

View File

@@ -3,7 +3,6 @@ import { htmlToText } from 'html-to-text';
import { RecursiveCharacterTextSplitter } from 'langchain/text_splitter'; import { RecursiveCharacterTextSplitter } from 'langchain/text_splitter';
import { Document } from '@langchain/core/documents'; import { Document } from '@langchain/core/documents';
import pdfParse from 'pdf-parse'; import pdfParse from 'pdf-parse';
import logger from '../utils/logger';
export const getDocumentsFromLinks = async ({ links }: { links: string[] }) => { export const getDocumentsFromLinks = async ({ links }: { links: string[] }) => {
const splitter = new RecursiveCharacterTextSplitter(); const splitter = new RecursiveCharacterTextSplitter();
@@ -17,81 +16,66 @@ export const getDocumentsFromLinks = async ({ links }: { links: string[] }) => {
? link ? link
: `https://${link}`; : `https://${link}`;
try { const res = await axios.get(link, {
const res = await axios.get(link, { responseType: 'arraybuffer',
responseType: 'arraybuffer', });
});
const isPdf = res.headers['content-type'] === 'application/pdf'; const isPdf = res.headers['content-type'] === 'application/pdf';
if (isPdf) { if (isPdf) {
const pdfText = await pdfParse(res.data); const pdfText = await pdfParse(res.data);
const parsedText = pdfText.text const parsedText = pdfText.text
.replace(/(\r\n|\n|\r)/gm, ' ')
.replace(/\s+/g, ' ')
.trim();
const splittedText = await splitter.splitText(parsedText);
const title = 'PDF Document';
const linkDocs = splittedText.map((text) => {
return new Document({
pageContent: text,
metadata: {
title: title,
url: link,
},
});
});
docs.push(...linkDocs);
return;
}
const parsedText = htmlToText(res.data.toString('utf8'), {
selectors: [
{
selector: 'a',
options: {
ignoreHref: true,
},
},
],
})
.replace(/(\r\n|\n|\r)/gm, ' ') .replace(/(\r\n|\n|\r)/gm, ' ')
.replace(/\s+/g, ' ') .replace(/\s+/g, ' ')
.trim(); .trim();
const splittedText = await splitter.splitText(parsedText); const splittedText = await splitter.splitText(parsedText);
const title = res.data const title = 'PDF Document';
.toString('utf8')
.match(/<title>(.*?)<\/title>/)?.[1];
const linkDocs = splittedText.map((text) => { const linkDocs = splittedText.map((text) => {
return new Document({ return new Document({
pageContent: text, pageContent: text,
metadata: { metadata: {
title: title || link, title: title,
url: link, url: link,
}, },
}); });
}); });
docs.push(...linkDocs); docs.push(...linkDocs);
} catch (err) { return;
logger.error(
`Error at generating documents from links: ${err.message}`,
);
docs.push(
new Document({
pageContent: `Failed to retrieve content from the link: ${err.message}`,
metadata: {
title: 'Failed to retrieve content',
url: link,
},
}),
);
} }
const parsedText = htmlToText(res.data.toString('utf8'), {
selectors: [
{
selector: 'a',
options: {
ignoreHref: true,
},
},
],
})
.replace(/(\r\n|\n|\r)/gm, ' ')
.replace(/\s+/g, ' ')
.trim();
const splittedText = await splitter.splitText(parsedText);
const title = res.data
.toString('utf8')
.match(/<title>(.*?)<\/title>/)?.[1];
const linkDocs = splittedText.map((text) => {
return new Document({
pageContent: text,
metadata: {
title: title || link,
url: link,
},
});
});
docs.push(...linkDocs);
}), }),
); );

View File

@@ -23,7 +23,7 @@ class LineListOutputParser extends BaseOutputParser<string[]> {
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,38 +9,26 @@ export const loadAnthropicChatModels = async () => {
try { try {
const chatModels = { const chatModels = {
'claude-3-5-sonnet-20240620': { 'Claude 3.5 Sonnet': new ChatAnthropic({
displayName: 'Claude 3.5 Sonnet', temperature: 0.7,
model: new ChatAnthropic({ anthropicApiKey: anthropicApiKey,
temperature: 0.7, model: 'claude-3-5-sonnet-20240620',
anthropicApiKey: anthropicApiKey, }),
model: 'claude-3-5-sonnet-20240620', 'Claude 3 Opus': new ChatAnthropic({
}), temperature: 0.7,
}, anthropicApiKey: anthropicApiKey,
'claude-3-opus-20240229': { model: 'claude-3-opus-20240229',
displayName: 'Claude 3 Opus', }),
model: new ChatAnthropic({ 'Claude 3 Sonnet': new ChatAnthropic({
temperature: 0.7, temperature: 0.7,
anthropicApiKey: anthropicApiKey, anthropicApiKey: anthropicApiKey,
model: 'claude-3-opus-20240229', model: 'claude-3-sonnet-20240229',
}), }),
}, 'Claude 3 Haiku': new ChatAnthropic({
'claude-3-sonnet-20240229': { temperature: 0.7,
displayName: 'Claude 3 Sonnet', anthropicApiKey: anthropicApiKey,
model: new ChatAnthropic({ model: 'claude-3-haiku-20240307',
temperature: 0.7, }),
anthropicApiKey: anthropicApiKey,
model: 'claude-3-sonnet-20240229',
}),
},
'claude-3-haiku-20240307': {
displayName: 'Claude 3 Haiku',
model: new ChatAnthropic({
temperature: 0.7,
anthropicApiKey: anthropicApiKey,
model: 'claude-3-haiku-20240307',
}),
},
}; };
return chatModels; return chatModels;

View File

@@ -9,136 +9,76 @@ export const loadGroqChatModels = async () => {
try { try {
const chatModels = { const chatModels = {
'llama-3.2-3b-preview': { 'Llama 3.1 70B': new ChatOpenAI(
displayName: 'Llama 3.2 3B', {
model: new ChatOpenAI( openAIApiKey: groqApiKey,
{ modelName: 'llama-3.1-70b-versatile',
openAIApiKey: groqApiKey, temperature: 0.7,
modelName: 'llama-3.2-3b-preview', },
temperature: 0.7, {
}, baseURL: 'https://api.groq.com/openai/v1',
{ },
baseURL: 'https://api.groq.com/openai/v1', ),
}, 'Llama 3.1 8B': new ChatOpenAI(
), {
}, openAIApiKey: groqApiKey,
'llama-3.2-11b-vision-preview': { modelName: 'llama-3.1-8b-instant',
displayName: 'Llama 3.2 11B Vision', temperature: 0.7,
model: new ChatOpenAI( },
{ {
openAIApiKey: groqApiKey, baseURL: 'https://api.groq.com/openai/v1',
modelName: 'llama-3.2-11b-vision-preview', },
temperature: 0.7, ),
}, 'LLaMA3 8b': new ChatOpenAI(
{ {
baseURL: 'https://api.groq.com/openai/v1', openAIApiKey: groqApiKey,
}, modelName: 'llama3-8b-8192',
), temperature: 0.7,
}, },
'llama-3.2-90b-vision-preview': { {
displayName: 'Llama 3.2 90B Vision', baseURL: 'https://api.groq.com/openai/v1',
model: new ChatOpenAI( },
{ ),
openAIApiKey: groqApiKey, 'LLaMA3 70b': new ChatOpenAI(
modelName: 'llama-3.2-90b-vision-preview', {
temperature: 0.7, openAIApiKey: groqApiKey,
}, modelName: 'llama3-70b-8192',
{ temperature: 0.7,
baseURL: 'https://api.groq.com/openai/v1', },
}, {
), baseURL: 'https://api.groq.com/openai/v1',
}, },
'llama-3.1-70b-versatile': { ),
displayName: 'Llama 3.1 70B', 'Mixtral 8x7b': new ChatOpenAI(
model: new ChatOpenAI( {
{ openAIApiKey: groqApiKey,
openAIApiKey: groqApiKey, modelName: 'mixtral-8x7b-32768',
modelName: 'llama-3.1-70b-versatile', temperature: 0.7,
temperature: 0.7, },
}, {
{ baseURL: 'https://api.groq.com/openai/v1',
baseURL: 'https://api.groq.com/openai/v1', },
}, ),
), 'Gemma 7b': new ChatOpenAI(
}, {
'llama-3.1-8b-instant': { openAIApiKey: groqApiKey,
displayName: 'Llama 3.1 8B', modelName: 'gemma-7b-it',
model: new ChatOpenAI( temperature: 0.7,
{ },
openAIApiKey: groqApiKey, {
modelName: 'llama-3.1-8b-instant', baseURL: 'https://api.groq.com/openai/v1',
temperature: 0.7, },
}, ),
{ 'Gemma2 9b': new ChatOpenAI(
baseURL: 'https://api.groq.com/openai/v1', {
}, openAIApiKey: groqApiKey,
), modelName: 'gemma2-9b-it',
}, temperature: 0.7,
'llama3-8b-8192': { },
displayName: 'LLaMA3 8B', {
model: new ChatOpenAI( baseURL: 'https://api.groq.com/openai/v1',
{ },
openAIApiKey: groqApiKey, ),
modelName: 'llama3-8b-8192',
temperature: 0.7,
},
{
baseURL: 'https://api.groq.com/openai/v1',
},
),
},
'llama3-70b-8192': {
displayName: 'LLaMA3 70B',
model: new ChatOpenAI(
{
openAIApiKey: groqApiKey,
modelName: 'llama3-70b-8192',
temperature: 0.7,
},
{
baseURL: 'https://api.groq.com/openai/v1',
},
),
},
'mixtral-8x7b-32768': {
displayName: 'Mixtral 8x7B',
model: new ChatOpenAI(
{
openAIApiKey: groqApiKey,
modelName: 'mixtral-8x7b-32768',
temperature: 0.7,
},
{
baseURL: 'https://api.groq.com/openai/v1',
},
),
},
'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': {
displayName: 'Gemma2 9B',
model: new ChatOpenAI(
{
openAIApiKey: groqApiKey,
modelName: 'gemma2-9b-it',
temperature: 0.7,
},
{
baseURL: 'https://api.groq.com/openai/v1',
},
),
},
}; };
return chatModels; return chatModels;

View File

@@ -18,15 +18,11 @@ export const loadOllamaChatModels = async () => {
const { models: ollamaModels } = (await response.json()) as any; const { models: ollamaModels } = (await response.json()) as any;
const chatModels = ollamaModels.reduce((acc, model) => { const chatModels = ollamaModels.reduce((acc, model) => {
acc[model.model] = { acc[model.model] = new ChatOllama({
displayName: model.name, baseUrl: ollamaEndpoint,
model: new ChatOllama({ model: model.model,
baseUrl: ollamaEndpoint, temperature: 0.7,
model: model.model, });
temperature: 0.7,
}),
};
return acc; return acc;
}, {}); }, {});
@@ -52,14 +48,10 @@ export const loadOllamaEmbeddingsModels = async () => {
const { models: ollamaModels } = (await response.json()) as any; const { models: ollamaModels } = (await response.json()) as any;
const embeddingsModels = ollamaModels.reduce((acc, model) => { const embeddingsModels = ollamaModels.reduce((acc, model) => {
acc[model.model] = { acc[model.model] = new OllamaEmbeddings({
displayName: model.name, baseUrl: ollamaEndpoint,
model: new OllamaEmbeddings({ model: model.model,
baseUrl: ollamaEndpoint, });
model: model.model,
}),
};
return acc; return acc;
}, {}); }, {});

View File

@@ -9,46 +9,31 @@ export const loadOpenAIChatModels = async () => {
try { try {
const chatModels = { const chatModels = {
'gpt-3.5-turbo': { 'GPT-3.5 turbo': new ChatOpenAI({
displayName: 'GPT-3.5 Turbo', openAIApiKey,
model: new ChatOpenAI({ modelName: 'gpt-3.5-turbo',
openAIApiKey, temperature: 0.7,
modelName: 'gpt-3.5-turbo', }),
temperature: 0.7, 'GPT-4': new ChatOpenAI({
}), openAIApiKey,
}, modelName: 'gpt-4',
'gpt-4': { temperature: 0.7,
displayName: 'GPT-4', }),
model: new ChatOpenAI({ 'GPT-4 turbo': new ChatOpenAI({
openAIApiKey, openAIApiKey,
modelName: 'gpt-4', modelName: 'gpt-4-turbo',
temperature: 0.7, temperature: 0.7,
}), }),
}, 'GPT-4 omni': new ChatOpenAI({
'gpt-4-turbo': { openAIApiKey,
displayName: 'GPT-4 turbo', modelName: 'gpt-4o',
model: new ChatOpenAI({ temperature: 0.7,
openAIApiKey, }),
modelName: 'gpt-4-turbo', 'GPT-4 omni mini': new ChatOpenAI({
temperature: 0.7, openAIApiKey,
}), modelName: 'gpt-4o-mini',
}, temperature: 0.7,
'gpt-4o': { }),
displayName: 'GPT-4 omni',
model: new ChatOpenAI({
openAIApiKey,
modelName: 'gpt-4o',
temperature: 0.7,
}),
},
'gpt-4o-mini': {
displayName: 'GPT-4 omni mini',
model: new ChatOpenAI({
openAIApiKey,
modelName: 'gpt-4o-mini',
temperature: 0.7,
}),
},
}; };
return chatModels; return chatModels;
@@ -65,20 +50,14 @@ export const loadOpenAIEmbeddingsModels = async () => {
try { try {
const embeddingModels = { const embeddingModels = {
'text-embedding-3-small': { 'Text embedding 3 small': new OpenAIEmbeddings({
displayName: 'Text Embedding 3 Small', openAIApiKey,
model: new OpenAIEmbeddings({ modelName: 'text-embedding-3-small',
openAIApiKey, }),
modelName: 'text-embedding-3-small', 'Text embedding 3 large': new OpenAIEmbeddings({
}), openAIApiKey,
}, modelName: 'text-embedding-3-large',
'text-embedding-3-large': { }),
displayName: 'Text Embedding 3 Large',
model: new OpenAIEmbeddings({
openAIApiKey,
modelName: 'text-embedding-3-large',
}),
},
}; };
return embeddingModels; return embeddingModels;

View File

@@ -4,24 +4,15 @@ import { HuggingFaceTransformersEmbeddings } from '../huggingfaceTransformer';
export const loadTransformersEmbeddingsModels = async () => { export const loadTransformersEmbeddingsModels = async () => {
try { try {
const embeddingModels = { const embeddingModels = {
'xenova-bge-small-en-v1.5': { 'BGE Small': new HuggingFaceTransformersEmbeddings({
displayName: 'BGE Small', modelName: 'Xenova/bge-small-en-v1.5',
model: new HuggingFaceTransformersEmbeddings({ }),
modelName: 'Xenova/bge-small-en-v1.5', 'GTE Small': new HuggingFaceTransformersEmbeddings({
}), modelName: 'Xenova/gte-small',
}, }),
'xenova-gte-small': { 'Bert Multilingual': new HuggingFaceTransformersEmbeddings({
displayName: 'GTE Small', modelName: 'Xenova/bert-base-multilingual-uncased',
model: new HuggingFaceTransformersEmbeddings({ }),
modelName: 'Xenova/gte-small',
}),
},
'xenova-bert-base-multilingual-uncased': {
displayName: 'Bert Multilingual',
model: new HuggingFaceTransformersEmbeddings({
modelName: 'Xenova/bert-base-multilingual-uncased',
}),
},
}; };
return embeddingModels; return embeddingModels;

View File

@@ -9,61 +9,73 @@ import {
getAnthropicApiKey, getAnthropicApiKey,
getOpenaiApiKey, getOpenaiApiKey,
updateConfig, updateConfig,
getConfigPassword,
isLibraryEnabled,
isCopilotEnabled,
isDiscoverEnabled,
} from '../config'; } from '../config';
import logger from '../utils/logger';
const router = express.Router(); const router = express.Router();
router.get('/', async (_, res) => { router.get('/', async (req, res) => {
try { const authHeader = req.headers['authorization']?.split(' ')[1];
const config = {}; const password = getConfigPassword();
const [chatModelProviders, embeddingModelProviders] = await Promise.all([ if (authHeader !== password) {
getAvailableChatModelProviders(), res.status(401).json({ message: 'Unauthorized' });
getAvailableEmbeddingModelProviders(), return;
]);
config['chatModelProviders'] = {};
config['embeddingModelProviders'] = {};
for (const provider in chatModelProviders) {
config['chatModelProviders'][provider] = Object.keys(
chatModelProviders[provider],
).map((model) => {
return {
name: model,
displayName: chatModelProviders[provider][model].displayName,
};
});
}
for (const provider in embeddingModelProviders) {
config['embeddingModelProviders'][provider] = Object.keys(
embeddingModelProviders[provider],
).map((model) => {
return {
name: model,
displayName: embeddingModelProviders[provider][model].displayName,
};
});
}
config['openaiApiKey'] = getOpenaiApiKey();
config['ollamaApiUrl'] = getOllamaApiEndpoint();
config['anthropicApiKey'] = getAnthropicApiKey();
config['groqApiKey'] = getGroqApiKey();
res.status(200).json(config);
} catch (err: any) {
res.status(500).json({ message: 'An error has occurred.' });
logger.error(`Error getting config: ${err.message}`);
} }
const config = {};
const [chatModelProviders, embeddingModelProviders] = await Promise.all([
getAvailableChatModelProviders(),
getAvailableEmbeddingModelProviders(),
]);
config['chatModelProviders'] = {};
config['embeddingModelProviders'] = {};
for (const provider in chatModelProviders) {
config['chatModelProviders'][provider] = Object.keys(
chatModelProviders[provider],
);
}
for (const provider in embeddingModelProviders) {
config['embeddingModelProviders'][provider] = Object.keys(
embeddingModelProviders[provider],
);
}
config['openaiApiKey'] = getOpenaiApiKey();
config['ollamaApiUrl'] = getOllamaApiEndpoint();
config['anthropicApiKey'] = getAnthropicApiKey();
config['groqApiKey'] = getGroqApiKey();
config['isLibraryEnabled'] = isLibraryEnabled();
config['isCopilotEnabled'] = isCopilotEnabled();
config['isDiscoverEnabled'] = isDiscoverEnabled();
res.status(200).json(config);
}); });
router.post('/', async (req, res) => { router.post('/', async (req, res) => {
const authHeader = req.headers['authorization']?.split(' ')[1];
const password = getConfigPassword();
if (authHeader !== password) {
res.status(401).json({ message: 'Unauthorized' });
return;
}
const config = req.body; const config = req.body;
const updatedConfig = { const updatedConfig = {
GENERAL: {
DISCOVER_ENABLED: config.isDiscoverEnabled,
LIBRARY_ENABLED: config.isLibraryEnabled,
COPILOT_ENABLED: config.isCopilotEnabled,
},
API_KEYS: { API_KEYS: {
OPENAI: config.openaiApiKey, OPENAI: config.openaiApiKey,
GROQ: config.groqApiKey, GROQ: config.groqApiKey,
@@ -79,4 +91,14 @@ router.post('/', async (req, res) => {
res.status(200).json({ message: 'Config updated' }); res.status(200).json({ message: 'Config updated' });
}); });
router.get('/preferences', (_, res) => {
const preferences = {
isLibraryEnabled: isLibraryEnabled(),
isCopilotEnabled: isCopilotEnabled(),
isDiscoverEnabled: isDiscoverEnabled(),
};
res.status(200).json(preferences);
});
export default router; export default router;

View File

@@ -1,48 +0,0 @@
import express from 'express';
import { searchSearxng } from '../lib/searxng';
import logger from '../utils/logger';
const router = express.Router();
router.get('/', async (req, res) => {
try {
const data = (
await Promise.all([
searchSearxng('site:businessinsider.com AI', {
engines: ['bing news'],
pageno: 1,
}),
searchSearxng('site:www.exchangewire.com AI', {
engines: ['bing news'],
pageno: 1,
}),
searchSearxng('site:yahoo.com AI', {
engines: ['bing news'],
pageno: 1,
}),
searchSearxng('site:businessinsider.com tech', {
engines: ['bing news'],
pageno: 1,
}),
searchSearxng('site:www.exchangewire.com tech', {
engines: ['bing news'],
pageno: 1,
}),
searchSearxng('site:yahoo.com tech', {
engines: ['bing news'],
pageno: 1,
}),
])
)
.map((result) => result.results)
.flat()
.sort(() => Math.random() - 0.5);
return res.json({ blogs: data });
} catch (err: any) {
logger.error(`Error in discover route: ${err.message}`);
return res.status(500).json({ message: 'An error has occurred' });
}
});
export default router;

View File

@@ -4,28 +4,14 @@ import { BaseChatModel } from '@langchain/core/language_models/chat_models';
import { getAvailableChatModelProviders } from '../lib/providers'; import { getAvailableChatModelProviders } from '../lib/providers';
import { HumanMessage, AIMessage } from '@langchain/core/messages'; import { HumanMessage, AIMessage } from '@langchain/core/messages';
import logger from '../utils/logger'; import logger from '../utils/logger';
import { ChatOpenAI } from '@langchain/openai';
const router = express.Router(); const router = express.Router();
interface ChatModel {
provider: string;
model: string;
customOpenAIBaseURL?: string;
customOpenAIKey?: string;
}
interface ImageSearchBody {
query: string;
chatHistory: any[];
chatModel?: ChatModel;
}
router.post('/', async (req, res) => { router.post('/', async (req, res) => {
try { try {
let body: ImageSearchBody = req.body; let { query, chat_history, chat_model_provider, chat_model } = req.body;
const chatHistory = body.chatHistory.map((msg: any) => { chat_history = chat_history.map((msg: any) => {
if (msg.role === 'user') { if (msg.role === 'user') {
return new HumanMessage(msg.content); return new HumanMessage(msg.content);
} else if (msg.role === 'assistant') { } else if (msg.role === 'assistant') {
@@ -33,50 +19,22 @@ router.post('/', async (req, res) => {
} }
}); });
const chatModelProviders = await getAvailableChatModelProviders(); const chatModels = await getAvailableChatModelProviders();
const provider = chat_model_provider ?? Object.keys(chatModels)[0];
const chatModelProvider = const chatModel = chat_model ?? Object.keys(chatModels[provider])[0];
body.chatModel?.provider || Object.keys(chatModelProviders)[0];
const chatModel =
body.chatModel?.model ||
Object.keys(chatModelProviders[chatModelProvider])[0];
let llm: BaseChatModel | undefined; let llm: BaseChatModel | undefined;
if (body.chatModel?.provider === 'custom_openai') { if (chatModels[provider] && chatModels[provider][chatModel]) {
if ( llm = chatModels[provider][chatModel] as BaseChatModel | undefined;
!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,
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 (!llm) { if (!llm) {
return res.status(400).json({ message: 'Invalid model selected' }); res.status(500).json({ message: 'Invalid LLM model selected' });
return;
} }
const images = await handleImageSearch( const images = await handleImageSearch({ query, chat_history }, llm);
{ query: body.query, chat_history: chatHistory },
llm,
);
res.status(200).json({ images }); res.status(200).json({ images });
} catch (err) { } catch (err) {

View File

@@ -5,8 +5,6 @@ import configRouter from './config';
import modelsRouter from './models'; import modelsRouter from './models';
import suggestionsRouter from './suggestions'; import suggestionsRouter from './suggestions';
import chatsRouter from './chats'; import chatsRouter from './chats';
import searchRouter from './search';
import discoverRouter from './discover';
const router = express.Router(); const router = express.Router();
@@ -16,7 +14,5 @@ router.use('/config', configRouter);
router.use('/models', modelsRouter); router.use('/models', modelsRouter);
router.use('/suggestions', suggestionsRouter); router.use('/suggestions', suggestionsRouter);
router.use('/chats', chatsRouter); router.use('/chats', chatsRouter);
router.use('/search', searchRouter);
router.use('/discover', discoverRouter);
export default router; export default router;

View File

@@ -9,20 +9,31 @@ const router = express.Router();
router.get('/', async (req, res) => { router.get('/', async (req, res) => {
try { try {
const [chatModelProviders, embeddingModelProviders] = await Promise.all([ const [chatModelProvidersRaw, embeddingModelProvidersRaw] =
getAvailableChatModelProviders(), await Promise.all([
getAvailableEmbeddingModelProviders(), getAvailableChatModelProviders(),
]); getAvailableEmbeddingModelProviders(),
]);
Object.keys(chatModelProviders).forEach((provider) => { const chatModelProviders = {};
Object.keys(chatModelProviders[provider]).forEach((model) => {
delete chatModelProviders[provider][model].model; const chatModelProvidersKeys = Object.keys(chatModelProvidersRaw);
chatModelProvidersKeys.forEach((provider) => {
chatModelProviders[provider] = {};
const models = Object.keys(chatModelProvidersRaw[provider]);
models.forEach((model) => {
chatModelProviders[provider][model] = {};
}); });
}); });
Object.keys(embeddingModelProviders).forEach((provider) => { const embeddingModelProviders = {};
Object.keys(embeddingModelProviders[provider]).forEach((model) => {
delete embeddingModelProviders[provider][model].model; const embeddingModelProvidersKeys = Object.keys(embeddingModelProvidersRaw);
embeddingModelProvidersKeys.forEach((provider) => {
embeddingModelProviders[provider] = {};
const models = Object.keys(embeddingModelProvidersRaw[provider]);
models.forEach((model) => {
embeddingModelProviders[provider][model] = {};
}); });
}); });

View File

@@ -1,158 +0,0 @@
import express from 'express';
import logger from '../utils/logger';
import { BaseChatModel } from 'langchain/chat_models/base';
import { Embeddings } from 'langchain/embeddings/base';
import { ChatOpenAI } from '@langchain/openai';
import {
getAvailableChatModelProviders,
getAvailableEmbeddingModelProviders,
} from '../lib/providers';
import { searchHandlers } from '../websocket/messageHandler';
import { AIMessage, BaseMessage, HumanMessage } from '@langchain/core/messages';
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;
if (!body.focusMode || !body.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
) {
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) {
return res.status(400).json({ message: 'Invalid model selected' });
}
const searchHandler = searchHandlers[body.focusMode];
if (!searchHandler) {
return res.status(400).json({ message: 'Invalid focus mode' });
}
const emitter = searchHandler(
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', () => {
res.status(200).json({ message, sources });
});
emitter.on('error', (data) => {
const parsedData = JSON.parse(data);
res.status(500).json({ message: parsedData.data });
});
} catch (err: any) {
logger.error(`Error in getting search results: ${err.message}`);
res.status(500).json({ message: 'An error has occurred.' });
}
});
export default router;

View File

@@ -4,27 +4,14 @@ import { BaseChatModel } from '@langchain/core/language_models/chat_models';
import { getAvailableChatModelProviders } from '../lib/providers'; import { getAvailableChatModelProviders } from '../lib/providers';
import { HumanMessage, AIMessage } from '@langchain/core/messages'; import { HumanMessage, AIMessage } from '@langchain/core/messages';
import logger from '../utils/logger'; import logger from '../utils/logger';
import { ChatOpenAI } from '@langchain/openai';
const router = express.Router(); const router = express.Router();
interface ChatModel {
provider: string;
model: string;
customOpenAIBaseURL?: string;
customOpenAIKey?: string;
}
interface SuggestionsBody {
chatHistory: any[];
chatModel?: ChatModel;
}
router.post('/', async (req, res) => { router.post('/', async (req, res) => {
try { try {
let body: SuggestionsBody = req.body; let { chat_history, chat_model, chat_model_provider } = req.body;
const chatHistory = body.chatHistory.map((msg: any) => { chat_history = chat_history.map((msg: any) => {
if (msg.role === 'user') { if (msg.role === 'user') {
return new HumanMessage(msg.content); return new HumanMessage(msg.content);
} else if (msg.role === 'assistant') { } else if (msg.role === 'assistant') {
@@ -32,50 +19,22 @@ router.post('/', async (req, res) => {
} }
}); });
const chatModelProviders = await getAvailableChatModelProviders(); const chatModels = await getAvailableChatModelProviders();
const provider = chat_model_provider ?? Object.keys(chatModels)[0];
const chatModelProvider = const chatModel = chat_model ?? Object.keys(chatModels[provider])[0];
body.chatModel?.provider || Object.keys(chatModelProviders)[0];
const chatModel =
body.chatModel?.model ||
Object.keys(chatModelProviders[chatModelProvider])[0];
let llm: BaseChatModel | undefined; let llm: BaseChatModel | undefined;
if (body.chatModel?.provider === 'custom_openai') { if (chatModels[provider] && chatModels[provider][chatModel]) {
if ( llm = chatModels[provider][chatModel] as BaseChatModel | undefined;
!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,
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 (!llm) { if (!llm) {
return res.status(400).json({ message: 'Invalid model selected' }); res.status(500).json({ message: 'Invalid LLM model selected' });
return;
} }
const suggestions = await generateSuggestions( const suggestions = await generateSuggestions({ chat_history }, llm);
{ chat_history: chatHistory },
llm,
);
res.status(200).json({ suggestions: suggestions }); res.status(200).json({ suggestions: suggestions });
} catch (err) { } catch (err) {

View File

@@ -4,28 +4,14 @@ import { getAvailableChatModelProviders } from '../lib/providers';
import { HumanMessage, AIMessage } from '@langchain/core/messages'; import { HumanMessage, AIMessage } from '@langchain/core/messages';
import logger from '../utils/logger'; import logger from '../utils/logger';
import handleVideoSearch from '../agents/videoSearchAgent'; import handleVideoSearch from '../agents/videoSearchAgent';
import { ChatOpenAI } from '@langchain/openai';
const router = express.Router(); const router = express.Router();
interface ChatModel {
provider: string;
model: string;
customOpenAIBaseURL?: string;
customOpenAIKey?: string;
}
interface VideoSearchBody {
query: string;
chatHistory: any[];
chatModel?: ChatModel;
}
router.post('/', async (req, res) => { router.post('/', async (req, res) => {
try { try {
let body: VideoSearchBody = req.body; let { query, chat_history, chat_model_provider, chat_model } = req.body;
const chatHistory = body.chatHistory.map((msg: any) => { chat_history = chat_history.map((msg: any) => {
if (msg.role === 'user') { if (msg.role === 'user') {
return new HumanMessage(msg.content); return new HumanMessage(msg.content);
} else if (msg.role === 'assistant') { } else if (msg.role === 'assistant') {
@@ -33,50 +19,22 @@ router.post('/', async (req, res) => {
} }
}); });
const chatModelProviders = await getAvailableChatModelProviders(); const chatModels = await getAvailableChatModelProviders();
const provider = chat_model_provider ?? Object.keys(chatModels)[0];
const chatModelProvider = const chatModel = chat_model ?? Object.keys(chatModels[provider])[0];
body.chatModel?.provider || Object.keys(chatModelProviders)[0];
const chatModel =
body.chatModel?.model ||
Object.keys(chatModelProviders[chatModelProvider])[0];
let llm: BaseChatModel | undefined; let llm: BaseChatModel | undefined;
if (body.chatModel?.provider === 'custom_openai') { if (chatModels[provider] && chatModels[provider][chatModel]) {
if ( llm = chatModels[provider][chatModel] as BaseChatModel | undefined;
!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,
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 (!llm) { if (!llm) {
return res.status(400).json({ message: 'Invalid model selected' }); res.status(500).json({ message: 'Invalid LLM model selected' });
return;
} }
const videos = await handleVideoSearch( const videos = await handleVideoSearch({ chat_history, query }, llm);
{ chat_history: chatHistory, query: body.query },
llm,
);
res.status(200).json({ videos }); res.status(200).json({ videos });
} catch (err) { } catch (err) {

View File

@@ -45,8 +45,9 @@ export const handleConnection = async (
chatModelProviders[chatModelProvider][chatModel] && chatModelProviders[chatModelProvider][chatModel] &&
chatModelProvider != 'custom_openai' chatModelProvider != 'custom_openai'
) { ) {
llm = chatModelProviders[chatModelProvider][chatModel] llm = chatModelProviders[chatModelProvider][chatModel] as unknown as
.model as unknown as BaseChatModel | undefined; | BaseChatModel
| undefined;
} else if (chatModelProvider == 'custom_openai') { } else if (chatModelProvider == 'custom_openai') {
llm = new ChatOpenAI({ llm = new ChatOpenAI({
modelName: chatModel, modelName: chatModel,
@@ -64,7 +65,7 @@ export const handleConnection = async (
) { ) {
embeddings = embeddingModelProviders[embeddingModelProvider][ embeddings = embeddingModelProviders[embeddingModelProvider][
embeddingModel embeddingModel
].model as Embeddings | undefined; ] as Embeddings | undefined;
} }
if (!llm || !embeddings) { if (!llm || !embeddings) {
@@ -78,18 +79,6 @@ export const handleConnection = async (
ws.close(); ws.close();
} }
const interval = setInterval(() => {
if (ws.readyState === ws.OPEN) {
ws.send(
JSON.stringify({
type: 'signal',
data: 'open',
}),
);
clearInterval(interval);
}
}, 5);
ws.on( ws.on(
'message', 'message',
async (message) => async (message) =>

View File

@@ -10,9 +10,10 @@ import type { BaseChatModel } from '@langchain/core/language_models/chat_models'
import type { Embeddings } from '@langchain/core/embeddings'; 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 } from '../db/schema';
import { eq, asc, gt } from 'drizzle-orm'; import { eq } from 'drizzle-orm';
import crypto from 'crypto'; import crypto from 'crypto';
import { isLibraryEnabled } from '../config';
type Message = { type Message = {
messageId: string; messageId: string;
@@ -22,13 +23,13 @@ type Message = {
type WSMessage = { type WSMessage = {
message: Message; message: Message;
optimizationMode: string; copilot: boolean;
type: string; type: string;
focusMode: string; focusMode: string;
history: Array<[string, string]>; history: Array<[string, string]>;
}; };
export const searchHandlers = { const searchHandlers = {
webSearch: handleWebSearch, webSearch: handleWebSearch,
academicSearch: handleAcademicSearch, academicSearch: handleAcademicSearch,
writingAssistant: handleWritingAssistant, writingAssistant: handleWritingAssistant,
@@ -46,6 +47,8 @@ const handleEmitterEvents = (
let recievedMessage = ''; let recievedMessage = '';
let sources = []; let sources = [];
const libraryEnabled = isLibraryEnabled();
emitter.on('data', (data) => { emitter.on('data', (data) => {
const parsedData = JSON.parse(data); const parsedData = JSON.parse(data);
if (parsedData.type === 'response') { if (parsedData.type === 'response') {
@@ -71,18 +74,20 @@ const handleEmitterEvents = (
emitter.on('end', () => { emitter.on('end', () => {
ws.send(JSON.stringify({ type: 'messageEnd', messageId: messageId })); ws.send(JSON.stringify({ type: 'messageEnd', messageId: messageId }));
db.insert(messagesSchema) if (libraryEnabled) {
.values({ db.insert(messages)
content: recievedMessage, .values({
chatId: chatId, content: recievedMessage,
messageId: messageId, chatId: chatId,
role: 'assistant', messageId: messageId,
metadata: JSON.stringify({ role: 'assistant',
createdAt: new Date(), metadata: JSON.stringify({
...(sources && sources.length > 0 && { sources }), createdAt: new Date(),
}), ...(sources && sources.length > 0 && { sources }),
}) }),
.execute(); })
.execute();
}
}); });
emitter.on('error', (data) => { emitter.on('error', (data) => {
const parsedData = JSON.parse(data); const parsedData = JSON.parse(data);
@@ -106,9 +111,7 @@ export const handleMessage = async (
const parsedWSMessage = JSON.parse(message) as WSMessage; const parsedWSMessage = JSON.parse(message) as WSMessage;
const parsedMessage = parsedWSMessage.message; const parsedMessage = parsedWSMessage.message;
const humanMessageId = const id = crypto.randomBytes(7).toString('hex');
parsedMessage.messageId ?? crypto.randomBytes(7).toString('hex');
const aiMessageId = crypto.randomBytes(7).toString('hex');
if (!parsedMessage.content) if (!parsedMessage.content)
return ws.send( return ws.send(
@@ -134,55 +137,47 @@ export const handleMessage = async (
if (parsedWSMessage.type === 'message') { if (parsedWSMessage.type === 'message') {
const handler = searchHandlers[parsedWSMessage.focusMode]; const handler = searchHandlers[parsedWSMessage.focusMode];
const libraryEnabled = isLibraryEnabled();
if (handler) { if (handler) {
const emitter = handler( const emitter = handler(
parsedMessage.content, parsedMessage.content,
history, history,
llm, llm,
embeddings, embeddings,
parsedWSMessage.optimizationMode,
); );
handleEmitterEvents(emitter, ws, aiMessageId, parsedMessage.chatId); handleEmitterEvents(emitter, ws, id, parsedMessage.chatId);
const chat = await db.query.chats.findFirst({ if (libraryEnabled) {
where: eq(chats.id, parsedMessage.chatId), const chat = await db.query.chats.findFirst({
}); where: eq(chats.id, parsedMessage.chatId),
});
if (!chat) {
await db
.insert(chats)
.values({
id: parsedMessage.chatId,
title: parsedMessage.content,
createdAt: new Date().toString(),
focusMode: parsedWSMessage.focusMode,
})
.execute();
}
if (!chat) {
await db await db
.insert(chats) .insert(messages)
.values({
id: parsedMessage.chatId,
title: parsedMessage.content,
createdAt: new Date().toString(),
focusMode: parsedWSMessage.focusMode,
})
.execute();
}
const messageExists = await db.query.messages.findFirst({
where: eq(messagesSchema.messageId, humanMessageId),
});
if (!messageExists) {
await db
.insert(messagesSchema)
.values({ .values({
content: parsedMessage.content, content: parsedMessage.content,
chatId: parsedMessage.chatId, chatId: parsedMessage.chatId,
messageId: humanMessageId, messageId: id,
role: 'user', role: 'user',
metadata: JSON.stringify({ metadata: JSON.stringify({
createdAt: new Date(), createdAt: new Date(),
}), }),
}) })
.execute(); .execute();
} else {
await db
.delete(messagesSchema)
.where(gt(messagesSchema.id, messageExists.id))
.execute();
} }
} else { } else {
ws.send( ws.send(

View File

@@ -1,112 +0,0 @@
'use client';
import { Search } from 'lucide-react';
import { useEffect, useState } from 'react';
import Link from 'next/link';
import { toast } from 'sonner';
interface Discover {
title: string;
content: string;
url: string;
thumbnail: string;
}
const Page = () => {
const [discover, setDiscover] = useState<Discover[] | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
try {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/discover`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
const data = await res.json();
if (!res.ok) {
throw new Error(data.message);
}
data.blogs = data.blogs.filter((blog: Discover) => blog.thumbnail);
setDiscover(data.blogs);
} catch (err: any) {
console.error('Error fetching data:', err.message);
toast.error('Error fetching data');
} finally {
setLoading(false);
}
};
fetchData();
}, []);
return loading ? (
<div className="flex flex-row items-center justify-center min-h-screen">
<svg
aria-hidden="true"
className="w-8 h-8 text-light-200 fill-light-secondary dark:text-[#202020] animate-spin dark:fill-[#ffffff3b]"
viewBox="0 0 100 101"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M100 50.5908C100.003 78.2051 78.1951 100.003 50.5908 100C22.9765 99.9972 0.997224 78.018 1 50.4037C1.00281 22.7993 22.8108 0.997224 50.4251 1C78.0395 1.00281 100.018 22.8108 100 50.4251ZM9.08164 50.594C9.06312 73.3997 27.7909 92.1272 50.5966 92.1457C73.4023 92.1642 92.1298 73.4365 92.1483 50.6308C92.1669 27.8251 73.4392 9.0973 50.6335 9.07878C27.8278 9.06026 9.10003 27.787 9.08164 50.594Z"
fill="currentColor"
/>
<path
d="M93.9676 39.0409C96.393 38.4037 97.8624 35.9116 96.9801 33.5533C95.1945 28.8227 92.871 24.3692 90.0681 20.348C85.6237 14.1775 79.4473 9.36872 72.0454 6.45794C64.6435 3.54717 56.3134 2.65431 48.3133 3.89319C45.869 4.27179 44.3768 6.77534 45.014 9.20079C45.6512 11.6262 48.1343 13.0956 50.5786 12.717C56.5073 11.8281 62.5542 12.5399 68.0406 14.7911C73.527 17.0422 78.2187 20.7487 81.5841 25.4923C83.7976 28.5886 85.4467 32.059 86.4416 35.7474C87.1273 38.1189 89.5423 39.6781 91.9676 39.0409Z"
fill="currentFill"
/>
</svg>
</div>
) : (
<>
<div>
<div className="flex flex-col pt-4">
<div className="flex items-center">
<Search />
<h1 className="text-3xl font-medium p-2">Discover</h1>
</div>
<hr className="border-t border-[#2B2C2C] my-4 w-full" />
</div>
<div className="grid lg:grid-cols-3 sm:grid-cols-2 grid-cols-1 gap-4 pb-28 lg:pb-8 w-full justify-items-center lg:justify-items-start">
{discover &&
discover?.map((item, i) => (
<Link
href={`/?q=Summary: ${item.url}`}
key={i}
className="max-w-sm rounded-lg overflow-hidden bg-light-secondary dark:bg-dark-secondary hover:-translate-y-[1px] transition duration-200"
>
<img
className="object-cover w-full aspect-video"
src={
new URL(item.thumbnail).origin +
new URL(item.thumbnail).pathname +
`?id=${new URL(item.thumbnail).searchParams.get('id')}`
}
alt={item.title}
/>
<div className="px-6 py-4">
<div className="font-bold text-lg mb-2">
{item.title.slice(0, 100)}...
</div>
<p className="text-black-70 dark:text-white/70 text-sm">
{item.content.slice(0, 100)}...
</p>
</div>
</Link>
))}
</div>
</div>
</>
);
};
export default Page;

View File

@@ -5,7 +5,31 @@ export const metadata: Metadata = {
title: 'Library - Perplexica', title: 'Library - Perplexica',
}; };
const Layout = ({ children }: { children: React.ReactNode }) => { const Layout = async ({ children }: { children: React.ReactNode }) => {
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/config/preferences`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
},
);
const data = await res.json();
const { isLibraryEnabled } = data;
if (!isLibraryEnabled) {
return (
<div className="flex flex-row items-center justify-center min-h-screen w-full">
<p className="text-lg dark:text-white/70 text-black/70">
Library is disabled
</p>
</div>
);
}
return <div>{children}</div>; return <div>{children}</div>;
}; };

View File

@@ -1,8 +1,8 @@
'use client'; 'use client';
import DeleteChat from '@/components/DeleteChat'; import DeleteChat from '@/components/DeleteChat';
import { cn, formatTimeDifference } from '@/lib/utils'; import { formatTimeDifference } from '@/lib/utils';
import { BookOpenText, ClockIcon, Delete, ScanEye } from 'lucide-react'; import { BookOpenText, ClockIcon } from 'lucide-react';
import Link from 'next/link'; import Link from 'next/link';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
@@ -58,12 +58,13 @@ const Page = () => {
</div> </div>
) : ( ) : (
<div> <div>
<div className="flex flex-col pt-4"> <div className="fixed z-40 top-0 left-0 right-0 lg:pl-[104px] lg:pr-6 lg:px-8 px-4 py-4 lg:py-6 border-b border-light-200 dark:border-dark-200">
<div className="flex items-center"> <div className="flex flex-row items-center space-x-2 max-w-screen-lg lg:mx-auto">
<BookOpenText /> <BookOpenText />
<h1 className="text-3xl font-medium p-2">Library</h1> <h2 className="text-black dark:text-white lg:text-3xl lg:font-medium">
Library
</h2>
</div> </div>
<hr className="border-t border-[#2B2C2C] my-4 w-full" />
</div> </div>
{chats.length === 0 && ( {chats.length === 0 && (
<div className="flex flex-row items-center justify-center min-h-screen"> <div className="flex flex-row items-center justify-center min-h-screen">
@@ -73,15 +74,10 @@ const Page = () => {
</div> </div>
)} )}
{chats.length > 0 && ( {chats.length > 0 && (
<div className="flex flex-col pb-20 lg:pb-2"> <div className="flex flex-col pt-16 lg:pt-24">
{chats.map((chat, i) => ( {chats.map((chat, i) => (
<div <div
className={cn( className="flex flex-col space-y-4 border-b border-white-200 dark:border-dark-200 py-6 lg:mx-4"
'flex flex-col space-y-4 py-6',
i !== chats.length - 1
? 'border-b border-white-200 dark:border-dark-200'
: '',
)}
key={i} key={i}
> >
<Link <Link

View File

@@ -59,9 +59,7 @@ const useSocket = (
chatModelProvider = Object.keys(chatModelProviders)[0]; 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 configure the API key and base URL',
);
setError(true); setError(true);
return; return;
} else { } else {
@@ -171,22 +169,11 @@ const useSocket = (
} }
}, 10000); }, 10000);
ws.addEventListener('message', (e) => { ws.onopen = () => {
const data = JSON.parse(e.data); console.log('[DEBUG] open');
if (data.type === 'signal' && data.data === 'open') { clearTimeout(timeoutId);
const interval = setInterval(() => { setIsWSReady(true);
if (ws.readyState === 1) { };
setIsWSReady(true);
clearInterval(interval);
}
}, 5);
clearTimeout(timeoutId);
console.log('[DEBUG] opened');
}
if (data.type === 'error') {
toast.error(data.data);
}
});
ws.onerror = () => { ws.onerror = () => {
clearTimeout(timeoutId); clearTimeout(timeoutId);
@@ -200,11 +187,25 @@ const useSocket = (
console.log('[DEBUG] closed'); console.log('[DEBUG] closed');
}; };
ws.addEventListener('message', (e) => {
const data = JSON.parse(e.data);
if (data.type === 'error') {
toast.error(data.data);
}
})
setWs(ws); setWs(ws);
}; };
connectWs(); connectWs();
} }
return () => {
if (ws?.readyState === 1) {
ws?.close();
console.log('[DEBUG] closed');
}
};
}, [ws, url, setIsWSReady, setError]); }, [ws, url, setIsWSReady, setError]);
return ws; return ws;
@@ -282,7 +283,6 @@ const ChatWindow = ({ id }: { id?: string }) => {
const [messages, setMessages] = useState<Message[]>([]); const [messages, setMessages] = useState<Message[]>([]);
const [focusMode, setFocusMode] = useState('webSearch'); const [focusMode, setFocusMode] = useState('webSearch');
const [optimizationMode, setOptimizationMode] = useState('speed');
const [isMessagesLoaded, setIsMessagesLoaded] = useState(false); const [isMessagesLoaded, setIsMessagesLoaded] = useState(false);
@@ -311,16 +311,6 @@ const ChatWindow = ({ id }: { id?: string }) => {
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, []); }, []);
useEffect(() => {
return () => {
if (ws?.readyState === 1) {
ws.close();
console.log('[DEBUG] closed');
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const messagesRef = useRef<Message[]>([]); const messagesRef = useRef<Message[]>([]);
useEffect(() => { useEffect(() => {
@@ -330,13 +320,11 @@ const ChatWindow = ({ id }: { id?: string }) => {
useEffect(() => { useEffect(() => {
if (isMessagesLoaded && isWSReady) { if (isMessagesLoaded && isWSReady) {
setIsReady(true); setIsReady(true);
console.log('[DEBUG] ready');
} }
}, [isMessagesLoaded, isWSReady]); }, [isMessagesLoaded, isWSReady]);
const sendMessage = async (message: string, messageId?: string) => { const sendMessage = async (message: string) => {
if (loading) return; if (loading) return;
setLoading(true); setLoading(true);
setMessageAppeared(false); setMessageAppeared(false);
@@ -344,18 +332,16 @@ const ChatWindow = ({ id }: { id?: string }) => {
let recievedMessage = ''; let recievedMessage = '';
let added = false; let added = false;
messageId = messageId ?? crypto.randomBytes(7).toString('hex'); const messageId = crypto.randomBytes(7).toString('hex');
ws?.send( ws?.send(
JSON.stringify({ JSON.stringify({
type: 'message', type: 'message',
message: { message: {
messageId: messageId,
chatId: chatId!, chatId: chatId!,
content: message, content: message,
}, },
focusMode: focusMode, focusMode: focusMode,
optimizationMode: optimizationMode,
history: [...chatHistory, ['human', message]], history: [...chatHistory, ['human', message]],
}), }),
); );
@@ -477,15 +463,15 @@ const ChatWindow = ({ id }: { id?: string }) => {
return [...prev.slice(0, messages.length > 2 ? index - 1 : 0)]; return [...prev.slice(0, messages.length > 2 ? index - 1 : 0)];
}); });
sendMessage(message.content, message.messageId); sendMessage(message.content);
}; };
useEffect(() => { useEffect(() => {
if (isReady && initialMessage && ws?.readyState === 1) { if (isReady && initialMessage) {
sendMessage(initialMessage); sendMessage(initialMessage);
} }
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [ws?.readyState, isReady, initialMessage, isWSReady]); }, [isReady, initialMessage]);
if (hasError) { if (hasError) {
return ( return (
@@ -504,7 +490,7 @@ const ChatWindow = ({ id }: { id?: string }) => {
<div> <div>
{messages.length > 0 ? ( {messages.length > 0 ? (
<> <>
<Navbar chatId={chatId!} messages={messages} /> <Navbar messages={messages} />
<Chat <Chat
loading={loading} loading={loading}
messages={messages} messages={messages}
@@ -518,8 +504,6 @@ const ChatWindow = ({ id }: { id?: string }) => {
sendMessage={sendMessage} sendMessage={sendMessage}
focusMode={focusMode} focusMode={focusMode}
setFocusMode={setFocusMode} setFocusMode={setFocusMode}
optimizationMode={optimizationMode}
setOptimizationMode={setOptimizationMode}
/> />
)} )}
</div> </div>

View File

@@ -1,13 +1,5 @@
import { Trash } from 'lucide-react'; import { Delete, Trash } from 'lucide-react';
import { import { Dialog, Transition } from '@headlessui/react';
Description,
Dialog,
DialogBackdrop,
DialogPanel,
DialogTitle,
Transition,
TransitionChild,
} from '@headlessui/react';
import { Fragment, useState } from 'react'; import { Fragment, useState } from 'react';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { Chat } from '@/app/library/page'; import { Chat } from '@/app/library/page';
@@ -16,12 +8,10 @@ const DeleteChat = ({
chatId, chatId,
chats, chats,
setChats, setChats,
redirect = false,
}: { }: {
chatId: string; chatId: string;
chats: Chat[]; chats: Chat[];
setChats: (chats: Chat[]) => void; setChats: (chats: Chat[]) => void;
redirect?: boolean;
}) => { }) => {
const [confirmationDialogOpen, setConfirmationDialogOpen] = useState(false); const [confirmationDialogOpen, setConfirmationDialogOpen] = useState(false);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -46,10 +36,6 @@ const DeleteChat = ({
const newChats = chats.filter((chat) => chat.id !== chatId); const newChats = chats.filter((chat) => chat.id !== chatId);
setChats(newChats); setChats(newChats);
if (redirect) {
window.location.href = '/';
}
} catch (err: any) { } catch (err: any) {
toast.error(err.message); toast.error(err.message);
} finally { } finally {
@@ -78,10 +64,10 @@ const DeleteChat = ({
} }
}} }}
> >
<DialogBackdrop className="fixed inset-0 bg-black/30" /> <Dialog.Backdrop className="fixed inset-0 bg-black/30" />
<div className="fixed inset-0 overflow-y-auto"> <div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-center justify-center p-4 text-center"> <div className="flex min-h-full items-center justify-center p-4 text-center">
<TransitionChild <Transition.Child
as={Fragment} as={Fragment}
enter="ease-out duration-200" enter="ease-out duration-200"
enterFrom="opacity-0 scale-95" enterFrom="opacity-0 scale-95"
@@ -90,13 +76,13 @@ const DeleteChat = ({
leaveFrom="opacity-100 scale-200" leaveFrom="opacity-100 scale-200"
leaveTo="opacity-0 scale-95" 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"> <Dialog.Panel 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-lg font-medium leading-6 dark:text-white"> <Dialog.Title className="text-lg font-medium leading-6 dark:text-white">
Delete Confirmation Delete Confirmation
</DialogTitle> </Dialog.Title>
<Description className="text-sm dark:text-white/70 text-black/70"> <Dialog.Description className="text-sm dark:text-white/70 text-black/70">
Are you sure you want to delete this chat? Are you sure you want to delete this chat?
</Description> </Dialog.Description>
<div className="flex flex-row items-end justify-end space-x-4 mt-6"> <div className="flex flex-row items-end justify-end space-x-4 mt-6">
<button <button
onClick={() => { onClick={() => {
@@ -115,8 +101,8 @@ const DeleteChat = ({
Delete Delete
</button> </button>
</div> </div>
</DialogPanel> </Dialog.Panel>
</TransitionChild> </Transition.Child>
</div> </div>
</div> </div>
</Dialog> </Dialog>

View File

@@ -1,32 +1,16 @@
import { Settings } from 'lucide-react';
import EmptyChatMessageInput from './EmptyChatMessageInput'; import EmptyChatMessageInput from './EmptyChatMessageInput';
import SettingsDialog from './SettingsDialog';
import { useState } from 'react';
const EmptyChat = ({ const EmptyChat = ({
sendMessage, sendMessage,
focusMode, focusMode,
setFocusMode, setFocusMode,
optimizationMode,
setOptimizationMode,
}: { }: {
sendMessage: (message: string) => void; sendMessage: (message: string) => void;
focusMode: string; focusMode: string;
setFocusMode: (mode: string) => void; setFocusMode: (mode: string) => void;
optimizationMode: string;
setOptimizationMode: (mode: string) => void;
}) => { }) => {
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
return ( return (
<div className="relative"> <div className="relative">
<SettingsDialog isOpen={isSettingsOpen} setIsOpen={setIsSettingsOpen} />
<div className="absolute w-full flex flex-row items-center justify-end mr-5 mt-5">
<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"> <div className="flex flex-col items-center justify-center min-h-screen max-w-screen-sm mx-auto p-2 space-y-8">
<h2 className="text-black/70 dark:text-white/70 text-3xl font-medium -mt-8"> <h2 className="text-black/70 dark:text-white/70 text-3xl font-medium -mt-8">
Research begins here. Research begins here.
@@ -35,8 +19,6 @@ const EmptyChat = ({
sendMessage={sendMessage} sendMessage={sendMessage}
focusMode={focusMode} focusMode={focusMode}
setFocusMode={setFocusMode} setFocusMode={setFocusMode}
optimizationMode={optimizationMode}
setOptimizationMode={setOptimizationMode}
/> />
</div> </div>
</div> </div>

View File

@@ -3,41 +3,29 @@ import { useEffect, useRef, useState } from 'react';
import TextareaAutosize from 'react-textarea-autosize'; import TextareaAutosize from 'react-textarea-autosize';
import CopilotToggle from './MessageInputActions/Copilot'; import CopilotToggle from './MessageInputActions/Copilot';
import Focus from './MessageInputActions/Focus'; import Focus from './MessageInputActions/Focus';
import Optimization from './MessageInputActions/Optimization';
const EmptyChatMessageInput = ({ const EmptyChatMessageInput = ({
sendMessage, sendMessage,
focusMode, focusMode,
setFocusMode, setFocusMode,
optimizationMode,
setOptimizationMode,
}: { }: {
sendMessage: (message: string) => void; sendMessage: (message: string) => void;
focusMode: string; focusMode: string;
setFocusMode: (mode: string) => void; setFocusMode: (mode: string) => void;
optimizationMode: string;
setOptimizationMode: (mode: string) => void;
}) => { }) => {
const [copilotEnabled, setCopilotEnabled] = useState(false); const [copilotEnabled, setCopilotEnabled] = useState(false);
const [message, setMessage] = useState(''); const [message, setMessage] = useState('');
const inputRef = useRef<HTMLTextAreaElement | null>(null); const inputRef = useRef<HTMLTextAreaElement | null>(null);
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === '/') {
e.preventDefault();
inputRef.current?.focus();
}
};
useEffect(() => { useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
const activeElement = document.activeElement;
const isInputFocused =
activeElement?.tagName === 'INPUT' ||
activeElement?.tagName === 'TEXTAREA' ||
activeElement?.hasAttribute('contenteditable');
if (e.key === '/' && !isInputFocused) {
e.preventDefault();
inputRef.current?.focus();
}
};
document.addEventListener('keydown', handleKeyDown); document.addEventListener('keydown', handleKeyDown);
return () => { return () => {
@@ -71,13 +59,14 @@ const EmptyChatMessageInput = ({
placeholder="Ask anything..." placeholder="Ask anything..."
/> />
<div className="flex flex-row items-center justify-between mt-4"> <div className="flex flex-row items-center justify-between mt-4">
<div className="flex flex-row items-center space-x-4"> <div className="flex flex-row items-center space-x-1 -mx-2">
<Focus focusMode={focusMode} setFocusMode={setFocusMode} /> <Focus focusMode={focusMode} setFocusMode={setFocusMode} />
{/* <Attach /> */}
</div> </div>
<div className="flex flex-row items-center space-x-1 sm:space-x-4"> <div className="flex flex-row items-center space-x-4 -mx-2">
<Optimization <CopilotToggle
optimizationMode={optimizationMode} copilotEnabled={copilotEnabled}
setOptimizationMode={setOptimizationMode} setCopilotEnabled={setCopilotEnabled}
/> />
<button <button
disabled={message.trim().length === 0} disabled={message.trim().length === 0}

View File

@@ -186,10 +186,10 @@ const MessageBox = ({
<div className="lg:sticky lg:top-20 flex flex-col items-center space-y-3 w-full lg:w-3/12 z-30 h-full pb-4"> <div className="lg:sticky lg:top-20 flex flex-col items-center space-y-3 w-full lg:w-3/12 z-30 h-full pb-4">
<SearchImages <SearchImages
query={history[messageIndex - 1].content} query={history[messageIndex - 1].content}
chatHistory={history.slice(0, messageIndex - 1)} chat_history={history.slice(0, messageIndex - 1)}
/> />
<SearchVideos <SearchVideos
chatHistory={history.slice(0, messageIndex - 1)} chat_history={history.slice(0, messageIndex - 1)}
query={history[messageIndex - 1].content} query={history[messageIndex - 1].content}
/> />
</div> </div>

View File

@@ -27,21 +27,14 @@ const MessageInput = ({
const inputRef = useRef<HTMLTextAreaElement | null>(null); const inputRef = useRef<HTMLTextAreaElement | null>(null);
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === '/') {
e.preventDefault();
inputRef.current?.focus();
}
};
useEffect(() => { useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
const activeElement = document.activeElement;
const isInputFocused =
activeElement?.tagName === 'INPUT' ||
activeElement?.tagName === 'TEXTAREA' ||
activeElement?.hasAttribute('contenteditable');
if (e.key === '/' && !isInputFocused) {
e.preventDefault();
inputRef.current?.focus();
}
};
document.addEventListener('keydown', handleKeyDown); document.addEventListener('keydown', handleKeyDown);
return () => { return () => {

View File

@@ -1,5 +1,6 @@
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { Switch } from '@headlessui/react'; import { Switch } from '@headlessui/react';
import { useEffect } from 'react';
const CopilotToggle = ({ const CopilotToggle = ({
copilotEnabled, copilotEnabled,
@@ -8,11 +9,33 @@ const CopilotToggle = ({
copilotEnabled: boolean; copilotEnabled: boolean;
setCopilotEnabled: (enabled: boolean) => void; setCopilotEnabled: (enabled: boolean) => void;
}) => { }) => {
const fetchAndSetCopilotEnabled = async () => {
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/config/preferences`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
},
);
const preferences = await res.json();
setCopilotEnabled(preferences.isCopilotEnabled);
};
useEffect(() => {
fetchAndSetCopilotEnabled();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return ( return (
<div className="group flex flex-row items-center space-x-1 active:scale-95 duration-200 transition cursor-pointer"> <div className="group flex flex-row items-center space-x-1 active:scale-95 duration-200 transition cursor-pointer">
<Switch <Switch
checked={copilotEnabled} checked={copilotEnabled}
onChange={setCopilotEnabled} onChange={setCopilotEnabled}
disabled={true}
className="bg-light-secondary dark:bg-dark-secondary border border-light-200/70 dark:border-dark-200 relative inline-flex h-5 w-10 sm:h-6 sm:w-11 items-center rounded-full" className="bg-light-secondary dark:bg-dark-secondary border border-light-200/70 dark:border-dark-200 relative inline-flex h-5 w-10 sm:h-6 sm:w-11 items-center rounded-full"
> >
<span className="sr-only">Copilot</span> <span className="sr-only">Copilot</span>

View File

@@ -7,12 +7,7 @@ import {
SwatchBook, SwatchBook,
} from 'lucide-react'; } from 'lucide-react';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { import { Popover, Transition } from '@headlessui/react';
Popover,
PopoverButton,
PopoverPanel,
Transition,
} from '@headlessui/react';
import { SiReddit, SiYoutube } from '@icons-pack/react-simple-icons'; import { SiReddit, SiYoutube } from '@icons-pack/react-simple-icons';
import { Fragment } from 'react'; import { Fragment } from 'react';
@@ -75,10 +70,10 @@ const Focus = ({
setFocusMode: (mode: string) => void; setFocusMode: (mode: string) => void;
}) => { }) => {
return ( return (
<Popover className="relative w-full max-w-[15rem] md:max-w-md lg:max-w-lg"> <Popover className="fixed w-full max-w-[15rem] md:max-w-md lg:max-w-lg">
<PopoverButton <Popover.Button
type="button" type="button"
className=" text-black/50 dark:text-white/50 rounded-xl hover:bg-light-secondary dark:hover:bg-dark-secondary active:scale-95 transition duration-200 hover:text-black dark:hover:text-white" className="p-2 text-black/50 dark:text-white/50 rounded-xl hover:bg-light-secondary dark:hover:bg-dark-secondary active:scale-95 transition duration-200 hover:text-black dark:hover:text-white"
> >
{focusMode !== 'webSearch' ? ( {focusMode !== 'webSearch' ? (
<div className="flex flex-row items-center space-x-1"> <div className="flex flex-row items-center space-x-1">
@@ -91,7 +86,7 @@ const Focus = ({
) : ( ) : (
<ScanEye /> <ScanEye />
)} )}
</PopoverButton> </Popover.Button>
<Transition <Transition
as={Fragment} as={Fragment}
enter="transition ease-out duration-150" enter="transition ease-out duration-150"
@@ -101,10 +96,10 @@ const Focus = ({
leaveFrom="opacity-100 translate-y-0" leaveFrom="opacity-100 translate-y-0"
leaveTo="opacity-0 translate-y-1" leaveTo="opacity-0 translate-y-1"
> >
<PopoverPanel className="absolute z-10 w-64 md:w-[500px] left-0"> <Popover.Panel className="absolute z-10 w-full">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2 bg-light-primary dark:bg-dark-primary border rounded-lg border-light-200 dark:border-dark-200 w-full p-4 max-h-[200px] md:max-h-none overflow-y-auto"> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-1 bg-light-primary dark:bg-dark-primary border rounded-lg border-light-200 dark:border-dark-200 w-full p-2 max-h-[200px] md:max-h-none overflow-y-auto">
{focusModes.map((mode, i) => ( {focusModes.map((mode, i) => (
<PopoverButton <Popover.Button
onClick={() => setFocusMode(mode.key)} onClick={() => setFocusMode(mode.key)}
key={i} key={i}
className={cn( className={cn(
@@ -128,10 +123,10 @@ const Focus = ({
<p className="text-black/70 dark:text-white/70 text-xs"> <p className="text-black/70 dark:text-white/70 text-xs">
{mode.description} {mode.description}
</p> </p>
</PopoverButton> </Popover.Button>
))} ))}
</div> </div>
</PopoverPanel> </Popover.Panel>
</Transition> </Transition>
</Popover> </Popover>
); );

View File

@@ -1,104 +0,0 @@
import { ChevronDown, Sliders, Star, Zap } from 'lucide-react';
import { cn } from '@/lib/utils';
import {
Popover,
PopoverButton,
PopoverPanel,
Transition,
} from '@headlessui/react';
import { Fragment } from 'react';
const OptimizationModes = [
{
key: 'speed',
title: 'Speed',
description: 'Prioritize speed and get the quickest possible answer.',
icon: <Zap size={20} className="text-[#FF9800]" />,
},
{
key: 'balanced',
title: 'Balanced',
description: 'Find the right balance between speed and accuracy',
icon: <Sliders size={20} className="text-[#4CAF50]" />,
},
{
key: 'quality',
title: 'Quality (Soon)',
description: 'Get the most thorough and accurate answer',
icon: (
<Star
size={16}
className="text-[#2196F3] dark:text-[#BBDEFB] fill-[#BBDEFB] dark:fill-[#2196F3]"
/>
),
},
];
const Optimization = ({
optimizationMode,
setOptimizationMode,
}: {
optimizationMode: string;
setOptimizationMode: (mode: string) => void;
}) => {
return (
<Popover className="relative w-full max-w-[15rem] md:max-w-md lg:max-w-lg">
<PopoverButton
type="button"
className="p-2 text-black/50 dark:text-white/50 rounded-xl hover:bg-light-secondary dark:hover:bg-dark-secondary active:scale-95 transition duration-200 hover:text-black dark:hover:text-white"
>
<div className="flex flex-row items-center space-x-1">
{
OptimizationModes.find((mode) => mode.key === optimizationMode)
?.icon
}
<p className="text-xs font-medium">
{
OptimizationModes.find((mode) => mode.key === optimizationMode)
?.title
}
</p>
<ChevronDown size={20} />
</div>
</PopoverButton>
<Transition
as={Fragment}
enter="transition ease-out duration-150"
enterFrom="opacity-0 translate-y-1"
enterTo="opacity-100 translate-y-0"
leave="transition ease-in duration-150"
leaveFrom="opacity-100 translate-y-0"
leaveTo="opacity-0 translate-y-1"
>
<PopoverPanel className="absolute z-10 w-64 md:w-[250px] right-0">
<div className="flex flex-col gap-2 bg-light-primary dark:bg-dark-primary border rounded-lg border-light-200 dark:border-dark-200 w-full p-4 max-h-[200px] md:max-h-none overflow-y-auto">
{OptimizationModes.map((mode, i) => (
<PopoverButton
onClick={() => setOptimizationMode(mode.key)}
key={i}
disabled={mode.key === 'quality'}
className={cn(
'p-2 rounded-lg flex flex-col items-start justify-start text-start space-y-1 duration-200 cursor-pointer transition',
optimizationMode === mode.key
? 'bg-light-secondary dark:bg-dark-secondary'
: 'hover:bg-light-secondary dark:hover:bg-dark-secondary',
mode.key === 'quality' && 'opacity-50 cursor-not-allowed',
)}
>
<div className="flex flex-row items-center space-x-1 text-black dark:text-white">
{mode.icon}
<p className="text-sm font-medium">{mode.title}</p>
</div>
<p className="text-black/70 dark:text-white/70 text-xs">
{mode.description}
</p>
</PopoverButton>
))}
</div>
</PopoverPanel>
</Transition>
</Popover>
);
};
export default Optimization;

View File

@@ -1,11 +1,5 @@
/* eslint-disable @next/next/no-img-element */ /* eslint-disable @next/next/no-img-element */
import { import { Dialog, Transition } from '@headlessui/react';
Dialog,
DialogPanel,
DialogTitle,
Transition,
TransitionChild,
} from '@headlessui/react';
import { Document } from '@langchain/core/documents'; import { Document } from '@langchain/core/documents';
import { Fragment, useState } from 'react'; import { Fragment, useState } from 'react';
@@ -80,7 +74,7 @@ const MessageSources = ({ sources }: { sources: Document[] }) => {
<Dialog as="div" className="relative z-50" onClose={closeModal}> <Dialog as="div" className="relative z-50" onClose={closeModal}>
<div className="fixed inset-0 overflow-y-auto"> <div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-center justify-center p-4 text-center"> <div className="flex min-h-full items-center justify-center p-4 text-center">
<TransitionChild <Transition.Child
as={Fragment} as={Fragment}
enter="ease-out duration-200" enter="ease-out duration-200"
enterFrom="opacity-0 scale-95" enterFrom="opacity-0 scale-95"
@@ -89,10 +83,10 @@ const MessageSources = ({ sources }: { sources: Document[] }) => {
leaveFrom="opacity-100 scale-200" leaveFrom="opacity-100 scale-200"
leaveTo="opacity-0 scale-95" 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"> <Dialog.Panel 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-lg font-medium leading-6 dark:text-white"> <Dialog.Title className="text-lg font-medium leading-6 dark:text-white">
Sources Sources
</DialogTitle> </Dialog.Title>
<div className="grid grid-cols-2 gap-2 overflow-auto max-h-[300px] mt-2 pr-2"> <div className="grid grid-cols-2 gap-2 overflow-auto max-h-[300px] mt-2 pr-2">
{sources.map((source, i) => ( {sources.map((source, i) => (
<a <a
@@ -128,8 +122,8 @@ const MessageSources = ({ sources }: { sources: Document[] }) => {
</a> </a>
))} ))}
</div> </div>
</DialogPanel> </Dialog.Panel>
</TransitionChild> </Transition.Child>
</div> </div>
</div> </div>
</Dialog> </Dialog>

View File

@@ -2,15 +2,8 @@ import { Clock, Edit, Share, Trash } from 'lucide-react';
import { Message } from './ChatWindow'; import { Message } from './ChatWindow';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { formatTimeDifference } from '@/lib/utils'; import { formatTimeDifference } from '@/lib/utils';
import DeleteChat from './DeleteChat';
const Navbar = ({ const Navbar = ({ messages }: { messages: Message[] }) => {
chatId,
messages,
}: {
messages: Message[];
chatId: string;
}) => {
const [title, setTitle] = useState<string>(''); const [title, setTitle] = useState<string>('');
const [timeAgo, setTimeAgo] = useState<string>(''); const [timeAgo, setTimeAgo] = useState<string>('');
@@ -46,12 +39,10 @@ const Navbar = ({
return ( return (
<div className="fixed z-40 top-0 left-0 right-0 px-4 lg:pl-[104px] lg:pr-6 lg:px-8 flex flex-row items-center justify-between w-full py-4 text-sm text-black dark:text-white/70 border-b bg-light-primary dark:bg-dark-primary border-light-100 dark:border-dark-200"> <div className="fixed z-40 top-0 left-0 right-0 px-4 lg:pl-[104px] lg:pr-6 lg:px-8 flex flex-row items-center justify-between w-full py-4 text-sm text-black dark:text-white/70 border-b bg-light-primary dark:bg-dark-primary border-light-100 dark:border-dark-200">
<a <Edit
href="/" size={17}
className="active:scale-95 transition duration-100 cursor-pointer lg:hidden" className="active:scale-95 transition duration-100 cursor-pointer lg:hidden"
> />
<Edit size={17} />
</a>
<div className="hidden lg:flex flex-row items-center justify-center space-x-2"> <div className="hidden lg:flex flex-row items-center justify-center space-x-2">
<Clock size={17} /> <Clock size={17} />
<p className="text-xs">{timeAgo} ago</p> <p className="text-xs">{timeAgo} ago</p>
@@ -63,7 +54,10 @@ const Navbar = ({
size={17} size={17}
className="active:scale-95 transition duration-100 cursor-pointer" className="active:scale-95 transition duration-100 cursor-pointer"
/> />
<DeleteChat redirect chatId={chatId} chats={[]} setChats={() => {}} /> <Trash
size={17}
className="text-red-400 active:scale-95 transition duration-100 cursor-pointer"
/>
</div> </div>
</div> </div>
); );

View File

@@ -13,10 +13,10 @@ type Image = {
const SearchImages = ({ const SearchImages = ({
query, query,
chatHistory, chat_history,
}: { }: {
query: string; query: string;
chatHistory: Message[]; chat_history: Message[];
}) => { }) => {
const [images, setImages] = useState<Image[] | null>(null); const [images, setImages] = useState<Image[] | null>(null);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -33,9 +33,6 @@ const SearchImages = ({
const chatModelProvider = localStorage.getItem('chatModelProvider'); const chatModelProvider = localStorage.getItem('chatModelProvider');
const chatModel = localStorage.getItem('chatModel'); const chatModel = localStorage.getItem('chatModel');
const customOpenAIBaseURL = localStorage.getItem('openAIBaseURL');
const customOpenAIKey = localStorage.getItem('openAIApiKey');
const res = await fetch( const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/images`, `${process.env.NEXT_PUBLIC_API_URL}/images`,
{ {
@@ -45,22 +42,16 @@ const SearchImages = ({
}, },
body: JSON.stringify({ body: JSON.stringify({
query: query, query: query,
chatHistory: chatHistory, chat_history: chat_history,
chatModel: { chat_model_provider: chatModelProvider,
provider: chatModelProvider, chat_model: chatModel,
model: chatModel,
...(chatModelProvider === 'custom_openai' && {
customOpenAIBaseURL: customOpenAIBaseURL,
customOpenAIKey: customOpenAIKey,
}),
},
}), }),
}, },
); );
const data = await res.json(); const data = await res.json();
const images = data.images ?? []; const images = data.images;
setImages(images); setImages(images);
setSlides( setSlides(
images.map((image: Image) => { images.map((image: Image) => {

View File

@@ -26,10 +26,10 @@ declare module 'yet-another-react-lightbox' {
const Searchvideos = ({ const Searchvideos = ({
query, query,
chatHistory, chat_history,
}: { }: {
query: string; query: string;
chatHistory: Message[]; chat_history: Message[];
}) => { }) => {
const [videos, setVideos] = useState<Video[] | null>(null); const [videos, setVideos] = useState<Video[] | null>(null);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -46,9 +46,6 @@ const Searchvideos = ({
const chatModelProvider = localStorage.getItem('chatModelProvider'); const chatModelProvider = localStorage.getItem('chatModelProvider');
const chatModel = localStorage.getItem('chatModel'); const chatModel = localStorage.getItem('chatModel');
const customOpenAIBaseURL = localStorage.getItem('openAIBaseURL');
const customOpenAIKey = localStorage.getItem('openAIApiKey');
const res = await fetch( const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/videos`, `${process.env.NEXT_PUBLIC_API_URL}/videos`,
{ {
@@ -58,22 +55,16 @@ const Searchvideos = ({
}, },
body: JSON.stringify({ body: JSON.stringify({
query: query, query: query,
chatHistory: chatHistory, chat_history: chat_history,
chatModel: { chat_model_provider: chatModelProvider,
provider: chatModelProvider, chat_model: chatModel,
model: chatModel,
...(chatModelProvider === 'custom_openai' && {
customOpenAIBaseURL: customOpenAIBaseURL,
customOpenAIKey: customOpenAIKey,
}),
},
}), }),
}, },
); );
const data = await res.json(); const data = await res.json();
const videos = data.videos ?? []; const videos = data.videos;
setVideos(videos); setVideos(videos);
setSlides( setSlides(
videos.map((video: Video) => { videos.map((video: Video) => {

View File

@@ -1,11 +1,5 @@
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { import { Dialog, Switch, Transition } from '@headlessui/react';
Dialog,
DialogPanel,
DialogTitle,
Transition,
TransitionChild,
} from '@headlessui/react';
import { CloudUpload, RefreshCcw, RefreshCw } from 'lucide-react'; import { CloudUpload, RefreshCcw, RefreshCw } from 'lucide-react';
import React, { import React, {
Fragment, Fragment,
@@ -14,6 +8,7 @@ import React, {
type SelectHTMLAttributes, type SelectHTMLAttributes,
} from 'react'; } from 'react';
import ThemeSwitcher from './theme/Switcher'; import ThemeSwitcher from './theme/Switcher';
import { toast } from 'sonner';
interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {} interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {}
@@ -55,15 +50,18 @@ export const Select = ({ className, options, ...restProps }: SelectProps) => {
interface SettingsType { interface SettingsType {
chatModelProviders: { chatModelProviders: {
[key: string]: [Record<string, any>]; [key: string]: string[];
}; };
embeddingModelProviders: { embeddingModelProviders: {
[key: string]: [Record<string, any>]; [key: string]: string[];
}; };
openaiApiKey: string; openaiApiKey: string;
groqApiKey: string; groqApiKey: string;
anthropicApiKey: string; anthropicApiKey: string;
ollamaApiUrl: string; ollamaApiUrl: string;
isCopilotEnabled: boolean;
isDiscoverEnabled: boolean;
isLibraryEnabled: boolean;
} }
const SettingsDialog = ({ const SettingsDialog = ({
@@ -74,10 +72,6 @@ const SettingsDialog = ({
setIsOpen: (isOpen: boolean) => void; setIsOpen: (isOpen: boolean) => void;
}) => { }) => {
const [config, setConfig] = useState<SettingsType | null>(null); 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< const [selectedChatModelProvider, setSelectedChatModelProvider] = useState<
string | null string | null
>(null); >(null);
@@ -94,82 +88,91 @@ const SettingsDialog = ({
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [isUpdating, setIsUpdating] = useState(false); const [isUpdating, setIsUpdating] = useState(false);
useEffect(() => { const [password, setPassword] = useState('');
if (isOpen) { const [passwordSubmitted, setPasswordSubmitted] = useState(false);
const fetchConfig = async () => { const [isPasswordValid, setIsPasswordValid] = useState(true);
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; const handlePasswordSubmit = async () => {
setConfig(data); setIsLoading(true);
setPasswordSubmitted(true);
const chatModelProvidersKeys = Object.keys( const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/config`, {
data.chatModelProviders || {}, headers: {
); 'Content-Type': 'application/json',
const embeddingModelProvidersKeys = Object.keys( Authorization: `Bearer ${password}`,
data.embeddingModelProviders || {}, },
); });
const defaultChatModelProvider = if (res.status === 401) {
chatModelProvidersKeys.length > 0 ? chatModelProvidersKeys[0] : ''; setIsPasswordValid(false);
const defaultEmbeddingModelProvider = setPasswordSubmitted(false);
embeddingModelProvidersKeys.length > 0 setIsLoading(false);
? embeddingModelProvidersKeys[0] return;
: ''; } else {
setIsPasswordValid(true);
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 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]?.[0]) ||
'';
const embeddingModelProvider =
localStorage.getItem('embeddingModelProvider') ||
defaultEmbeddingModelProvider ||
'';
const embeddingModel =
localStorage.getItem('embeddingModel') ||
(data.embeddingModelProviders &&
data.embeddingModelProviders[embeddingModelProvider]?.[0]) ||
'';
setSelectedChatModelProvider(chatModelProvider);
setSelectedChatModel(chatModel);
setSelectedEmbeddingModelProvider(embeddingModelProvider);
setSelectedEmbeddingModel(embeddingModel);
setCustomOpenAIApiKey(localStorage.getItem('openAIApiKey') || '');
setCustomOpenAIBaseURL(localStorage.getItem('openAIBaseURL') || '');
setIsLoading(false);
};
const handleSubmit = async () => { const handleSubmit = async () => {
setIsUpdating(true); setIsUpdating(true);
try { try {
await fetch(`${process.env.NEXT_PUBLIC_API_URL}/config`, { const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/config`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
Authorization: `Bearer ${password}`,
}, },
body: JSON.stringify(config), body: JSON.stringify(config),
}); });
if (res.status === 401) {
toast.error('Unauthorized');
return;
}
localStorage.setItem('chatModelProvider', selectedChatModelProvider!); localStorage.setItem('chatModelProvider', selectedChatModelProvider!);
localStorage.setItem('chatModel', selectedChatModel!); localStorage.setItem('chatModel', selectedChatModel!);
localStorage.setItem( localStorage.setItem(
@@ -196,7 +199,7 @@ const SettingsDialog = ({
className="relative z-50" className="relative z-50"
onClose={() => setIsOpen(false)} onClose={() => setIsOpen(false)}
> >
<TransitionChild <Transition.Child
as={Fragment} as={Fragment}
enter="ease-out duration-300" enter="ease-out duration-300"
enterFrom="opacity-0" enterFrom="opacity-0"
@@ -206,10 +209,10 @@ const SettingsDialog = ({
leaveTo="opacity-0" leaveTo="opacity-0"
> >
<div className="fixed inset-0 bg-white/50 dark:bg-black/50" /> <div className="fixed inset-0 bg-white/50 dark:bg-black/50" />
</TransitionChild> </Transition.Child>
<div className="fixed inset-0 overflow-y-auto"> <div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-center justify-center p-4 text-center"> <div className="flex min-h-full items-center justify-center p-4 text-center">
<TransitionChild <Transition.Child
as={Fragment} as={Fragment}
enter="ease-out duration-200" enter="ease-out duration-200"
enterFrom="opacity-0 scale-95" enterFrom="opacity-0 scale-95"
@@ -218,289 +221,403 @@ const SettingsDialog = ({
leaveFrom="opacity-100 scale-200" leaveFrom="opacity-100 scale-200"
leaveTo="opacity-0 scale-95" 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"> <Dialog.Panel 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"> {isPasswordValid && passwordSubmitted && (
Settings <>
</DialogTitle> <Dialog.Title className="text-xl font-medium leading-6 dark:text-white">
{config && !isLoading && ( Settings
<div className="flex flex-col space-y-4 mt-6"> </Dialog.Title>
<div className="flex flex-col space-y-1"> {config && !isLoading && (
<p className="text-black/70 dark:text-white/70 text-sm"> <div className="flex flex-col space-y-4 mt-6">
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"> <div className="flex flex-col space-y-1">
<p className="text-black/70 dark:text-white/70 text-sm"> <p className="text-black/70 dark:text-white/70 text-sm">
Chat Model Theme
</p> </p>
<Select <ThemeSwitcher />
value={selectedChatModel ?? undefined} </div>
onChange={(e) => <div className="flex flex-col items-start space-y-2">
setSelectedChatModel(e.target.value) <p className="text-black/70 dark:text-white/70 text-sm">
} Copilot enabled
options={(() => { </p>
const chatModelProvider = <Switch
config.chatModelProviders[ checked={config.isCopilotEnabled}
selectedChatModelProvider onChange={(checked) => {
]; setConfig({
...config,
isCopilotEnabled: checked,
});
}}
className="bg-light-secondary dark:bg-dark-secondary border border-light-200/70 dark:border-dark-200 relative inline-flex h-5 w-10 sm:h-6 sm:w-11 items-center rounded-full active:scale-95 duration-200 transition cursor-pointer"
>
<span className="sr-only">Copilot</span>
<span
className={cn(
config.isCopilotEnabled
? 'translate-x-6 bg-[#24A0ED]'
: 'translate-x-1 bg-black/50 dark:bg-white/50',
'inline-block h-3 w-3 sm:h-4 sm:w-4 transform rounded-full transition-all duration-200',
)}
/>
</Switch>
</div>
<div className="flex flex-col items-start space-y-2">
<p className="text-black/70 dark:text-white/70 text-sm">
Discover enabled
</p>
<Switch
checked={config.isDiscoverEnabled}
onChange={(checked) => {
setConfig({
...config,
isDiscoverEnabled: checked,
});
}}
className="bg-light-secondary dark:bg-dark-secondary border border-light-200/70 dark:border-dark-200 relative inline-flex h-5 w-10 sm:h-6 sm:w-11 items-center rounded-full active:scale-95 duration-200 transition cursor-pointer"
>
<span className="sr-only">Discover</span>
<span
className={cn(
config.isDiscoverEnabled
? 'translate-x-6 bg-[#24A0ED]'
: 'translate-x-1 bg-black/50 dark:bg-white/50',
'inline-block h-3 w-3 sm:h-4 sm:w-4 transform rounded-full transition-all duration-200',
)}
/>
</Switch>
</div>
<div className="flex flex-col items-start space-y-2">
<p className="text-black/70 dark:text-white/70 text-sm">
Library enabled
</p>
<Switch
checked={config.isLibraryEnabled}
onChange={(checked) => {
setConfig({
...config,
isLibraryEnabled: checked,
});
}}
className="bg-light-secondary dark:bg-dark-secondary border border-light-200/70 dark:border-dark-200 relative inline-flex h-5 w-10 sm:h-6 sm:w-11 items-center rounded-full active:scale-95 duration-200 transition cursor-pointer"
>
<span className="sr-only">Library</span>
<span
className={cn(
config.isLibraryEnabled
? 'translate-x-6 bg-[#24A0ED]'
: 'translate-x-1 bg-black/50 dark:bg-white/50',
'inline-block h-3 w-3 sm:h-4 sm:w-4 transform rounded-full transition-all duration-200',
)}
/>
</Switch>
</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],
);
}
}}
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 return chatModelProvider
? chatModelProvider.length > 0 ? chatModelProvider.length > 0
? chatModelProvider.map((model) => ({ ? chatModelProvider.map((model) => ({
value: model.name, value: model,
label: model.displayName, label: model,
})) }))
: [
{
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],
);
}}
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,
value: model,
}))
: [
{
label:
'No embedding models available',
value: '',
disabled: true,
},
]
: [ : [
{ {
label:
'Invalid provider, please check backend logs',
value: '', value: '',
label: 'No models available',
disabled: true, disabled: true,
}, },
] ];
: [ })()}
{ />
value: '', </div>
label: )}
'Invalid provider, please check backend logs', <div className="flex flex-col space-y-1">
disabled: true, <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>
)}
{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> </div>
)} )}
{selectedEmbeddingModelProvider && ( {isLoading && (
<div className="flex flex-col space-y-1"> <div className="w-full flex items-center justify-center mt-6 text-black/70 dark:text-white/70 py-6">
<p className="text-black/70 dark:text-white/70 text-sm"> <RefreshCcw className="animate-spin" />
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>
)} )}
<div className="flex flex-col space-y-1"> <div className="w-full mt-6 space-y-2">
<p className="text-black/70 dark:text-white/70 text-sm"> <p className="text-xs text-black/50 dark:text-white/50">
OpenAI API Key We&apos;ll refresh the page after updating the settings.
</p> </p>
<Input <button
type="text" onClick={handleSubmit}
placeholder="OpenAI API Key" 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"
defaultValue={config.openaiApiKey} disabled={isLoading || isUpdating}
onChange={(e) => >
setConfig({ {isUpdating ? (
...config, <RefreshCw size={20} className="animate-spin" />
openaiApiKey: e.target.value, ) : (
}) <CloudUpload size={20} />
} )}
/> </button>
</div> </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>
)} )}
{isLoading && ( {!passwordSubmitted && (
<div className="w-full flex items-center justify-center mt-6 text-black/70 dark:text-white/70 py-6"> <>
<RefreshCcw className="animate-spin" /> <Dialog.Title className="text-sm dark:font-white/80 font-black/80">
</div> Enter the password to access the settings
)} </Dialog.Title>
<div className="w-full mt-6 space-y-2"> <div className="flex flex-col">
<p className="text-xs text-black/50 dark:text-white/50"> <Input
We&apos;ll refresh the page after updating the settings. type="password"
</p> placeholder="Password"
<button className="mt-4"
onClick={handleSubmit} disabled={isLoading}
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" onChange={(e) => setPassword(e.target.value)}
disabled={isLoading || isUpdating} />
> </div>
{isUpdating ? ( {!isPasswordValid && (
<RefreshCw size={20} className="animate-spin" /> <p className="text-xs text-red-500 mt-2">
) : ( Password is incorrect
<CloudUpload size={20} /> </p>
)} )}
</button> <button
</div> onClick={handlePasswordSubmit}
</DialogPanel> disabled={isLoading}
</TransitionChild> className="bg-[#24A0ED] flex flex-row items-center text-xs mt-4 text-white disabled:text-white/50 hover:bg-opacity-85 transition duration-100 disabled:bg-[#ececec21] rounded-full px-4 py-2"
>
Submit
</button>
</>
)}
</Dialog.Panel>
</Transition.Child>
</div> </div>
</div> </div>
</Dialog> </Dialog>

View File

@@ -4,10 +4,16 @@ import { cn } from '@/lib/utils';
import { BookOpenText, Home, Search, SquarePen, Settings } from 'lucide-react'; import { BookOpenText, Home, Search, SquarePen, Settings } from 'lucide-react';
import Link from 'next/link'; import Link from 'next/link';
import { useSelectedLayoutSegments } from 'next/navigation'; import { useSelectedLayoutSegments } from 'next/navigation';
import React, { useState, type ReactNode } from 'react'; import React, { useEffect, useMemo, useState, type ReactNode } from 'react';
import Layout from './Layout'; import Layout from './Layout';
import SettingsDialog from './SettingsDialog'; import SettingsDialog from './SettingsDialog';
export type Preferences = {
isLibraryEnabled: boolean;
isDiscoverEnabled: boolean;
isCopilotEnabled: boolean;
};
const VerticalIconContainer = ({ children }: { children: ReactNode }) => { const VerticalIconContainer = ({ children }: { children: ReactNode }) => {
return ( return (
<div className="flex flex-col items-center gap-y-3 w-full">{children}</div> <div className="flex flex-col items-center gap-y-3 w-full">{children}</div>
@@ -18,6 +24,31 @@ const Sidebar = ({ children }: { children: React.ReactNode }) => {
const segments = useSelectedLayoutSegments(); const segments = useSelectedLayoutSegments();
const [isSettingsOpen, setIsSettingsOpen] = useState(false); const [isSettingsOpen, setIsSettingsOpen] = useState(false);
const [preferences, setPreferences] = useState<Preferences | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchPreferences = async () => {
setLoading(true);
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/config/preferences`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
},
);
const data = await res.json();
setPreferences(data);
setLoading(false);
};
fetchPreferences();
}, []);
const navLinks = [ const navLinks = [
{ {
@@ -25,22 +56,44 @@ const Sidebar = ({ children }: { children: React.ReactNode }) => {
href: '/', href: '/',
active: segments.length === 0 || segments.includes('c'), active: segments.length === 0 || segments.includes('c'),
label: 'Home', label: 'Home',
show: true,
}, },
{ {
icon: Search, icon: Search,
href: '/discover', href: '/discover',
active: segments.includes('discover'), active: segments.includes('discover'),
label: 'Discover', label: 'Discover',
show: preferences?.isDiscoverEnabled,
}, },
{ {
icon: BookOpenText, icon: BookOpenText,
href: '/library', href: '/library',
active: segments.includes('library'), active: segments.includes('library'),
label: 'Library', label: 'Library',
show: preferences?.isLibraryEnabled,
}, },
]; ];
return ( return loading ? (
<div className="flex flex-row items-center justify-center h-full">
<svg
aria-hidden="true"
className="w-8 h-8 text-light-200 fill-light-secondary dark:text-[#202020] animate-spin dark:fill-[#ffffff3b]"
viewBox="0 0 100 101"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M100 50.5908C100.003 78.2051 78.1951 100.003 50.5908 100C22.9765 99.9972 0.997224 78.018 1 50.4037C1.00281 22.7993 22.8108 0.997224 50.4251 1C78.0395 1.00281 100.018 22.8108 100 50.4251ZM9.08164 50.594C9.06312 73.3997 27.7909 92.1272 50.5966 92.1457C73.4023 92.1642 92.1298 73.4365 92.1483 50.6308C92.1669 27.8251 73.4392 9.0973 50.6335 9.07878C27.8278 9.06026 9.10003 27.787 9.08164 50.594Z"
fill="currentColor"
/>
<path
d="M93.9676 39.0409C96.393 38.4037 97.8624 35.9116 96.9801 33.5533C95.1945 28.8227 92.871 24.3692 90.0681 20.348C85.6237 14.1775 79.4473 9.36872 72.0454 6.45794C64.6435 3.54717 56.3134 2.65431 48.3133 3.89319C45.869 4.27179 44.3768 6.77534 45.014 9.20079C45.6512 11.6262 48.1343 13.0956 50.5786 12.717C56.5073 11.8281 62.5542 12.5399 68.0406 14.7911C73.527 17.0422 78.2187 20.7487 81.5841 25.4923C83.7976 28.5886 85.4467 32.059 86.4416 35.7474C87.1273 38.1189 89.5423 39.6781 91.9676 39.0409Z"
fill="currentFill"
/>
</svg>
</div>
) : (
<div> <div>
<div className="hidden lg:fixed lg:inset-y-0 lg:z-50 lg:flex lg:w-20 lg:flex-col"> <div className="hidden lg:fixed lg:inset-y-0 lg:z-50 lg:flex lg:w-20 lg:flex-col">
<div className="flex grow flex-col items-center justify-between gap-y-5 overflow-y-auto bg-light-secondary dark:bg-dark-secondary px-2 py-8"> <div className="flex grow flex-col items-center justify-between gap-y-5 overflow-y-auto bg-light-secondary dark:bg-dark-secondary px-2 py-8">
@@ -48,23 +101,26 @@ const Sidebar = ({ children }: { children: React.ReactNode }) => {
<SquarePen className="cursor-pointer" /> <SquarePen className="cursor-pointer" />
</a> </a>
<VerticalIconContainer> <VerticalIconContainer>
{navLinks.map((link, i) => ( {navLinks.map(
<Link (link, i) =>
key={i} link.show === true && (
href={link.href} <Link
className={cn( key={i}
'relative flex flex-row items-center justify-center cursor-pointer hover:bg-black/10 dark:hover:bg-white/10 duration-150 transition w-full py-2 rounded-lg', href={link.href}
link.active className={cn(
? 'text-black dark:text-white' 'relative flex flex-row items-center justify-center cursor-pointer hover:bg-black/10 dark:hover:bg-white/10 duration-150 transition w-full py-2 rounded-lg',
: 'text-black/70 dark:text-white/70', link.active
)} ? 'text-black dark:text-white'
> : 'text-black/70 dark:text-white/70',
<link.icon /> )}
{link.active && ( >
<div className="absolute right-0 -mr-2 h-full w-1 rounded-l-lg bg-black dark:bg-white" /> <link.icon />
)} {link.active && (
</Link> <div className="absolute right-0 -mr-2 h-full w-1 rounded-l-lg bg-black dark:bg-white" />
))} )}
</Link>
),
)}
</VerticalIconContainer> </VerticalIconContainer>
<Settings <Settings

View File

@@ -4,24 +4,15 @@ export const getSuggestions = async (chatHisory: Message[]) => {
const chatModel = localStorage.getItem('chatModel'); const chatModel = localStorage.getItem('chatModel');
const chatModelProvider = localStorage.getItem('chatModelProvider'); const chatModelProvider = localStorage.getItem('chatModelProvider');
const customOpenAIKey = localStorage.getItem('openAIApiKey');
const customOpenAIBaseURL = localStorage.getItem('openAIBaseURL');
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/suggestions`, { const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/suggestions`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
body: JSON.stringify({ body: JSON.stringify({
chatHistory: chatHisory, chat_history: chatHisory,
chatModel: { chat_model: chatModel,
provider: chatModelProvider, chat_model_provider: chatModelProvider,
model: chatModel,
...(chatModelProvider === 'custom_openai' && {
customOpenAIKey,
customOpenAIBaseURL,
}),
},
}), }),
}); });

View File

@@ -1,6 +1,6 @@
{ {
"name": "perplexica-frontend", "name": "perplexica-frontend",
"version": "1.9.2", "version": "1.9.0-rc1",
"license": "MIT", "license": "MIT",
"author": "ItzCrazyKns", "author": "ItzCrazyKns",
"scripts": { "scripts": {
@@ -11,7 +11,7 @@
"format:write": "prettier . --write" "format:write": "prettier . --write"
}, },
"dependencies": { "dependencies": {
"@headlessui/react": "^2.1.9", "@headlessui/react": "^1.7.18",
"@icons-pack/react-simple-icons": "^9.4.0", "@icons-pack/react-simple-icons": "^9.4.0",
"@langchain/openai": "^0.0.25", "@langchain/openai": "^0.0.25",
"@tailwindcss/typography": "^0.5.12", "@tailwindcss/typography": "^0.5.12",

View File

@@ -66,51 +66,13 @@
resolved "https://registry.yarnpkg.com/@eslint/js/-/js-8.57.0.tgz#a5417ae8427873f1dd08b70b3574b453e67b5f7f" resolved "https://registry.yarnpkg.com/@eslint/js/-/js-8.57.0.tgz#a5417ae8427873f1dd08b70b3574b453e67b5f7f"
integrity sha512-Ys+3g2TaW7gADOJzPt83SJtCDhMjndcDMFVQ/Tj9iA1BfJzFKD9mAUXT3OenpuPHbI6P/myECxRJrofUsDx/5g== integrity sha512-Ys+3g2TaW7gADOJzPt83SJtCDhMjndcDMFVQ/Tj9iA1BfJzFKD9mAUXT3OenpuPHbI6P/myECxRJrofUsDx/5g==
"@floating-ui/core@^1.6.0": "@headlessui/react@^1.7.18":
version "1.6.8" version "1.7.18"
resolved "https://registry.yarnpkg.com/@floating-ui/core/-/core-1.6.8.tgz#aa43561be075815879305965020f492cdb43da12" resolved "https://registry.yarnpkg.com/@headlessui/react/-/react-1.7.18.tgz#30af4634d2215b2ca1aa29d07f33d02bea82d9d7"
integrity sha512-7XJ9cPU+yI2QeLS+FCSlqNFZJq8arvswefkZrYI1yQBbftw6FyrZOxYSh+9S7z7TpeWlRt9zJ5IhM1WIL334jA== integrity sha512-4i5DOrzwN4qSgNsL4Si61VMkUcWbcSKueUV7sFhpHzQcSShdlHENE5+QBntMSRvHt8NyoFO2AGG8si9lq+w4zQ==
dependencies: dependencies:
"@floating-ui/utils" "^0.2.8" "@tanstack/react-virtual" "^3.0.0-beta.60"
client-only "^0.0.1"
"@floating-ui/dom@^1.0.0":
version "1.6.11"
resolved "https://registry.yarnpkg.com/@floating-ui/dom/-/dom-1.6.11.tgz#8631857838d34ee5712339eb7cbdfb8ad34da723"
integrity sha512-qkMCxSR24v2vGkhYDo/UzxfJN3D4syqSjyuTFz6C7XcpU1pASPRieNI0Kj5VP3/503mOfYiGY891ugBX1GlABQ==
dependencies:
"@floating-ui/core" "^1.6.0"
"@floating-ui/utils" "^0.2.8"
"@floating-ui/react-dom@^2.1.2":
version "2.1.2"
resolved "https://registry.yarnpkg.com/@floating-ui/react-dom/-/react-dom-2.1.2.tgz#a1349bbf6a0e5cb5ded55d023766f20a4d439a31"
integrity sha512-06okr5cgPzMNBy+Ycse2A6udMi4bqwW/zgBF/rwjcNqWkyr82Mcg8b0vjX8OJpZFy/FKjJmw6wV7t44kK6kW7A==
dependencies:
"@floating-ui/dom" "^1.0.0"
"@floating-ui/react@^0.26.16":
version "0.26.24"
resolved "https://registry.yarnpkg.com/@floating-ui/react/-/react-0.26.24.tgz#072b9dfeca4e79ef4e3000ef1c28e0ffc86f4ed4"
integrity sha512-2ly0pCkZIGEQUq5H8bBK0XJmc1xIK/RM3tvVzY3GBER7IOD1UgmC2Y2tjj4AuS+TC+vTE1KJv2053290jua0Sw==
dependencies:
"@floating-ui/react-dom" "^2.1.2"
"@floating-ui/utils" "^0.2.8"
tabbable "^6.0.0"
"@floating-ui/utils@^0.2.8":
version "0.2.8"
resolved "https://registry.yarnpkg.com/@floating-ui/utils/-/utils-0.2.8.tgz#21a907684723bbbaa5f0974cf7730bd797eb8e62"
integrity sha512-kym7SodPp8/wloecOpcmSnWJsK7M0E5Wg8UcFA+uO4B9s5d0ywXOEro/8HM9x0rW+TljRzul/14UYz3TleT3ig==
"@headlessui/react@^2.1.9":
version "2.1.9"
resolved "https://registry.yarnpkg.com/@headlessui/react/-/react-2.1.9.tgz#d8d3ff64255177a87706cc4f24f42aeac65b1695"
integrity sha512-ckWw7vlKtnoa1fL2X0fx1a3t/Li9MIKDVXn3SgG65YlxvDAsNrY39PPCxVM7sQRA7go2fJsuHSSauKFNaJHH7A==
dependencies:
"@floating-ui/react" "^0.26.16"
"@react-aria/focus" "^3.17.1"
"@react-aria/interactions" "^3.21.3"
"@tanstack/react-virtual" "^3.8.1"
"@humanwhocodes/config-array@^0.11.14": "@humanwhocodes/config-array@^0.11.14":
version "0.11.14" version "0.11.14"
@@ -316,57 +278,6 @@
resolved "https://registry.yarnpkg.com/@pkgjs/parseargs/-/parseargs-0.11.0.tgz#a77ea742fab25775145434eb1d2328cf5013ac33" resolved "https://registry.yarnpkg.com/@pkgjs/parseargs/-/parseargs-0.11.0.tgz#a77ea742fab25775145434eb1d2328cf5013ac33"
integrity sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg== integrity sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==
"@react-aria/focus@^3.17.1":
version "3.18.3"
resolved "https://registry.yarnpkg.com/@react-aria/focus/-/focus-3.18.3.tgz#4fe32de1e7530beab8da2e7b89f0f17d22a47e5e"
integrity sha512-WKUElg+5zS0D3xlVn8MntNnkzJql2J6MuzAMP8Sv5WTgFDse/XGR842dsxPTIyKKdrWVCRegCuwa4m3n/GzgJw==
dependencies:
"@react-aria/interactions" "^3.22.3"
"@react-aria/utils" "^3.25.3"
"@react-types/shared" "^3.25.0"
"@swc/helpers" "^0.5.0"
clsx "^2.0.0"
"@react-aria/interactions@^3.21.3", "@react-aria/interactions@^3.22.3":
version "3.22.3"
resolved "https://registry.yarnpkg.com/@react-aria/interactions/-/interactions-3.22.3.tgz#3ba50db12f6ed443ae061eed79e41509eaa3d8e6"
integrity sha512-RRUb/aG+P0IKTIWikY/SylB6bIbLZeztnZY2vbe7RAG5MgVaCgn5HQ45SI15GlTmhsFG8CnF6slJsUFJiNHpbQ==
dependencies:
"@react-aria/ssr" "^3.9.6"
"@react-aria/utils" "^3.25.3"
"@react-types/shared" "^3.25.0"
"@swc/helpers" "^0.5.0"
"@react-aria/ssr@^3.9.6":
version "3.9.6"
resolved "https://registry.yarnpkg.com/@react-aria/ssr/-/ssr-3.9.6.tgz#a9e8b351acdc8238f2b5215b0ce904636c6ea690"
integrity sha512-iLo82l82ilMiVGy342SELjshuWottlb5+VefO3jOQqQRNYnJBFpUSadswDPbRimSgJUZuFwIEYs6AabkP038fA==
dependencies:
"@swc/helpers" "^0.5.0"
"@react-aria/utils@^3.25.3":
version "3.25.3"
resolved "https://registry.yarnpkg.com/@react-aria/utils/-/utils-3.25.3.tgz#cad9bffc07b045cdc283df2cb65c18747acbf76d"
integrity sha512-PR5H/2vaD8fSq0H/UB9inNbc8KDcVmW6fYAfSWkkn+OAdhTTMVKqXXrZuZBWyFfSD5Ze7VN6acr4hrOQm2bmrA==
dependencies:
"@react-aria/ssr" "^3.9.6"
"@react-stately/utils" "^3.10.4"
"@react-types/shared" "^3.25.0"
"@swc/helpers" "^0.5.0"
clsx "^2.0.0"
"@react-stately/utils@^3.10.4":
version "3.10.4"
resolved "https://registry.yarnpkg.com/@react-stately/utils/-/utils-3.10.4.tgz#310663a834b67048d305e1680ed258130092fe51"
integrity sha512-gBEQEIMRh5f60KCm7QKQ2WfvhB2gLUr9b72sqUdIZ2EG+xuPgaIlCBeSicvjmjBvYZwOjoOEnmIkcx2GHp/HWw==
dependencies:
"@swc/helpers" "^0.5.0"
"@react-types/shared@^3.25.0":
version "3.25.0"
resolved "https://registry.yarnpkg.com/@react-types/shared/-/shared-3.25.0.tgz#7223baf72256e918a3c29081bb1ecc6fad4fbf58"
integrity sha512-OZSyhzU6vTdW3eV/mz5i6hQwQUhkRs7xwY2d1aqPvTdMe0+2cY7Fwp45PAiwYLEj73i9ro2FxF9qC4DvHGSCgQ==
"@rushstack/eslint-patch@^1.3.3": "@rushstack/eslint-patch@^1.3.3":
version "1.10.1" version "1.10.1"
resolved "https://registry.yarnpkg.com/@rushstack/eslint-patch/-/eslint-patch-1.10.1.tgz#7ca168b6937818e9a74b47ac4e2112b2e1a024cf" resolved "https://registry.yarnpkg.com/@rushstack/eslint-patch/-/eslint-patch-1.10.1.tgz#7ca168b6937818e9a74b47ac4e2112b2e1a024cf"
@@ -379,13 +290,6 @@
dependencies: dependencies:
tslib "^2.4.0" tslib "^2.4.0"
"@swc/helpers@^0.5.0":
version "0.5.13"
resolved "https://registry.yarnpkg.com/@swc/helpers/-/helpers-0.5.13.tgz#33e63ff3cd0cade557672bd7888a39ce7d115a8c"
integrity sha512-UoKGxQ3r5kYI9dALKJapMmuK+1zWM/H17Z1+iwnNmzcJRnfFuevZs375TA5rW31pu4BS4NoSy1fRsexDXfWn5w==
dependencies:
tslib "^2.4.0"
"@tailwindcss/typography@^0.5.12": "@tailwindcss/typography@^0.5.12":
version "0.5.12" version "0.5.12"
resolved "https://registry.yarnpkg.com/@tailwindcss/typography/-/typography-0.5.12.tgz#c0532fd594427b7f4e8e38eff7bf272c63a1dca4" resolved "https://registry.yarnpkg.com/@tailwindcss/typography/-/typography-0.5.12.tgz#c0532fd594427b7f4e8e38eff7bf272c63a1dca4"
@@ -396,17 +300,17 @@
lodash.merge "^4.6.2" lodash.merge "^4.6.2"
postcss-selector-parser "6.0.10" postcss-selector-parser "6.0.10"
"@tanstack/react-virtual@^3.8.1": "@tanstack/react-virtual@^3.0.0-beta.60":
version "3.10.8" version "3.2.0"
resolved "https://registry.yarnpkg.com/@tanstack/react-virtual/-/react-virtual-3.10.8.tgz#bf4b06f157ed298644a96ab7efc1a2b01ab36e3c" resolved "https://registry.yarnpkg.com/@tanstack/react-virtual/-/react-virtual-3.2.0.tgz#fb70f9c6baee753a5a0f7618ac886205d5a02af9"
integrity sha512-VbzbVGSsZlQktyLrP5nxE+vE1ZR+U0NFAWPbJLoG2+DKPwd2D7dVICTVIIaYlJqX1ZCEnYDbaOpmMwbsyhBoIA== integrity sha512-OEdMByf2hEfDa6XDbGlZN8qO6bTjlNKqjM3im9JG+u3mCL8jALy0T/67oDI001raUUPh1Bdmfn4ZvPOV5knpcg==
dependencies: dependencies:
"@tanstack/virtual-core" "3.10.8" "@tanstack/virtual-core" "3.2.0"
"@tanstack/virtual-core@3.10.8": "@tanstack/virtual-core@3.2.0":
version "3.10.8" version "3.2.0"
resolved "https://registry.yarnpkg.com/@tanstack/virtual-core/-/virtual-core-3.10.8.tgz#975446a667755222f62884c19e5c3c66d959b8b4" resolved "https://registry.yarnpkg.com/@tanstack/virtual-core/-/virtual-core-3.2.0.tgz#874d36135e4badce2719e7bdc556ce240cbaff14"
integrity sha512-PBu00mtt95jbKFi6Llk9aik8bnR3tR/oQP1o3TSi+iG//+Q2RTIzCEgKkHG8BB86kxMNW6O8wku+Lmi+QFR6jA== integrity sha512-P5XgYoAw/vfW65byBbJQCw+cagdXDT/qH6wmABiLt4v4YBT2q2vqCOhihe+D1Nt325F/S/0Tkv6C5z0Lv+VBQQ==
"@types/json5@^0.0.29": "@types/json5@^0.0.29":
version "0.0.29" version "0.0.29"
@@ -875,16 +779,11 @@ chokidar@^3.5.3:
optionalDependencies: optionalDependencies:
fsevents "~2.3.2" fsevents "~2.3.2"
client-only@0.0.1: client-only@0.0.1, client-only@^0.0.1:
version "0.0.1" version "0.0.1"
resolved "https://registry.yarnpkg.com/client-only/-/client-only-0.0.1.tgz#38bba5d403c41ab150bff64a95c85013cf73bca1" resolved "https://registry.yarnpkg.com/client-only/-/client-only-0.0.1.tgz#38bba5d403c41ab150bff64a95c85013cf73bca1"
integrity sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA== integrity sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==
clsx@^2.0.0:
version "2.1.1"
resolved "https://registry.yarnpkg.com/clsx/-/clsx-2.1.1.tgz#eed397c9fd8bd882bfb18deab7102049a2f32999"
integrity sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==
clsx@^2.1.0: clsx@^2.1.0:
version "2.1.0" version "2.1.0"
resolved "https://registry.yarnpkg.com/clsx/-/clsx-2.1.0.tgz#e851283bcb5c80ee7608db18487433f7b23f77cb" resolved "https://registry.yarnpkg.com/clsx/-/clsx-2.1.0.tgz#e851283bcb5c80ee7608db18487433f7b23f77cb"
@@ -3096,11 +2995,6 @@ supports-preserve-symlinks-flag@^1.0.0:
resolved "https://registry.yarnpkg.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz#6eda4bd344a3c94aea376d4cc31bc77311039e09" resolved "https://registry.yarnpkg.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz#6eda4bd344a3c94aea376d4cc31bc77311039e09"
integrity sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w== integrity sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==
tabbable@^6.0.0:
version "6.2.0"
resolved "https://registry.yarnpkg.com/tabbable/-/tabbable-6.2.0.tgz#732fb62bc0175cfcec257330be187dcfba1f3b97"
integrity sha512-Cat63mxsVJlzYvN51JmVXIgNoUokrIaT2zLclCXjRd8boZ0004U4KCs/sToJ75C6sdlByWxpYnb5Boif1VSFew==
tailwind-merge@^2.2.2: tailwind-merge@^2.2.2:
version "2.2.2" version "2.2.2"
resolved "https://registry.yarnpkg.com/tailwind-merge/-/tailwind-merge-2.2.2.tgz#87341e7604f0e20499939e152cd2841f41f7a3df" resolved "https://registry.yarnpkg.com/tailwind-merge/-/tailwind-merge-2.2.2.tgz#87341e7604f0e20499939e152cd2841f41f7a3df"

View File

@@ -690,13 +690,6 @@
resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-9.0.8.tgz#7545ba4fc3c003d6c756f651f3bf163d8f0f29ba" resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-9.0.8.tgz#7545ba4fc3c003d6c756f651f3bf163d8f0f29ba"
integrity sha512-jg+97EGIcY9AGHJJRaaPVgetKDsrTgbRjQ5Msgjh/DQKEFl0DtyRr/VCOyD1T2R1MNeWPK/u7JoGhlDZnKBAfA== integrity sha512-jg+97EGIcY9AGHJJRaaPVgetKDsrTgbRjQ5Msgjh/DQKEFl0DtyRr/VCOyD1T2R1MNeWPK/u7JoGhlDZnKBAfA==
"@types/ws@^8.5.12":
version "8.5.12"
resolved "https://registry.yarnpkg.com/@types/ws/-/ws-8.5.12.tgz#619475fe98f35ccca2a2f6c137702d85ec247b7e"
integrity sha512-3tPRkv1EtkDpzlgyKyI8pGsGZAGPEaXeu0DOj5DI25Ja91bdAYddYHbADRYVrZMRbfW+1l5YwXVDKohDJNQxkQ==
dependencies:
"@types/node" "*"
"@xenova/transformers@^2.17.1": "@xenova/transformers@^2.17.1":
version "2.17.1" version "2.17.1"
resolved "https://registry.yarnpkg.com/@xenova/transformers/-/transformers-2.17.1.tgz#712f7a72c76c8aa2075749382f83dc7dd4e5a9a5" resolved "https://registry.yarnpkg.com/@xenova/transformers/-/transformers-2.17.1.tgz#712f7a72c76c8aa2075749382f83dc7dd4e5a9a5"