diff --git a/.assets/perplexica-screenshot.png b/.assets/perplexica-screenshot.png index c47a544..fc7a697 100644 Binary files a/.assets/perplexica-screenshot.png and b/.assets/perplexica-screenshot.png differ diff --git a/.github/workflows/docker-build.yaml b/.github/workflows/docker-build.yaml new file mode 100644 index 0000000..f658c29 --- /dev/null +++ b/.github/workflows/docker-build.yaml @@ -0,0 +1,73 @@ +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 . diff --git a/.gitignore b/.gitignore index d64d5cc..8391d19 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,7 @@ yarn-error.log # Build output /.next/ /out/ +/dist/ # IDE/Editor specific .vscode/ @@ -31,4 +32,8 @@ logs/ # Miscellaneous .DS_Store -Thumbs.db \ No newline at end of file +Thumbs.db + +# Db +db.sqlite +/searxng diff --git a/.prettierignore b/.prettierignore index c184fdb..55d3c7c 100644 --- a/.prettierignore +++ b/.prettierignore @@ -35,4 +35,7 @@ coverage *.swp # Ignore all files with the .DS_Store extension (macOS specific) -.DS_Store \ No newline at end of file +.DS_Store + +# Ignore all files in uploads directory +uploads \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c779f91..b16eccf 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,6 +8,7 @@ Perplexica's design consists of two main domains: - **Frontend (`ui` directory)**: This is a Next.js application holding all user interface components. It's a self-contained environment that manages everything the user interacts with. - **Backend (root and `src` directory)**: The backend logic is situated in the `src` folder, but the root directory holds the main `package.json` for backend dependency management. + - All of the focus modes are created using the Meta Search Agent class present in `src/search/metaSearchAgent.ts`. The main logic behind Perplexica lies there. ## Setting Up Your Environment @@ -18,7 +19,8 @@ Before diving into coding, setting up your local environment is key. Here's what 1. In the root directory, locate the `sample.config.toml` file. 2. Rename it to `config.toml` and fill in the necessary configuration fields specific to the backend. 3. Run `npm install` to install dependencies. -4. Use `npm run dev` to start the backend in development mode. +4. Run `npm run db:push` to set up the local sqlite. +5. Use `npm run dev` to start the backend in development mode. ### Frontend diff --git a/README.md b/README.md index 0cf197b..cf9e459 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,9 @@ # 🚀 Perplexica - An AI-powered search engine 🔎 -![preview](.assets/perplexica-screenshot.png) +[![Discord](https://dcbadge.vercel.app/api/server/26aArMy8tT?style=flat&compact=true)](https://discord.gg/26aArMy8tT) + + +![preview](.assets/perplexica-screenshot.png?) ## Table of Contents @@ -10,8 +13,10 @@ - [Installation](#installation) - [Getting Started with Docker (Recommended)](#getting-started-with-docker-recommended) - [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 Perplexica's API](#using-perplexicas-api) +- [Expose Perplexica to a network](#expose-perplexica-to-network) - [One-Click Deployment](#one-click-deployment) - [Upcoming Features](#upcoming-features) - [Support Us](#support-us) @@ -45,6 +50,7 @@ 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. - **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. +- **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). @@ -67,7 +73,8 @@ There are mainly 2 ways of installing Perplexica - With Docker, Without Docker. - `OPENAI`: Your OpenAI API key. **You only need to fill this if you wish to use OpenAI's models**. - `OLLAMA`: Your Ollama API URL. You should enter it as `http://host.docker.internal:PORT_NUMBER`. If you installed Ollama on port 11434, use `http://host.docker.internal:11434`. For other ports, adjust accordingly. **You need to fill this if you wish to use Ollama's models instead of OpenAI's**. - - `GROQ`: Your Groq API key. **You only need to fill this if you wish to use Groq's hosted models** + - `GROQ`: Your Groq API key. **You only need to fill this if you wish to use Groq's hosted models**. + - `ANTHROPIC`: Your Anthropic API key. **You only need to fill this if you wish to use Anthropic models**. **Note**: You can change these after starting Perplexica from the settings dialog. @@ -85,25 +92,35 @@ There are mainly 2 ways of installing Perplexica - With Docker, Without Docker. ### Non-Docker Installation -1. Clone the repository and rename the `sample.config.toml` file to `config.toml` in the root directory. Ensure you complete all required fields in this file. -2. Rename the `.env.example` file to `.env` in the `ui` folder and fill in all necessary fields. -3. After populating the configuration and environment files, run `npm i` in both the `ui` folder and the root directory. -4. Install the dependencies and then execute `npm run build` in both the `ui` folder and the root directory. -5. Finally, start both the frontend and the backend by running `npm run start` in both the `ui` folder and the root directory. +1. Install SearXNG and allow `JSON` format in the SearXNG settings. +2. Clone the repository and rename the `sample.config.toml` file to `config.toml` in the root directory. Ensure you complete all required fields in this file. +3. Rename the `.env.example` file to `.env` in the `ui` folder and fill in all necessary fields. +4. After populating the configuration and environment files, run `npm i` in both the `ui` folder and the root directory. +5. Install the dependencies and then execute `npm run build` in both the `ui` folder and the root directory. +6. Finally, start both the frontend and the backend by running `npm run start` in both the `ui` folder and the root directory. **Note**: Using Docker is recommended as it simplifies the setup process, especially for managing environment variables and dependencies. See the [installation documentation](https://github.com/ItzCrazyKns/Perplexica/tree/master/docs/installation) for more information like exposing it your network, etc. -### Ollama connection errors +### Ollama Connection Errors -If you're facing an Ollama connection error, it is often related to the backend not being able to connect to Ollama's API. How can you fix it? You can fix it by updating your Ollama API URL in the settings menu to the following: +If you're encountering an Ollama connection error, it is likely due to the backend being unable to connect to Ollama's API. To fix this issue you can: -On Windows: `http://host.docker.internal:11434`
-On Mac: `http://host.docker.internal:11434`
-On Linux: `http://private_ip_of_computer_hosting_ollama:11434` +1. **Check your Ollama API URL:** Ensure that the API URL is correctly set in the settings menu. +2. **Update API URL Based on OS:** -You need to edit the ports accordingly. + - **Windows:** Use `http://host.docker.internal:11434` + - **Mac:** Use `http://host.docker.internal:11434` + - **Linux:** Use `http://:11434` + + Adjust the port number if you're using a different one. + +3. **Linux Users - Expose Ollama to Network:** + + - Inside `/etc/systemd/system/ollama.service`, you need to add `Environment="OLLAMA_HOST=0.0.0.0"`. Then restart Ollama by `systemctl restart ollama`. For more information see [Ollama docs](https://github.com/ollama/ollama/blob/main/docs/faq.md#setting-environment-variables-on-linux) + + - Ensure that the port (default is 11434) is not blocked by your firewall. ## Using as a Search Engine @@ -114,17 +131,29 @@ 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. 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 [![Deploy to RepoCloud](https://d16t0pc4846x52.cloudfront.net/deploylobe.svg)](https://repocloud.io/details/?app_id=267) ## Upcoming Features -- [ ] Finalizing Copilot Mode - [x] Add settings page - [x] Adding support for local LLMs -- [ ] Adding Discover and History Saving features +- [x] History Saving features - [x] Introducing various Focus Modes +- [x] Adding API support +- [x] Adding Discover +- [ ] Finalizing Copilot Mode ## Support Us @@ -132,11 +161,11 @@ If you find Perplexica useful, consider giving us a star on GitHub. This helps m ### Donations -We also accept donations to help sustain our project. If you would like to contribute, you can use the following button to make a donation in cryptocurrency. Thank you for your support! +We also accept donations to help sustain our project. If you would like to contribute, you can use the following options to donate. Thank you for your support! - - Crypto donation button by NOWPayments - +| Ethereum | +| ----------------------------------------------------- | +| Address: `0xB025a84b2F269570Eb8D4b05DEdaA41D8525B6DD` | ## Contribution diff --git a/app.dockerfile b/app.dockerfile index 105cf86..488e64b 100644 --- a/app.dockerfile +++ b/app.dockerfile @@ -1,7 +1,7 @@ -FROM node:alpine +FROM node:20.18.0-alpine -ARG NEXT_PUBLIC_WS_URL -ARG NEXT_PUBLIC_API_URL +ARG NEXT_PUBLIC_WS_URL=ws://127.0.0.1:3001 +ARG NEXT_PUBLIC_API_URL=http://127.0.0.1:3001/api ENV NEXT_PUBLIC_WS_URL=${NEXT_PUBLIC_WS_URL} ENV NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL} @@ -9,7 +9,7 @@ WORKDIR /home/perplexica COPY ui /home/perplexica/ -RUN yarn install +RUN yarn install --frozen-lockfile RUN yarn build CMD ["yarn", "start"] \ No newline at end of file diff --git a/backend.dockerfile b/backend.dockerfile index 47c5d81..b6ab95a 100644 --- a/backend.dockerfile +++ b/backend.dockerfile @@ -1,18 +1,17 @@ -FROM node:buster-slim - -ARG SEARXNG_API_URL +FROM node:18-slim WORKDIR /home/perplexica COPY src /home/perplexica/src COPY tsconfig.json /home/perplexica/ -COPY config.toml /home/perplexica/ +COPY drizzle.config.ts /home/perplexica/ COPY package.json /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/uploads -RUN yarn install +RUN yarn install --frozen-lockfile --network-timeout 600000 RUN yarn build CMD ["yarn", "start"] \ No newline at end of file diff --git a/data/.gitignore b/data/.gitignore new file mode 100644 index 0000000..d6b7ef3 --- /dev/null +++ b/data/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/docker-compose.yaml b/docker-compose.yaml index 0b3d80e..a0e1d73 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -13,12 +13,19 @@ services: build: context: . dockerfile: backend.dockerfile - args: - - SEARXNG_API_URL=http://searxng:8080 + image: itzcrazykns1337/perplexica-backend:main + environment: + - SEARXNG_API_URL=http://searxng:8080 depends_on: - searxng ports: - 3001:3001 + volumes: + - backend-dbstore:/home/perplexica/data + - uploads:/home/perplexica/uploads + - ./config.toml:/home/perplexica/config.toml + extra_hosts: + - 'host.docker.internal:host-gateway' networks: - perplexica-network restart: unless-stopped @@ -30,6 +37,7 @@ services: args: - NEXT_PUBLIC_API_URL=http://127.0.0.1:3001/api - NEXT_PUBLIC_WS_URL=ws://127.0.0.1:3001 + image: itzcrazykns1337/perplexica-frontend:main depends_on: - perplexica-backend ports: @@ -40,3 +48,7 @@ services: networks: perplexica-network: + +volumes: + backend-dbstore: + uploads: diff --git a/docs/API/SEARCH.md b/docs/API/SEARCH.md new file mode 100644 index 0000000..9405bc5 --- /dev/null +++ b/docs/API/SEARCH.md @@ -0,0 +1,117 @@ +# Perplexica Search API Documentation + +## Overview + +Perplexica’s 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 you’re 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. diff --git a/docs/architecture/README.md b/docs/architecture/README.md index b1fcfcb..5732471 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -1,4 +1,4 @@ -## Perplexica's Architecture +# Perplexica's Architecture Perplexica's architecture consists of the following key components: diff --git a/docs/architecture/WORKING.md b/docs/architecture/WORKING.md index e39de7a..75b20fd 100644 --- a/docs/architecture/WORKING.md +++ b/docs/architecture/WORKING.md @@ -1,4 +1,4 @@ -## How does Perplexica work? +# How does Perplexica work? Curious about how Perplexica works? Don't worry, we'll cover it here. Before we begin, make sure you've read about the architecture of Perplexica to ensure you understand what it's made up of. Haven't read it? You can read it [here](https://github.com/ItzCrazyKns/Perplexica/tree/master/docs/architecture/README.md). @@ -10,10 +10,10 @@ We'll understand how Perplexica works by taking an example of a scenario where a 4. After the information is retrieved, it is based on keyword-based search. We then convert the information into embeddings and the query as well, then we perform a similarity search to find the most relevant sources to answer the query. 5. After all this is done, the sources are passed to the response generator. This chain takes all the chat history, the query, and the sources. It generates a response that is streamed to the UI. -### How are the answers cited? +## How are the answers cited? The LLMs are prompted to do so. We've prompted them so well that they cite the answers themselves, and using some UI magic, we display it to the user. -### Image and Video Search +## Image and Video Search Image and video searches are conducted in a similar manner. A query is always generated first, then we search the web for images and videos that match the query. These results are then returned to the user. diff --git a/docs/installation/NETWORKING.md b/docs/installation/NETWORKING.md index baad296..ae39e3f 100644 --- a/docs/installation/NETWORKING.md +++ b/docs/installation/NETWORKING.md @@ -10,27 +10,27 @@ This guide will show you how to make Perplexica available over a network. Follow 3. Stop and remove the existing Perplexica containers and images: -``` -docker compose down --rmi all -``` + ```bash + docker compose down --rmi all + ``` 4. Open the `docker-compose.yaml` file in a text editor like Notepad++ 5. Replace `127.0.0.1` with the IP address of the server Perplexica is running on in these two lines: -``` -args: - - NEXT_PUBLIC_API_URL=http://127.0.0.1:3001/api - - NEXT_PUBLIC_WS_URL=ws://127.0.0.1:3001 -``` + ```bash + args: + - NEXT_PUBLIC_API_URL=http://127.0.0.1:3001/api + - NEXT_PUBLIC_WS_URL=ws://127.0.0.1:3001 + ``` 6. Save and close the `docker-compose.yaml` file 7. Rebuild and restart the Perplexica container: -``` -docker compose up -d --build -``` + ```bash + docker compose up -d --build + ``` ## macOS @@ -38,37 +38,37 @@ docker compose up -d --build 2. Navigate to the directory with the `docker-compose.yaml` file: -``` -cd /path/to/docker-compose.yaml -``` + ```bash + cd /path/to/docker-compose.yaml + ``` 3. Stop and remove existing containers and images: -``` -docker compose down --rmi all -``` + ```bash + docker compose down --rmi all + ``` 4. Open `docker-compose.yaml` in a text editor like Sublime Text: -``` -nano docker-compose.yaml -``` + ```bash + nano docker-compose.yaml + ``` 5. Replace `127.0.0.1` with the server IP in these lines: -``` -args: - - NEXT_PUBLIC_API_URL=http://127.0.0.1:3001/api - - NEXT_PUBLIC_WS_URL=ws://127.0.0.1:3001 -``` + ```bash + args: + - NEXT_PUBLIC_API_URL=http://127.0.0.1:3001/api + - NEXT_PUBLIC_WS_URL=ws://127.0.0.1:3001 + ``` 6. Save and exit the editor 7. Rebuild and restart Perplexica: -``` -docker compose up -d --build -``` + ```bash + docker compose up -d --build + ``` ## Linux @@ -76,34 +76,34 @@ docker compose up -d --build 2. Navigate to the `docker-compose.yaml` directory: -``` -cd /path/to/docker-compose.yaml -``` + ```bash + cd /path/to/docker-compose.yaml + ``` 3. Stop and remove containers and images: -``` -docker compose down --rmi all -``` + ```bash + docker compose down --rmi all + ``` 4. Edit `docker-compose.yaml`: -``` -nano docker-compose.yaml -``` + ```bash + nano docker-compose.yaml + ``` 5. Replace `127.0.0.1` with the server IP: -``` -args: - - NEXT_PUBLIC_API_URL=http://127.0.0.1:3001/api - - NEXT_PUBLIC_WS_URL=ws://127.0.0.1:3001 -``` + ```bash + args: + - NEXT_PUBLIC_API_URL=http://127.0.0.1:3001/api + - NEXT_PUBLIC_WS_URL=ws://127.0.0.1:3001 + ``` 6. Save and exit the editor 7. Rebuild and restart Perplexica: -``` -docker compose up -d --build -``` + ```bash + docker compose up -d --build + ``` diff --git a/docs/installation/UPDATING.md b/docs/installation/UPDATING.md new file mode 100644 index 0000000..b41b05a --- /dev/null +++ b/docs/installation/UPDATING.md @@ -0,0 +1,40 @@ +# Update Perplexica to the latest version + +To update Perplexica to the latest version, follow these steps: + +## For Docker users + +1. Clone the latest version of Perplexica from GitHub: + + ```bash + git clone https://github.com/ItzCrazyKns/Perplexica.git + ``` + +2. Navigate to the Project Directory. + +3. Pull latest images from registry. + + ```bash + docker compose pull + ``` + +4. Update and Recreate containers. + + ```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 + +1. Clone the latest version of Perplexica from GitHub: + + ```bash + git clone https://github.com/ItzCrazyKns/Perplexica.git + ``` + +2. Navigate to the Project Directory +3. Execute `npm i` in both the `ui` folder and the root directory. +4. Once packages are updated, execute `npm run build` in both the `ui` folder and the root directory. +5. Finally, start both the frontend and the backend by running `npm run start` in both the `ui` folder and the root directory. diff --git a/drizzle.config.ts b/drizzle.config.ts new file mode 100644 index 0000000..9ac3ec5 --- /dev/null +++ b/drizzle.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from 'drizzle-kit'; + +export default defineConfig({ + dialect: 'sqlite', + schema: './src/db/schema.ts', + out: './drizzle', + dbCredentials: { + url: './data/db.sqlite', + }, +}); diff --git a/package.json b/package.json index 0308e93..3fce442 100644 --- a/package.json +++ b/package.json @@ -1,19 +1,26 @@ { "name": "perplexica-backend", - "version": "1.5.0", + "version": "1.10.0-rc2", "license": "MIT", "author": "ItzCrazyKns", "scripts": { - "start": "node dist/app.js", + "start": "npm run db:push && node dist/app.js", "build": "tsc", - "dev": "nodemon src/app.ts", + "dev": "nodemon --ignore uploads/ src/app.ts ", + "db:push": "drizzle-kit push sqlite", "format": "prettier . --check", "format:write": "prettier . --write" }, "devDependencies": { + "@types/better-sqlite3": "^7.6.10", "@types/cors": "^2.8.17", "@types/express": "^4.17.21", + "@types/html-to-text": "^9.0.4", + "@types/multer": "^1.4.12", + "@types/pdf-parse": "^1.1.4", "@types/readable-stream": "^4.0.11", + "@types/ws": "^8.5.12", + "drizzle-kit": "^0.22.7", "nodemon": "^3.1.0", "prettier": "^3.2.5", "ts-node": "^10.9.2", @@ -21,17 +28,26 @@ }, "dependencies": { "@iarna/toml": "^2.2.5", + "@langchain/anthropic": "^0.2.3", + "@langchain/community": "^0.2.16", "@langchain/openai": "^0.0.25", + "@langchain/google-genai": "^0.0.23", "@xenova/transformers": "^2.17.1", "axios": "^1.6.8", + "better-sqlite3": "^11.0.0", "compute-cosine-similarity": "^1.1.0", "compute-dot": "^1.1.0", "cors": "^2.8.5", "dotenv": "^16.4.5", + "drizzle-orm": "^0.31.2", "express": "^4.19.2", + "html-to-text": "^9.0.5", "langchain": "^0.1.30", + "mammoth": "^1.8.0", + "multer": "^1.4.5-lts.1", + "pdf-parse": "^1.1.1", "winston": "^3.13.0", - "ws": "^8.16.0", + "ws": "^8.17.1", "zod": "^3.22.4" } } diff --git a/sample.config.toml b/sample.config.toml index 8d35666..50ba95d 100644 --- a/sample.config.toml +++ b/sample.config.toml @@ -1,10 +1,13 @@ [GENERAL] PORT = 3001 # Port to run the server on SIMILARITY_MEASURE = "cosine" # "cosine" or "dot" +KEEP_ALIVE = "5m" # How long to keep Ollama models loaded into memory. (Instead of using -1 use "-1m") [API_KEYS] OPENAI = "" # OpenAI API key - sk-1234567890abcdef1234567890abcdef GROQ = "" # Groq API key - gsk_1234567890abcdef1234567890abcdef +ANTHROPIC = "" # Anthropic API key - sk-ant-1234567890abcdef1234567890abcdef +GEMINI = "" # Gemini API key - sk-1234567890abcdef1234567890abcdef [API_ENDPOINTS] SEARXNG = "http://localhost:32768" # SearxNG API URL diff --git a/searxng/settings.yml b/searxng/settings.yml index da973c1..54d27c4 100644 --- a/searxng/settings.yml +++ b/searxng/settings.yml @@ -1,2356 +1,17 @@ -general: - # Debug mode, only for development. Is overwritten by ${SEARXNG_DEBUG} - debug: false - # displayed name - instance_name: 'searxng' - # For example: https://example.com/privacy - privacypolicy_url: false - # use true to use your own donation page written in searx/info/en/donate.md - # use false to disable the donation link - donation_url: false - # mailto:contact@example.com - contact_url: false - # record stats - enable_metrics: true +use_default_settings: true -brand: - new_issue_url: https://github.com/searxng/searxng/issues/new - docs_url: https://docs.searxng.org/ - public_instances: https://searx.space - wiki_url: https://github.com/searxng/searxng/wiki - issue_url: https://github.com/searxng/searxng/issues - # custom: - # maintainer: "Jon Doe" - # # Custom entries in the footer: [title]: [link] - # links: - # Uptime: https://uptime.searxng.org/history/darmarit-org - # About: "https://searxng.org" +general: + instance_name: 'searxng' search: - # Filter results. 0: None, 1: Moderate, 2: Strict - safe_search: 0 - # Existing autocomplete backends: "dbpedia", "duckduckgo", "google", "yandex", "mwmbl", - # "seznam", "startpage", "stract", "swisscows", "qwant", "wikipedia" - leave blank to turn it off - # by default. autocomplete: 'google' - # minimun characters to type before autocompleter starts - autocomplete_min: 4 - # Default search language - leave blank to detect from browser information or - # use codes from 'languages.py' - default_lang: 'auto' - # max_page: 0 # if engine supports paging, 0 means unlimited numbers of pages - # Available languages - # languages: - # - all - # - en - # - en-US - # - de - # - it-IT - # - fr - # - fr-BE - # ban time in seconds after engine errors - ban_time_on_fail: 5 - # max ban time in seconds after engine errors - max_ban_time_on_fail: 120 - suspended_times: - # Engine suspension time after error (in seconds; set to 0 to disable) - # For error "Access denied" and "HTTP error [402, 403]" - SearxEngineAccessDenied: 86400 - # For error "CAPTCHA" - SearxEngineCaptcha: 86400 - # For error "Too many request" and "HTTP error 429" - SearxEngineTooManyRequests: 3600 - # Cloudflare CAPTCHA - cf_SearxEngineCaptcha: 1296000 - cf_SearxEngineAccessDenied: 86400 - # ReCAPTCHA - recaptcha_SearxEngineCaptcha: 604800 - - # remove format to deny access, use lower case. - # formats: [html, csv, json, rss] formats: - html - json server: - # Is overwritten by ${SEARXNG_PORT} and ${SEARXNG_BIND_ADDRESS} - port: 8888 - bind_address: '127.0.0.1' - # public URL of the instance, to ensure correct inbound links. Is overwritten - # by ${SEARXNG_URL}. - base_url: / # "http://example.com/location" - limiter: false # rate limit the number of request on the instance, block some bots - public_instance: false # enable features designed only for public instances - - # If your instance owns a /etc/searxng/settings.yml file, then set the following - # values there. - secret_key: 'a2fb23f1b02e6ee83875b09826990de0f6bd908b6638e8c10277d415f6ab852b' # Is overwritten by ${SEARXNG_SECRET} - # Proxying image results through searx - image_proxy: false - # 1.0 and 1.1 are supported - http_protocol_version: '1.0' - # POST queries are more secure as they don't show up in history but may cause - # problems when using Firefox containers - method: 'POST' - default_http_headers: - X-Content-Type-Options: nosniff - X-Download-Options: noopen - X-Robots-Tag: noindex, nofollow - Referrer-Policy: no-referrer - -redis: - # URL to connect redis database. Is overwritten by ${SEARXNG_REDIS_URL}. - # https://docs.searxng.org/admin/settings/settings_redis.html#settings-redis - url: false - -ui: - # Custom static path - leave it blank if you didn't change - static_path: '' - static_use_hash: false - # Custom templates path - leave it blank if you didn't change - templates_path: '' - # query_in_title: When true, the result page's titles contains the query - # it decreases the privacy, since the browser can records the page titles. - query_in_title: false - # infinite_scroll: When true, automatically loads the next page when scrolling to bottom of the current page. - infinite_scroll: false - # ui theme - default_theme: simple - # center the results ? - center_alignment: false - # URL prefix of the internet archive, don't forget trailing slash (if needed). - # cache_url: "https://webcache.googleusercontent.com/search?q=cache:" - # Default interface locale - leave blank to detect from browser information or - # use codes from the 'locales' config section - default_locale: '' - # Open result links in a new tab by default - # results_on_new_tab: false - theme_args: - # style of simple theme: auto, light, dark - simple_style: auto - # Perform search immediately if a category selected. - # Disable to select multiple categories at once and start the search manually. - search_on_category_select: true - # Hotkeys: default or vim - hotkeys: default - -# Lock arbitrary settings on the preferences page. To find the ID of the user -# setting you want to lock, check the ID of the form on the page "preferences". -# -# preferences: -# lock: -# - language -# - autocomplete -# - method -# - query_in_title - -# searx supports result proxification using an external service: -# https://github.com/asciimoo/morty uncomment below section if you have running -# morty proxy the key is base64 encoded (keep the !!binary notation) -# Note: since commit af77ec3, morty accepts a base64 encoded key. -# -# result_proxy: -# url: http://127.0.0.1:3000/ -# # the key is a base64 encoded string, the YAML !!binary prefix is optional -# key: !!binary "your_morty_proxy_key" -# # [true|false] enable the "proxy" button next to each result -# proxify_results: true - -# communication with search engines -# -outgoing: - # default timeout in seconds, can be override by engine - request_timeout: 3.0 - # the maximum timeout in seconds - # max_request_timeout: 10.0 - # suffix of searx_useragent, could contain information like an email address - # to the administrator - useragent_suffix: '' - # The maximum number of concurrent connections that may be established. - pool_connections: 100 - # Allow the connection pool to maintain keep-alive connections below this - # point. - pool_maxsize: 20 - # See https://www.python-httpx.org/http2/ - enable_http2: true - # uncomment below section if you want to use a custom server certificate - # see https://www.python-httpx.org/advanced/#changing-the-verification-defaults - # and https://www.python-httpx.org/compatibility/#ssl-configuration - # verify: ~/.mitmproxy/mitmproxy-ca-cert.cer - # - # uncomment below section if you want to use a proxyq see: SOCKS proxies - # https://2.python-requests.org/en/latest/user/advanced/#proxies - # are also supported: see - # https://2.python-requests.org/en/latest/user/advanced/#socks - # - # proxies: - # all://: - # - http://proxy1:8080 - # - http://proxy2:8080 - # - # using_tor_proxy: true - # - # Extra seconds to add in order to account for the time taken by the proxy - # - # extra_proxy_timeout: 10.0 - # - # uncomment below section only if you have more than one network interface - # which can be the source of outgoing search requests - # - # source_ips: - # - 1.1.1.1 - # - 1.1.1.2 - # - fe80::/126 - -# External plugin configuration, for more details see -# https://docs.searxng.org/dev/plugins.html -# -# plugins: -# - plugin1 -# - plugin2 -# - ... - -# Comment or un-comment plugin to activate / deactivate by default. -# -# enabled_plugins: -# # these plugins are enabled if nothing is configured .. -# - 'Hash plugin' -# - 'Self Information' -# - 'Tracker URL remover' -# - 'Ahmia blacklist' # activation depends on outgoing.using_tor_proxy -# # these plugins are disabled if nothing is configured .. -# - 'Hostname replace' # see hostname_replace configuration below -# - 'Open Access DOI rewrite' -# - 'Tor check plugin' -# # Read the docs before activate: auto-detection of the language could be -# # detrimental to users expectations / users can activate the plugin in the -# # preferences if they want. -# - 'Autodetect search language' - -# Configuration of the "Hostname replace" plugin: -# -# hostname_replace: -# '(.*\.)?youtube\.com$': 'invidious.example.com' -# '(.*\.)?youtu\.be$': 'invidious.example.com' -# '(.*\.)?youtube-noocookie\.com$': 'yotter.example.com' -# '(.*\.)?reddit\.com$': 'teddit.example.com' -# '(.*\.)?redd\.it$': 'teddit.example.com' -# '(www\.)?twitter\.com$': 'nitter.example.com' -# # to remove matching host names from result list, set value to false -# 'spam\.example\.com': false - -checker: - # disable checker when in debug mode - off_when_debug: true - - # use "scheduling: false" to disable scheduling - # scheduling: interval or int - - # to activate the scheduler: - # * uncomment "scheduling" section - # * add "cache2 = name=searxngcache,items=2000,blocks=2000,blocksize=4096,bitmap=1" - # to your uwsgi.ini - - # scheduling: - # start_after: [300, 1800] # delay to start the first run of the checker - # every: [86400, 90000] # how often the checker runs - - # additional tests: only for the YAML anchors (see the engines section) - # - additional_tests: - rosebud: &test_rosebud - matrix: - query: rosebud - lang: en - result_container: - - not_empty - - ['one_title_contains', 'citizen kane'] - test: - - unique_results - - android: &test_android - matrix: - query: ['android'] - lang: ['en', 'de', 'fr', 'zh-CN'] - result_container: - - not_empty - - ['one_title_contains', 'google'] - test: - - unique_results - - # tests: only for the YAML anchors (see the engines section) - tests: - infobox: &tests_infobox - infobox: - matrix: - query: ['linux', 'new york', 'bbc'] - result_container: - - has_infobox - -categories_as_tabs: - general: - images: - videos: - news: - map: - music: - it: - science: - files: - social media: engines: - - name: 9gag - engine: 9gag - shortcut: 9g - disabled: true - - - name: annas archive - engine: annas_archive - disabled: true - shortcut: aa - - # - name: annas articles - # engine: annas_archive - # shortcut: aaa - # # https://docs.searxng.org/dev/engines/online/annas_archive.html - # aa_content: 'journal_article' # book_any .. magazine, standards_document - # aa_ext: 'pdf' # pdf, epub, .. - # aa_sort: 'newest' # newest, oldest, largest, smallest - - - name: apk mirror - engine: apkmirror - timeout: 4.0 - shortcut: apkm - disabled: true - - - name: apple app store - engine: apple_app_store - shortcut: aps - disabled: true - - # Requires Tor - - name: ahmia - engine: ahmia - categories: onions - enable_http: true - shortcut: ah - - - name: anaconda - engine: xpath - paging: true - first_page_num: 0 - search_url: https://anaconda.org/search?q={query}&page={pageno} - results_xpath: //tbody/tr - url_xpath: ./td/h5/a[last()]/@href - title_xpath: ./td/h5 - content_xpath: ./td[h5]/text() - categories: it - timeout: 6.0 - shortcut: conda - disabled: true - - - name: arch linux wiki - engine: archlinux - shortcut: al - - - name: artic - engine: artic - shortcut: arc - timeout: 4.0 - - - name: arxiv - engine: arxiv - shortcut: arx - timeout: 4.0 - - - name: ask - engine: ask - shortcut: ask - disabled: true - - # tmp suspended: dh key too small - # - name: base - # engine: base - # shortcut: bs - - - name: bandcamp - engine: bandcamp - shortcut: bc - categories: music - - - name: wikipedia - engine: wikipedia - shortcut: wp - # add "list" to the array to get results in the results list - display_type: ['infobox'] - base_url: 'https://{language}.wikipedia.org/' - categories: [general] - - - name: bilibili - engine: bilibili - shortcut: bil - disabled: true - - - name: bing - engine: bing - shortcut: bi - disabled: true - - - name: bing images - engine: bing_images - shortcut: bii - - - name: bing news - engine: bing_news - shortcut: bin - - - name: bing videos - engine: bing_videos - shortcut: biv - - - name: bitbucket - engine: xpath - paging: true - search_url: https://bitbucket.org/repo/all/{pageno}?name={query} - url_xpath: //article[@class="repo-summary"]//a[@class="repo-link"]/@href - title_xpath: //article[@class="repo-summary"]//a[@class="repo-link"] - content_xpath: //article[@class="repo-summary"]/p - categories: [it, repos] - timeout: 4.0 - disabled: true - shortcut: bb - about: - website: https://bitbucket.org/ - wikidata_id: Q2493781 - official_api_documentation: https://developer.atlassian.com/bitbucket - use_official_api: false - require_api_key: false - results: HTML - - - name: bpb - engine: bpb - shortcut: bpb - disabled: true - - - name: btdigg - engine: btdigg - shortcut: bt - disabled: true - - - name: ccc-tv - engine: xpath - paging: false - search_url: https://media.ccc.de/search/?q={query} - url_xpath: //div[@class="caption"]/h3/a/@href - title_xpath: //div[@class="caption"]/h3/a/text() - content_xpath: //div[@class="caption"]/h4/@title - categories: videos - disabled: true - shortcut: c3tv - about: - website: https://media.ccc.de/ - wikidata_id: Q80729951 - official_api_documentation: https://github.com/voc/voctoweb - use_official_api: false - require_api_key: false - results: HTML - # We don't set language: de here because media.ccc.de is not just - # for a German audience. It contains many English videos and many - # German videos have English subtitles. - - - name: openverse - engine: openverse - categories: images - shortcut: opv - - - name: chefkoch - engine: chefkoch - shortcut: chef - # to show premium or plus results too: - # skip_premium: false - - # - name: core.ac.uk - # engine: core - # categories: science - # shortcut: cor - # # get your API key from: https://core.ac.uk/api-keys/register/ - # api_key: 'unset' - - - name: crossref - engine: crossref - shortcut: cr - timeout: 30 - disabled: true - - - name: crowdview - engine: json_engine - shortcut: cv - categories: general - paging: false - search_url: https://crowdview-next-js.onrender.com/api/search-v3?query={query} - results_query: results - url_query: link - title_query: title - content_query: snippet - disabled: true - about: - website: https://crowdview.ai/ - - - name: yep - engine: yep - shortcut: yep - categories: general - search_type: web - disabled: true - - - name: yep images - engine: yep - shortcut: yepi - categories: images - search_type: images - disabled: true - - - name: yep news - engine: yep - shortcut: yepn - categories: news - search_type: news - disabled: true - - - name: curlie - engine: xpath - shortcut: cl - categories: general - disabled: true - paging: true - lang_all: '' - search_url: https://curlie.org/search?q={query}&lang={lang}&start={pageno}&stime=92452189 - page_size: 20 - results_xpath: //div[@id="site-list-content"]/div[@class="site-item"] - url_xpath: ./div[@class="title-and-desc"]/a/@href - title_xpath: ./div[@class="title-and-desc"]/a/div - content_xpath: ./div[@class="title-and-desc"]/div[@class="site-descr"] - about: - website: https://curlie.org/ - wikidata_id: Q60715723 - use_official_api: false - require_api_key: false - results: HTML - - - name: currency - engine: currency_convert - categories: general - shortcut: cc - - - name: bahnhof - engine: json_engine - search_url: https://www.bahnhof.de/api/stations/search/{query} - url_prefix: https://www.bahnhof.de/ - url_query: slug - title_query: name - content_query: state - shortcut: bf - disabled: true - about: - website: https://www.bahn.de - wikidata_id: Q22811603 - use_official_api: false - require_api_key: false - results: JSON - language: de - - - name: deezer - engine: deezer - shortcut: dz - disabled: true - - - name: destatis - engine: destatis - shortcut: destat - disabled: true - - - name: deviantart - engine: deviantart - shortcut: da - timeout: 3.0 - - - name: ddg definitions - engine: duckduckgo_definitions - shortcut: ddd - weight: 2 - disabled: true - tests: *tests_infobox - - # cloudflare protected - # - name: digbt - # engine: digbt - # shortcut: dbt - # timeout: 6.0 - # disabled: true - - - name: docker hub - engine: docker_hub - shortcut: dh - categories: [it, packages] - - - name: erowid - engine: xpath - paging: true - first_page_num: 0 - page_size: 30 - search_url: https://www.erowid.org/search.php?q={query}&s={pageno} - url_xpath: //dl[@class="results-list"]/dt[@class="result-title"]/a/@href - title_xpath: //dl[@class="results-list"]/dt[@class="result-title"]/a/text() - content_xpath: //dl[@class="results-list"]/dd[@class="result-details"] - categories: [] - shortcut: ew - disabled: true - about: - website: https://www.erowid.org/ - wikidata_id: Q1430691 - official_api_documentation: - use_official_api: false - require_api_key: false - results: HTML - - # - name: elasticsearch - # shortcut: es - # engine: elasticsearch - # base_url: http://localhost:9200 - # username: elastic - # password: changeme - # index: my-index - # # available options: match, simple_query_string, term, terms, custom - # query_type: match - # # if query_type is set to custom, provide your query here - # #custom_query_json: {"query":{"match_all": {}}} - # #show_metadata: false - # disabled: true - - - name: wikidata - engine: wikidata - shortcut: wd - timeout: 3.0 - weight: 2 - # add "list" to the array to get results in the results list - display_type: ['infobox'] - tests: *tests_infobox - categories: [general] - - - name: duckduckgo - engine: duckduckgo - shortcut: ddg - - - name: duckduckgo images - engine: duckduckgo_extra - categories: [images, web] - ddg_category: images - shortcut: ddi - disabled: true - - - name: duckduckgo videos - engine: duckduckgo_extra - categories: [videos, web] - ddg_category: videos - shortcut: ddv - disabled: true - - - name: duckduckgo news - engine: duckduckgo_extra - categories: [news, web] - ddg_category: news - shortcut: ddn - disabled: true - - - name: duckduckgo weather - engine: duckduckgo_weather - shortcut: ddw - disabled: true - - - name: apple maps - engine: apple_maps - shortcut: apm - disabled: true - timeout: 5.0 - - - name: emojipedia - engine: emojipedia - timeout: 4.0 - shortcut: em - disabled: true - - - name: tineye - engine: tineye - shortcut: tin - timeout: 9.0 - disabled: true - - - name: etymonline - engine: xpath - paging: true - search_url: https://etymonline.com/search?page={pageno}&q={query} - url_xpath: //a[contains(@class, "word__name--")]/@href - title_xpath: //a[contains(@class, "word__name--")] - content_xpath: //section[contains(@class, "word__defination")] - first_page_num: 1 - shortcut: et - categories: [dictionaries] - about: - website: https://www.etymonline.com/ - wikidata_id: Q1188617 - official_api_documentation: - use_official_api: false - require_api_key: false - results: HTML - - # - name: ebay - # engine: ebay - # shortcut: eb - # base_url: 'https://www.ebay.com' - # disabled: true - # timeout: 5 - - - name: 1x - engine: www1x - shortcut: 1x - timeout: 3.0 - disabled: true - - - name: fdroid - engine: fdroid - shortcut: fd - disabled: true - - - name: flickr - categories: images - shortcut: fl - # You can use the engine using the official stable API, but you need an API - # key, see: https://www.flickr.com/services/apps/create/ - # engine: flickr - # api_key: 'apikey' # required! - # Or you can use the html non-stable engine, activated by default - engine: flickr_noapi - - - name: free software directory - engine: mediawiki - shortcut: fsd - categories: [it, software wikis] - base_url: https://directory.fsf.org/ - search_type: title - timeout: 5.0 - disabled: true - about: - website: https://directory.fsf.org/ - wikidata_id: Q2470288 - - # - name: freesound - # engine: freesound - # shortcut: fnd - # disabled: true - # timeout: 15.0 - # API key required, see: https://freesound.org/docs/api/overview.html - # api_key: MyAPIkey - - - name: frinkiac - engine: frinkiac - shortcut: frk - disabled: true - - - name: fyyd - engine: fyyd - shortcut: fy - timeout: 8.0 - disabled: true - - - name: genius - engine: genius - shortcut: gen - - - name: gentoo - engine: gentoo - shortcut: ge - timeout: 10.0 - - - name: gitlab - engine: json_engine - paging: true - search_url: https://gitlab.com/api/v4/projects?search={query}&page={pageno} - url_query: web_url - title_query: name_with_namespace - content_query: description - page_size: 20 - categories: [it, repos] - shortcut: gl - timeout: 10.0 - disabled: true - about: - website: https://about.gitlab.com/ - wikidata_id: Q16639197 - official_api_documentation: https://docs.gitlab.com/ee/api/ - use_official_api: false - require_api_key: false - results: JSON - - - name: github - engine: github - shortcut: gh - - # This a Gitea service. If you would like to use a different instance, - # change codeberg.org to URL of the desired Gitea host. Or you can create a - # new engine by copying this and changing the name, shortcut and search_url. - - - name: codeberg - engine: json_engine - search_url: https://codeberg.org/api/v1/repos/search?q={query}&limit=10 - url_query: html_url - title_query: name - content_query: description - categories: [it, repos] - shortcut: cb - disabled: true - about: - website: https://codeberg.org/ - wikidata_id: - official_api_documentation: https://try.gitea.io/api/swagger - use_official_api: false - require_api_key: false - results: JSON - - - name: goodreads - engine: goodreads - shortcut: good - timeout: 4.0 - disabled: true - - - name: google - engine: google - shortcut: go - # additional_tests: - # android: *test_android - - - name: google images - engine: google_images - shortcut: goi - # additional_tests: - # android: *test_android - # dali: - # matrix: - # query: ['Dali Christ'] - # lang: ['en', 'de', 'fr', 'zh-CN'] - # result_container: - # - ['one_title_contains', 'Salvador'] - - - name: google news - engine: google_news - shortcut: gon - # additional_tests: - # android: *test_android - - - name: google videos - engine: google_videos - shortcut: gov - # additional_tests: - # android: *test_android - - - name: google scholar - engine: google_scholar - shortcut: gos - - - name: google play apps - engine: google_play - categories: [files, apps] - shortcut: gpa - play_categ: apps - disabled: true - - - name: google play movies - engine: google_play - categories: videos - shortcut: gpm - play_categ: movies - disabled: true - - - name: material icons - engine: material_icons - categories: images - shortcut: mi - disabled: true - - - name: gpodder - engine: json_engine - shortcut: gpod - timeout: 4.0 - paging: false - search_url: https://gpodder.net/search.json?q={query} - url_query: url - title_query: title - content_query: description - page_size: 19 - categories: music - disabled: true - about: - website: https://gpodder.net - wikidata_id: Q3093354 - official_api_documentation: https://gpoddernet.readthedocs.io/en/latest/api/ - use_official_api: false - requires_api_key: false - results: JSON - - - name: habrahabr - engine: xpath - paging: true - search_url: https://habr.com/en/search/page{pageno}/?q={query} - results_xpath: //article[contains(@class, "tm-articles-list__item")] - url_xpath: .//a[@class="tm-title__link"]/@href - title_xpath: .//a[@class="tm-title__link"] - content_xpath: .//div[contains(@class, "article-formatted-body")] - categories: it - timeout: 4.0 - disabled: true - shortcut: habr - about: - website: https://habr.com/ - wikidata_id: Q4494434 - official_api_documentation: https://habr.com/en/docs/help/api/ - use_official_api: false - require_api_key: false - results: HTML - - - name: hackernews - engine: hackernews - shortcut: hn - disabled: true - - - name: hoogle - engine: xpath - paging: true - search_url: https://hoogle.haskell.org/?hoogle={query}&start={pageno} - results_xpath: '//div[@class="result"]' - title_xpath: './/div[@class="ans"]//a' - url_xpath: './/div[@class="ans"]//a/@href' - content_xpath: './/div[@class="from"]' - page_size: 20 - categories: [it, packages] - shortcut: ho - about: - website: https://hoogle.haskell.org/ - wikidata_id: Q34010 - official_api_documentation: https://hackage.haskell.org/api - use_official_api: false - require_api_key: false - results: JSON - - - name: imdb - engine: imdb - shortcut: imdb - timeout: 6.0 - disabled: true - - - name: imgur - engine: imgur - shortcut: img - disabled: true - - - name: ina - engine: ina - shortcut: in - timeout: 6.0 - disabled: true - - - name: invidious - engine: invidious - # Instanes will be selected randomly, see https://api.invidious.io/ for - # instances that are stable (good uptime) and close to you. - base_url: - - https://invidious.io.lol - - https://invidious.fdn.fr - - https://yt.artemislena.eu - - https://invidious.tiekoetter.com - - https://invidious.flokinet.to - - https://vid.puffyan.us - - https://invidious.privacydev.net - - https://inv.tux.pizza - shortcut: iv - timeout: 3.0 - disabled: true - - - name: jisho - engine: jisho - shortcut: js - timeout: 3.0 - disabled: true - - - name: kickass - engine: kickass - base_url: - - https://kickasstorrents.to - - https://kickasstorrents.cr - - https://kickasstorrent.cr - - https://kickass.sx - - https://kat.am - shortcut: kc - timeout: 4.0 - - - name: lemmy communities - engine: lemmy - lemmy_type: Communities - shortcut: leco - - - name: lemmy users - engine: lemmy - network: lemmy communities - lemmy_type: Users - shortcut: leus - - - name: lemmy posts - engine: lemmy - network: lemmy communities - lemmy_type: Posts - shortcut: lepo - - - name: lemmy comments - engine: lemmy - network: lemmy communities - lemmy_type: Comments - shortcut: lecom - - - name: library genesis - engine: xpath - # search_url: https://libgen.is/search.php?req={query} - search_url: https://libgen.rs/search.php?req={query} - url_xpath: //a[contains(@href,"book/index.php?md5")]/@href - title_xpath: //a[contains(@href,"book/")]/text()[1] - content_xpath: //td/a[1][contains(@href,"=author")]/text() - categories: files - timeout: 7.0 - disabled: true - shortcut: lg - about: - website: https://libgen.fun/ - wikidata_id: Q22017206 - official_api_documentation: - use_official_api: false - require_api_key: false - results: HTML - - - name: z-library - engine: zlibrary - shortcut: zlib - categories: files - timeout: 7.0 - - - name: library of congress - engine: loc - shortcut: loc - categories: images - - - name: lingva - engine: lingva - shortcut: lv - # set lingva instance in url, by default it will use the official instance - # url: https://lingva.thedaviddelta.com - - - name: lobste.rs - engine: xpath - search_url: https://lobste.rs/search?utf8=%E2%9C%93&q={query}&what=stories&order=relevance - results_xpath: //li[contains(@class, "story")] - url_xpath: .//a[@class="u-url"]/@href - title_xpath: .//a[@class="u-url"] - content_xpath: .//a[@class="domain"] - categories: it - shortcut: lo - timeout: 5.0 - disabled: true - about: - website: https://lobste.rs/ - wikidata_id: Q60762874 - official_api_documentation: - use_official_api: false - require_api_key: false - results: HTML - - - name: mastodon users - engine: mastodon - mastodon_type: accounts - base_url: https://mastodon.social - shortcut: mau - - - name: mastodon hashtags - engine: mastodon - mastodon_type: hashtags - base_url: https://mastodon.social - shortcut: mah - - # - name: matrixrooms - # engine: mrs - # # https://docs.searxng.org/dev/engines/online/mrs.html - # # base_url: https://mrs-api-host - # shortcut: mtrx - # disabled: true - - - name: mdn - shortcut: mdn - engine: json_engine - categories: [it] - paging: true - search_url: https://developer.mozilla.org/api/v1/search?q={query}&page={pageno} - results_query: documents - url_query: mdn_url - url_prefix: https://developer.mozilla.org - title_query: title - content_query: summary - about: - website: https://developer.mozilla.org - wikidata_id: Q3273508 - official_api_documentation: null - use_official_api: false - require_api_key: false - results: JSON - - - name: metacpan - engine: metacpan - shortcut: cpan - disabled: true - number_of_results: 20 - - # - name: meilisearch - # engine: meilisearch - # shortcut: mes - # enable_http: true - # base_url: http://localhost:7700 - # index: my-index - - - name: mixcloud - engine: mixcloud - shortcut: mc - - # MongoDB engine - # Required dependency: pymongo - # - name: mymongo - # engine: mongodb - # shortcut: md - # exact_match_only: false - # host: '127.0.0.1' - # port: 27017 - # enable_http: true - # results_per_page: 20 - # database: 'business' - # collection: 'reviews' # name of the db collection - # key: 'name' # key in the collection to search for - - - name: mozhi - engine: mozhi - base_url: - - https://mozhi.aryak.me - - https://translate.bus-hit.me - - https://nyc1.mz.ggtyler.dev - # mozhi_engine: google - see https://mozhi.aryak.me for supported engines - timeout: 4.0 - shortcut: mz - disabled: true - - - name: mwmbl - engine: mwmbl - # api_url: https://api.mwmbl.org - shortcut: mwm - disabled: true - - - name: npm - engine: json_engine - paging: true - first_page_num: 0 - search_url: https://api.npms.io/v2/search?q={query}&size=25&from={pageno} - results_query: results - url_query: package/links/npm - title_query: package/name - content_query: package/description - page_size: 25 - categories: [it, packages] - disabled: true - timeout: 5.0 - shortcut: npm - about: - website: https://npms.io/ - wikidata_id: Q7067518 - official_api_documentation: https://api-docs.npms.io/ - use_official_api: false - require_api_key: false - results: JSON - - - name: nyaa - engine: nyaa - shortcut: nt - disabled: true - - - name: mankier - engine: json_engine - search_url: https://www.mankier.com/api/v2/mans/?q={query} - results_query: results - url_query: url - title_query: name - content_query: description - categories: it - shortcut: man - about: - website: https://www.mankier.com/ - official_api_documentation: https://www.mankier.com/api - use_official_api: true - require_api_key: false - results: JSON - - - name: odysee - engine: odysee - shortcut: od - disabled: true - - - name: openairedatasets - engine: json_engine - paging: true - search_url: https://api.openaire.eu/search/datasets?format=json&page={pageno}&size=10&title={query} - results_query: response/results/result - url_query: metadata/oaf:entity/oaf:result/children/instance/webresource/url/$ - title_query: metadata/oaf:entity/oaf:result/title/$ - content_query: metadata/oaf:entity/oaf:result/description/$ - content_html_to_text: true - categories: 'science' - shortcut: oad - timeout: 5.0 - about: - website: https://www.openaire.eu/ - wikidata_id: Q25106053 - official_api_documentation: https://api.openaire.eu/ - use_official_api: false - require_api_key: false - results: JSON - - - name: openairepublications - engine: json_engine - paging: true - search_url: https://api.openaire.eu/search/publications?format=json&page={pageno}&size=10&title={query} - results_query: response/results/result - url_query: metadata/oaf:entity/oaf:result/children/instance/webresource/url/$ - title_query: metadata/oaf:entity/oaf:result/title/$ - content_query: metadata/oaf:entity/oaf:result/description/$ - content_html_to_text: true - categories: science - shortcut: oap - timeout: 5.0 - about: - website: https://www.openaire.eu/ - wikidata_id: Q25106053 - official_api_documentation: https://api.openaire.eu/ - use_official_api: false - require_api_key: false - results: JSON - - # - name: opensemanticsearch - # engine: opensemantic - # shortcut: oss - # base_url: 'http://localhost:8983/solr/opensemanticsearch/' - - - name: openstreetmap - engine: openstreetmap - shortcut: osm - - - name: openrepos - engine: xpath - paging: true - search_url: https://openrepos.net/search/node/{query}?page={pageno} - url_xpath: //li[@class="search-result"]//h3[@class="title"]/a/@href - title_xpath: //li[@class="search-result"]//h3[@class="title"]/a - content_xpath: //li[@class="search-result"]//div[@class="search-snippet-info"]//p[@class="search-snippet"] - categories: files - timeout: 4.0 - disabled: true - shortcut: or - about: - website: https://openrepos.net/ - wikidata_id: - official_api_documentation: - use_official_api: false - require_api_key: false - results: HTML - - - name: packagist - engine: json_engine - paging: true - search_url: https://packagist.org/search.json?q={query}&page={pageno} - results_query: results - url_query: url - title_query: name - content_query: description - categories: [it, packages] - disabled: true - timeout: 5.0 - shortcut: pack - about: - website: https://packagist.org - wikidata_id: Q108311377 - official_api_documentation: https://packagist.org/apidoc - use_official_api: true - require_api_key: false - results: JSON - - - name: pdbe - engine: pdbe - shortcut: pdb - # Hide obsolete PDB entries. Default is not to hide obsolete structures - # hide_obsolete: false - - - name: photon - engine: photon - shortcut: ph - - - name: pinterest - engine: pinterest - shortcut: pin - - - name: piped - engine: piped - shortcut: ppd - categories: videos - piped_filter: videos - timeout: 3.0 - - # URL to use as link and for embeds - frontend_url: https://srv.piped.video - # Instance will be selected randomly, for more see https://piped-instances.kavin.rocks/ - backend_url: - - https://pipedapi.kavin.rocks - - https://pipedapi-libre.kavin.rocks - - https://pipedapi.adminforge.de - - - name: piped.music - engine: piped - network: piped - shortcut: ppdm - categories: music - piped_filter: music_songs - timeout: 3.0 - - - name: piratebay - engine: piratebay - shortcut: tpb - # You may need to change this URL to a proxy if piratebay is blocked in your - # country - url: https://thepiratebay.org/ - timeout: 3.0 - - - name: podcastindex - engine: podcastindex - shortcut: podcast - - # Required dependency: psychopg2 - # - name: postgresql - # engine: postgresql - # database: postgres - # username: postgres - # password: postgres - # limit: 10 - # query_str: 'SELECT * from my_table WHERE my_column = %(query)s' - # shortcut : psql - - - name: presearch - engine: presearch - search_type: search - categories: [general, web] - shortcut: ps - timeout: 4.0 - disabled: true - - - name: presearch images - engine: presearch - network: presearch - search_type: images - categories: [images, web] - timeout: 4.0 - shortcut: psimg - disabled: true - - - name: presearch videos - engine: presearch - network: presearch - search_type: videos - categories: [general, web] - timeout: 4.0 - shortcut: psvid - disabled: true - - - name: presearch news - engine: presearch - network: presearch - search_type: news - categories: [news, web] - timeout: 4.0 - shortcut: psnews - disabled: true - - - name: pub.dev - engine: xpath - shortcut: pd - search_url: https://pub.dev/packages?q={query}&page={pageno} - paging: true - results_xpath: //div[contains(@class,"packages-item")] - url_xpath: ./div/h3/a/@href - title_xpath: ./div/h3/a - content_xpath: ./div/div/div[contains(@class,"packages-description")]/span - categories: [packages, it] - timeout: 3.0 - disabled: true - first_page_num: 1 - about: - website: https://pub.dev/ - official_api_documentation: https://pub.dev/help/api - use_official_api: false - require_api_key: false - results: HTML - - - name: pubmed - engine: pubmed - shortcut: pub - timeout: 3.0 - - - name: pypi - shortcut: pypi - engine: xpath - paging: true - search_url: https://pypi.org/search/?q={query}&page={pageno} - results_xpath: /html/body/main/div/div/div/form/div/ul/li/a[@class="package-snippet"] - url_xpath: ./@href - title_xpath: ./h3/span[@class="package-snippet__name"] - content_xpath: ./p - suggestion_xpath: /html/body/main/div/div/div/form/div/div[@class="callout-block"]/p/span/a[@class="link"] - first_page_num: 1 - categories: [it, packages] - about: - website: https://pypi.org - wikidata_id: Q2984686 - official_api_documentation: https://warehouse.readthedocs.io/api-reference/index.html - use_official_api: false - require_api_key: false - results: HTML - - - name: qwant - qwant_categ: web - engine: qwant - shortcut: qw - categories: [general, web] - additional_tests: - rosebud: *test_rosebud - - - name: qwant news - qwant_categ: news - engine: qwant - shortcut: qwn - categories: news - network: qwant - - - name: qwant images - qwant_categ: images - engine: qwant - shortcut: qwi - categories: [images, web] - network: qwant - - - name: qwant videos - qwant_categ: videos - engine: qwant - shortcut: qwv - categories: [videos, web] - network: qwant - - # - name: library - # engine: recoll - # shortcut: lib - # base_url: 'https://recoll.example.org/' - # search_dir: '' - # mount_prefix: /export - # dl_prefix: 'https://download.example.org' - # timeout: 30.0 - # categories: files - # disabled: true - - # - name: recoll library reference - # engine: recoll - # base_url: 'https://recoll.example.org/' - # search_dir: reference - # mount_prefix: /export - # dl_prefix: 'https://download.example.org' - # shortcut: libr - # timeout: 30.0 - # categories: files - # disabled: true - - - name: radio browser - engine: radio_browser - shortcut: rb - - - name: reddit - engine: reddit - shortcut: re - page_size: 25 - - - name: rottentomatoes - engine: rottentomatoes - shortcut: rt - disabled: true - - # Required dependency: redis - # - name: myredis - # shortcut : rds - # engine: redis_server - # exact_match_only: false - # host: '127.0.0.1' - # port: 6379 - # enable_http: true - # password: '' - # db: 0 - - # tmp suspended: bad certificate - # - name: scanr structures - # shortcut: scs - # engine: scanr_structures - # disabled: true - - - name: sepiasearch - engine: sepiasearch - shortcut: sep - - - name: soundcloud - engine: soundcloud - shortcut: sc - - - name: stackoverflow - engine: stackexchange - shortcut: st - api_site: 'stackoverflow' - categories: [it, q&a] - - - name: askubuntu - engine: stackexchange - shortcut: ubuntu - api_site: 'askubuntu' - categories: [it, q&a] - - - name: internetarchivescholar - engine: internet_archive_scholar - shortcut: ias - timeout: 5.0 - - - name: superuser - engine: stackexchange - shortcut: su - api_site: 'superuser' - categories: [it, q&a] - - - name: searchcode code - engine: searchcode_code - shortcut: scc - disabled: true - - # - name: searx - # engine: searx_engine - # shortcut: se - # instance_urls : - # - http://127.0.0.1:8888/ - # - ... - # disabled: true - - - name: semantic scholar - engine: semantic_scholar - disabled: true - shortcut: se - - # Spotify needs API credentials - # - name: spotify - # engine: spotify - # shortcut: stf - # api_client_id: ******* - # api_client_secret: ******* - - # - name: solr - # engine: solr - # shortcut: slr - # base_url: http://localhost:8983 - # collection: collection_name - # sort: '' # sorting: asc or desc - # field_list: '' # comma separated list of field names to display on the UI - # default_fields: '' # default field to query - # query_fields: '' # query fields - # enable_http: true - - # - name: springer nature - # engine: springer - # # get your API key from: https://dev.springernature.com/signup - # # working API key, for test & debug: "a69685087d07eca9f13db62f65b8f601" - # api_key: 'unset' - # shortcut: springer - # timeout: 15.0 - - - name: startpage - engine: startpage - shortcut: sp - timeout: 6.0 - disabled: true - additional_tests: - rosebud: *test_rosebud - - - name: tokyotoshokan - engine: tokyotoshokan - shortcut: tt - timeout: 6.0 - disabled: true - - - name: solidtorrents - engine: solidtorrents - shortcut: solid - timeout: 4.0 - base_url: - - https://solidtorrents.to - - https://bitsearch.to - - # For this demo of the sqlite engine download: - # https://liste.mediathekview.de/filmliste-v2.db.bz2 - # and unpack into searx/data/filmliste-v2.db - # Query to test: "!demo concert" - # - # - name: demo - # engine: sqlite - # shortcut: demo - # categories: general - # result_template: default.html - # database: searx/data/filmliste-v2.db - # query_str: >- - # SELECT title || ' (' || time(duration, 'unixepoch') || ')' AS title, - # COALESCE( NULLIF(url_video_hd,''), NULLIF(url_video_sd,''), url_video) AS url, - # description AS content - # FROM film - # WHERE title LIKE :wildcard OR description LIKE :wildcard - # ORDER BY duration DESC - - - name: tagesschau - engine: tagesschau - # when set to false, display URLs from Tagesschau, and not the actual source - # (e.g. NDR, WDR, SWR, HR, ...) - use_source_url: true - shortcut: ts - disabled: true - - - name: tmdb - engine: xpath - paging: true - categories: movies - search_url: https://www.themoviedb.org/search?page={pageno}&query={query} - results_xpath: //div[contains(@class,"movie") or contains(@class,"tv")]//div[contains(@class,"card")] - url_xpath: .//div[contains(@class,"poster")]/a/@href - thumbnail_xpath: .//img/@src - title_xpath: .//div[contains(@class,"title")]//h2 - content_xpath: .//div[contains(@class,"overview")] - shortcut: tm - disabled: true - - # Requires Tor - - name: torch - engine: xpath - paging: true - search_url: http://xmh57jrknzkhv6y3ls3ubitzfqnkrwxhopf5aygthi7d6rplyvk3noyd.onion/cgi-bin/omega/omega?P={query}&DEFAULTOP=and - results_xpath: //table//tr - url_xpath: ./td[2]/a - title_xpath: ./td[2]/b - content_xpath: ./td[2]/small - categories: onions - enable_http: true - shortcut: tch - - # torznab engine lets you query any torznab compatible indexer. Using this - # engine in combination with Jackett opens the possibility to query a lot of - # public and private indexers directly from SearXNG. More details at: - # https://docs.searxng.org/dev/engines/online/torznab.html - # - # - name: Torznab EZTV - # engine: torznab - # shortcut: eztv - # base_url: http://localhost:9117/api/v2.0/indexers/eztv/results/torznab - # enable_http: true # if using localhost - # api_key: xxxxxxxxxxxxxxx - # show_magnet_links: true - # show_torrent_files: false - # # https://github.com/Jackett/Jackett/wiki/Jackett-Categories - # torznab_categories: # optional - # - 2000 - # - 5000 - - # tmp suspended - too slow, too many errors - # - name: urbandictionary - # engine : xpath - # search_url : https://www.urbandictionary.com/define.php?term={query} - # url_xpath : //*[@class="word"]/@href - # title_xpath : //*[@class="def-header"] - # content_xpath: //*[@class="meaning"] - # shortcut: ud - - - name: unsplash - engine: unsplash - shortcut: us - - - name: yandex music - engine: yandex_music - shortcut: ydm - disabled: true - # https://yandex.com/support/music/access.html - inactive: true - - - name: yahoo - engine: yahoo - shortcut: yh - disabled: true - - - name: yahoo news - engine: yahoo_news - shortcut: yhn - - - name: youtube - shortcut: yt - # You can use the engine using the official stable API, but you need an API - # key See: https://console.developers.google.com/project - # - # engine: youtube_api - # api_key: 'apikey' # required! - # - # Or you can use the html non-stable engine, activated by default - engine: youtube_noapi - - - name: dailymotion - engine: dailymotion - shortcut: dm - - - name: vimeo - engine: vimeo - shortcut: vm - - - name: wiby - engine: json_engine - paging: true - search_url: https://wiby.me/json/?q={query}&p={pageno} - url_query: URL - title_query: Title - content_query: Snippet - categories: [general, web] - shortcut: wib - disabled: true - about: - website: https://wiby.me/ - - - name: alexandria - engine: json_engine - shortcut: alx - categories: general - paging: true - search_url: https://api.alexandria.org/?a=1&q={query}&p={pageno} - results_query: results - title_query: title - url_query: url - content_query: snippet - timeout: 1.5 - disabled: true - about: - website: https://alexandria.org/ - official_api_documentation: https://github.com/alexandria-org/alexandria-api/raw/master/README.md - use_official_api: true - require_api_key: false - results: JSON - - - name: wikibooks - engine: mediawiki - weight: 0.5 - shortcut: wb - categories: [general, wikimedia] - base_url: 'https://{language}.wikibooks.org/' - search_type: text - disabled: true - about: - website: https://www.wikibooks.org/ - wikidata_id: Q367 - - - name: wikinews - engine: mediawiki - shortcut: wn - categories: [news, wikimedia] - base_url: 'https://{language}.wikinews.org/' - search_type: text - srsort: create_timestamp_desc - about: - website: https://www.wikinews.org/ - wikidata_id: Q964 - - - name: wikiquote - engine: mediawiki - weight: 0.5 - shortcut: wq - categories: [general, wikimedia] - base_url: 'https://{language}.wikiquote.org/' - search_type: text - disabled: true - additional_tests: - rosebud: *test_rosebud - about: - website: https://www.wikiquote.org/ - wikidata_id: Q369 - - - name: wikisource - engine: mediawiki - weight: 0.5 - shortcut: ws - categories: [general, wikimedia] - base_url: 'https://{language}.wikisource.org/' - search_type: text - disabled: true - about: - website: https://www.wikisource.org/ - wikidata_id: Q263 - - - name: wikispecies - engine: mediawiki - shortcut: wsp - categories: [general, science, wikimedia] - base_url: 'https://species.wikimedia.org/' - search_type: text - disabled: true - about: - website: https://species.wikimedia.org/ - wikidata_id: Q13679 - - - name: wiktionary - engine: mediawiki - shortcut: wt - categories: [dictionaries, wikimedia] - base_url: 'https://{language}.wiktionary.org/' - search_type: text - about: - website: https://www.wiktionary.org/ - wikidata_id: Q151 - - - name: wikiversity - engine: mediawiki - weight: 0.5 - shortcut: wv - categories: [general, wikimedia] - base_url: 'https://{language}.wikiversity.org/' - search_type: text - disabled: true - about: - website: https://www.wikiversity.org/ - wikidata_id: Q370 - - - name: wikivoyage - engine: mediawiki - weight: 0.5 - shortcut: wy - categories: [general, wikimedia] - base_url: 'https://{language}.wikivoyage.org/' - search_type: text - disabled: true - about: - website: https://www.wikivoyage.org/ - wikidata_id: Q373 - - - name: wikicommons.images - engine: wikicommons - shortcut: wc - categories: images - number_of_results: 10 - - name: wolframalpha - shortcut: wa - # You can use the engine using the official stable API, but you need an API - # key. See: https://products.wolframalpha.com/api/ - # - # engine: wolframalpha_api - # api_key: '' - # - # Or you can use the html non-stable engine, activated by default - engine: wolframalpha_noapi - timeout: 6.0 - categories: general disabled: false - - - name: dictzone - engine: dictzone - shortcut: dc - - - name: mymemory translated - engine: translated - shortcut: tl - timeout: 5.0 - # You can use without an API key, but you are limited to 1000 words/day - # See: https://mymemory.translated.net/doc/usagelimits.php - # api_key: '' - - # Required dependency: mysql-connector-python - # - name: mysql - # engine: mysql_server - # database: mydatabase - # username: user - # password: pass - # limit: 10 - # query_str: 'SELECT * from mytable WHERE fieldname=%(query)s' - # shortcut: mysql - - - name: 1337x - engine: 1337x - shortcut: 1337x - disabled: true - - - name: duden - engine: duden - shortcut: du - disabled: true - - - name: seznam - shortcut: szn - engine: seznam - disabled: true - - # - name: deepl - # engine: deepl - # shortcut: dpl - # # You can use the engine using the official stable API, but you need an API key - # # See: https://www.deepl.com/pro-api?cta=header-pro-api - # api_key: '' # required! - # timeout: 5.0 - # disabled: true - - - name: mojeek - shortcut: mjk - engine: xpath - paging: true - categories: [general, web] - search_url: https://www.mojeek.com/search?q={query}&s={pageno}&lang={lang}&lb={lang} - results_xpath: //ul[@class="results-standard"]/li/a[@class="ob"] - url_xpath: ./@href - title_xpath: ../h2/a - content_xpath: ..//p[@class="s"] - suggestion_xpath: //div[@class="top-info"]/p[@class="top-info spell"]/em/a - first_page_num: 0 - page_size: 10 - max_page: 100 - disabled: true - about: - website: https://www.mojeek.com/ - wikidata_id: Q60747299 - official_api_documentation: https://www.mojeek.com/services/api.html/ - use_official_api: false - require_api_key: false - results: HTML - - - name: moviepilot - engine: moviepilot - shortcut: mp - disabled: true - - - name: naver - shortcut: nvr - categories: [general, web] - engine: xpath - paging: true - search_url: https://search.naver.com/search.naver?where=webkr&sm=osp_hty&ie=UTF-8&query={query}&start={pageno} - url_xpath: //a[@class="link_tit"]/@href - title_xpath: //a[@class="link_tit"] - content_xpath: //a[@class="total_dsc"]/div - first_page_num: 1 - page_size: 10 - disabled: true - about: - website: https://www.naver.com/ - wikidata_id: Q485639 - official_api_documentation: https://developers.naver.com/docs/nmt/examples/ - use_official_api: false - require_api_key: false - results: HTML - language: ko - - - name: rubygems - shortcut: rbg - engine: xpath - paging: true - search_url: https://rubygems.org/search?page={pageno}&query={query} - results_xpath: /html/body/main/div/a[@class="gems__gem"] - url_xpath: ./@href - title_xpath: ./span/h2 - content_xpath: ./span/p - suggestion_xpath: /html/body/main/div/div[@class="search__suggestions"]/p/a - first_page_num: 1 - categories: [it, packages] - disabled: true - about: - website: https://rubygems.org/ - wikidata_id: Q1853420 - official_api_documentation: https://guides.rubygems.org/rubygems-org-api/ - use_official_api: false - require_api_key: false - results: HTML - - - name: peertube - engine: peertube - shortcut: ptb - paging: true - # alternatives see: https://instances.joinpeertube.org/instances - # base_url: https://tube.4aem.com - categories: videos - disabled: true - timeout: 6.0 - - - name: mediathekviewweb - engine: mediathekviewweb - shortcut: mvw - disabled: true - - - name: yacy - engine: yacy - categories: general - search_type: text - base_url: https://yacy.searchlab.eu - shortcut: ya - disabled: true - # required if you aren't using HTTPS for your local yacy instance - # https://docs.searxng.org/dev/engines/online/yacy.html - # enable_http: true - # timeout: 3.0 - # search_mode: 'global' - - - name: yacy images - engine: yacy - categories: images - search_type: image - base_url: https://yacy.searchlab.eu - shortcut: yai - disabled: true - - - name: rumble - engine: rumble - shortcut: ru - base_url: https://rumble.com/ - paging: true - categories: videos - disabled: true - - - name: livespace - engine: livespace - shortcut: ls - categories: videos - disabled: true - timeout: 5.0 - - - name: wordnik - engine: wordnik - shortcut: def - base_url: https://www.wordnik.com/ - categories: [dictionaries] - timeout: 5.0 - - - name: woxikon.de synonyme - engine: xpath - shortcut: woxi - categories: [dictionaries] - timeout: 5.0 - disabled: true - search_url: https://synonyme.woxikon.de/synonyme/{query}.php - url_xpath: //div[@class="upper-synonyms"]/a/@href - content_xpath: //div[@class="synonyms-list-group"] - title_xpath: //div[@class="upper-synonyms"]/a - no_result_for_http_status: [404] - about: - website: https://www.woxikon.de/ - wikidata_id: # No Wikidata ID - use_official_api: false - require_api_key: false - results: HTML - language: de - - - name: seekr news - engine: seekr - shortcut: senews - categories: news - seekr_category: news - disabled: true - - - name: seekr images - engine: seekr - network: seekr news - shortcut: seimg - categories: images - seekr_category: images - disabled: true - - - name: seekr videos - engine: seekr - network: seekr news - shortcut: sevid - categories: videos - seekr_category: videos - disabled: true - - - name: sjp.pwn - engine: sjp - shortcut: sjp - base_url: https://sjp.pwn.pl/ - timeout: 5.0 - disabled: true - - - name: stract - engine: stract - shortcut: str - disabled: true - - - name: svgrepo - engine: svgrepo - shortcut: svg - timeout: 10.0 - disabled: true - - - name: tootfinder - engine: tootfinder - shortcut: toot - - - name: wallhaven - engine: wallhaven - # api_key: abcdefghijklmnopqrstuvwxyz - shortcut: wh - - # wikimini: online encyclopedia for children - # The fulltext and title parameter is necessary for Wikimini because - # sometimes it will not show the results and redirect instead - - name: wikimini - engine: xpath - shortcut: wkmn - search_url: https://fr.wikimini.org/w/index.php?search={query}&title=Sp%C3%A9cial%3ASearch&fulltext=Search - url_xpath: //li/div[@class="mw-search-result-heading"]/a/@href - title_xpath: //li//div[@class="mw-search-result-heading"]/a - content_xpath: //li/div[@class="searchresult"] - categories: general - disabled: true - about: - website: https://wikimini.org/ - wikidata_id: Q3568032 - use_official_api: false - require_api_key: false - results: HTML - language: fr - - - name: wttr.in - engine: wttr - shortcut: wttr - timeout: 9.0 - - - name: yummly - engine: yummly - shortcut: yum - disabled: true - - - name: brave - engine: brave - shortcut: br - time_range_support: true - paging: true - categories: [general, web] - brave_category: search - # brave_spellcheck: true - - - name: brave.images - engine: brave - network: brave - shortcut: brimg - categories: [images, web] - brave_category: images - - - name: brave.videos - engine: brave - network: brave - shortcut: brvid - categories: [videos, web] - brave_category: videos - - - name: brave.news - engine: brave - network: brave - shortcut: brnews - categories: news - brave_category: news - - # - name: brave.goggles - # engine: brave - # network: brave - # shortcut: brgog - # time_range_support: true - # paging: true - # categories: [general, web] - # brave_category: goggles - # Goggles: # required! This should be a URL ending in .goggle - - - name: lib.rs - shortcut: lrs - engine: xpath - search_url: https://lib.rs/search?q={query} - results_xpath: /html/body/main/div/ol/li/a - url_xpath: ./@href - title_xpath: ./div[@class="h"]/h4 - content_xpath: ./div[@class="h"]/p - categories: [it, packages] - disabled: true - about: - website: https://lib.rs - wikidata_id: Q113486010 - use_official_api: false - require_api_key: false - results: HTML - - - name: sourcehut - shortcut: srht - engine: xpath - paging: true - search_url: https://sr.ht/projects?page={pageno}&search={query} - results_xpath: (//div[@class="event-list"])[1]/div[@class="event"] - url_xpath: ./h4/a[2]/@href - title_xpath: ./h4/a[2] - content_xpath: ./p - first_page_num: 1 - categories: [it, repos] - disabled: true - about: - website: https://sr.ht - wikidata_id: Q78514485 - official_api_documentation: https://man.sr.ht/ - use_official_api: false - require_api_key: false - results: HTML - - - name: goo - shortcut: goo - engine: xpath - paging: true - search_url: https://search.goo.ne.jp/web.jsp?MT={query}&FR={pageno}0 - url_xpath: //div[@class="result"]/p[@class='title fsL1']/a/@href - title_xpath: //div[@class="result"]/p[@class='title fsL1']/a - content_xpath: //p[contains(@class,'url fsM')]/following-sibling::p - first_page_num: 0 - categories: [general, web] - disabled: true - timeout: 4.0 - about: - website: https://search.goo.ne.jp - wikidata_id: Q249044 - use_official_api: false - require_api_key: false - results: HTML - language: ja - - - name: bt4g - engine: bt4g - shortcut: bt4g - - - name: pkg.go.dev - engine: xpath - shortcut: pgo - search_url: https://pkg.go.dev/search?limit=100&m=package&q={query} - results_xpath: /html/body/main/div[contains(@class,"SearchResults")]/div[not(@class)]/div[@class="SearchSnippet"] - url_xpath: ./div[@class="SearchSnippet-headerContainer"]/h2/a/@href - title_xpath: ./div[@class="SearchSnippet-headerContainer"]/h2/a - content_xpath: ./p[@class="SearchSnippet-synopsis"] - categories: [packages, it] - timeout: 3.0 - disabled: true - about: - website: https://pkg.go.dev/ - use_official_api: false - require_api_key: false - results: HTML - -# Doku engine lets you access to any Doku wiki instance: -# A public one or a privete/corporate one. -# - name: ubuntuwiki -# engine: doku -# shortcut: uw -# base_url: 'https://doc.ubuntu-fr.org' - -# Be careful when enabling this engine if you are -# running a public instance. Do not expose any sensitive -# information. You can restrict access by configuring a list -# of access tokens under tokens. -# - name: git grep -# engine: command -# command: ['git', 'grep', '{{QUERY}}'] -# shortcut: gg -# tokens: [] -# disabled: true -# delimiter: -# chars: ':' -# keys: ['filepath', 'code'] - -# Be careful when enabling this engine if you are -# running a public instance. Do not expose any sensitive -# information. You can restrict access by configuring a list -# of access tokens under tokens. -# - name: locate -# engine: command -# command: ['locate', '{{QUERY}}'] -# shortcut: loc -# tokens: [] -# disabled: true -# delimiter: -# chars: ' ' -# keys: ['line'] - -# Be careful when enabling this engine if you are -# running a public instance. Do not expose any sensitive -# information. You can restrict access by configuring a list -# of access tokens under tokens. -# - name: find -# engine: command -# command: ['find', '.', '-name', '{{QUERY}}'] -# query_type: path -# shortcut: fnd -# tokens: [] -# disabled: true -# delimiter: -# chars: ' ' -# keys: ['line'] - -# Be careful when enabling this engine if you are -# running a public instance. Do not expose any sensitive -# information. You can restrict access by configuring a list -# of access tokens under tokens. -# - name: pattern search in files -# engine: command -# command: ['fgrep', '{{QUERY}}'] -# shortcut: fgr -# tokens: [] -# disabled: true -# delimiter: -# chars: ' ' -# keys: ['line'] - -# Be careful when enabling this engine if you are -# running a public instance. Do not expose any sensitive -# information. You can restrict access by configuring a list -# of access tokens under tokens. -# - name: regex search in files -# engine: command -# command: ['grep', '{{QUERY}}'] -# shortcut: gr -# tokens: [] -# disabled: true -# delimiter: -# chars: ' ' -# keys: ['line'] - -doi_resolvers: - oadoi.org: 'https://oadoi.org/' - doi.org: 'https://doi.org/' - doai.io: 'https://dissem.in/' - sci-hub.se: 'https://sci-hub.se/' - sci-hub.st: 'https://sci-hub.st/' - sci-hub.ru: 'https://sci-hub.ru/' - -default_doi_resolver: 'oadoi.org' diff --git a/src/agents/academicSearchAgent.ts b/src/agents/academicSearchAgent.ts deleted file mode 100644 index 5c11307..0000000 --- a/src/agents/academicSearchAgent.ts +++ /dev/null @@ -1,265 +0,0 @@ -import { BaseMessage } from '@langchain/core/messages'; -import { - PromptTemplate, - ChatPromptTemplate, - MessagesPlaceholder, -} from '@langchain/core/prompts'; -import { - RunnableSequence, - RunnableMap, - RunnableLambda, -} from '@langchain/core/runnables'; -import { StringOutputParser } from '@langchain/core/output_parsers'; -import { Document } from '@langchain/core/documents'; -import { searchSearxng } from '../lib/searxng'; -import type { StreamEvent } from '@langchain/core/tracers/log_stream'; -import type { BaseChatModel } from '@langchain/core/language_models/chat_models'; -import type { Embeddings } from '@langchain/core/embeddings'; -import formatChatHistoryAsString from '../utils/formatHistory'; -import eventEmitter from 'events'; -import computeSimilarity from '../utils/computeSimilarity'; -import logger from '../utils/logger'; - -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. -If it is a writing task or a simple hi, hello rather than a question, you need to return \`not_needed\` as the response. - -Example: -1. Follow up question: How does stable diffusion work? -Rephrased: Stable diffusion working - -2. Follow up question: What is linear algebra? -Rephrased: Linear algebra - -3. Follow up question: What is the third law of thermodynamics? -Rephrased: Third law of thermodynamics - -Conversation: -{chat_history} - -Follow up question: {query} -Rephrased question: -`; - -const basicAcademicSearchResponsePrompt = ` - You are Perplexica, an AI model who is expert at searching the web and answering user's queries. You are set on focus mode 'Academic', this means you will be searching for academic papers and articles on the web. - - Generate a response that is informative and relevant to the user's query based on provided context (the context consits of search results containg a brief description of the content of that page). - You must use this context to answer the user's query in the best way possible. Use an unbaised and journalistic tone in your response. Do not repeat the text. - You must not tell the user to open any link or visit any website to get the answer. You must provide the answer in the response itself. If the user asks for links you can provide them. - Your responses should be medium to long in length be informative and relevant to the user's query. You can use markdowns to format your response. You should use bullet points to list the information. Make sure the answer is not short and is informative. - You have to cite the answer using [number] notation. You must cite the sentences with their relevent context number. You must cite each and every part of the answer so the user can know where the information is coming from. - Place these citations at the end of that particular sentence. You can cite the same sentence multiple times if it is relevant to the user's query like [number1][number2]. - However you do not need to cite it using the same number. You can use different numbers to cite the same sentence multiple times. The number refers to the number of the search result (passed in the context) used to generate that part of the answer. - - Aything inside the following \`context\` HTML block provided below is for your knowledge returned by the search engine and is not shared by the user. You have to answer question on the basis of it and cite the relevant information from it but you do not have to - talk about the context in your response. - - - {context} - - - If you think there's nothing relevant in the search results, you can say that 'Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?'. - Anything between the \`context\` is retrieved from a search engine and is not a part of the conversation with the user. Today's date is ${new Date().toISOString()} -`; - -const strParser = new StringOutputParser(); - -const handleStream = async ( - stream: AsyncGenerator, - emitter: eventEmitter, -) => { - for await (const event of stream) { - if ( - event.event === 'on_chain_end' && - event.name === 'FinalSourceRetriever' - ) { - emitter.emit( - 'data', - JSON.stringify({ type: 'sources', data: event.data.output }), - ); - } - if ( - event.event === 'on_chain_stream' && - event.name === 'FinalResponseGenerator' - ) { - emitter.emit( - 'data', - JSON.stringify({ type: 'response', data: event.data.chunk }), - ); - } - if ( - event.event === 'on_chain_end' && - event.name === 'FinalResponseGenerator' - ) { - emitter.emit('end'); - } - } -}; - -type BasicChainInput = { - chat_history: BaseMessage[]; - query: string; -}; - -const createBasicAcademicSearchRetrieverChain = (llm: BaseChatModel) => { - return RunnableSequence.from([ - PromptTemplate.fromTemplate(basicAcademicSearchRetrieverPrompt), - llm, - strParser, - RunnableLambda.from(async (input: string) => { - if (input === 'not_needed') { - return { query: '', docs: [] }; - } - - const res = await searchSearxng(input, { - language: 'en', - engines: [ - 'arxiv', - 'google scholar', - 'internetarchivescholar', - 'pubmed', - ], - }); - - const documents = res.results.map( - (result) => - new Document({ - pageContent: result.content, - metadata: { - title: result.title, - url: result.url, - ...(result.img_src && { img_src: result.img_src }), - }, - }), - ); - - return { query: input, docs: documents }; - }), - ]); -}; - -const createBasicAcademicSearchAnsweringChain = ( - llm: BaseChatModel, - embeddings: Embeddings, -) => { - const basicAcademicSearchRetrieverChain = - createBasicAcademicSearchRetrieverChain(llm); - - const processDocs = async (docs: Document[]) => { - return docs - .map((_, index) => `${index + 1}. ${docs[index].pageContent}`) - .join('\n'); - }; - - const rerankDocs = async ({ - query, - docs, - }: { - query: string; - docs: Document[]; - }) => { - if (docs.length === 0) { - return docs; - } - - const docsWithContent = docs.filter( - (doc) => doc.pageContent && doc.pageContent.length > 0, - ); - - const [docEmbeddings, queryEmbedding] = await Promise.all([ - embeddings.embedDocuments(docsWithContent.map((doc) => doc.pageContent)), - embeddings.embedQuery(query), - ]); - - const similarity = docEmbeddings.map((docEmbedding, i) => { - const sim = computeSimilarity(queryEmbedding, docEmbedding); - - return { - index: i, - similarity: sim, - }; - }); - - const sortedDocs = similarity - .sort((a, b) => b.similarity - a.similarity) - .slice(0, 15) - .map((sim) => docsWithContent[sim.index]); - - return sortedDocs; - }; - - return RunnableSequence.from([ - RunnableMap.from({ - query: (input: BasicChainInput) => input.query, - chat_history: (input: BasicChainInput) => input.chat_history, - context: RunnableSequence.from([ - (input) => ({ - query: input.query, - chat_history: formatChatHistoryAsString(input.chat_history), - }), - basicAcademicSearchRetrieverChain - .pipe(rerankDocs) - .withConfig({ - runName: 'FinalSourceRetriever', - }) - .pipe(processDocs), - ]), - }), - ChatPromptTemplate.fromMessages([ - ['system', basicAcademicSearchResponsePrompt], - new MessagesPlaceholder('chat_history'), - ['user', '{query}'], - ]), - llm, - strParser, - ]).withConfig({ - runName: 'FinalResponseGenerator', - }); -}; - -const basicAcademicSearch = ( - query: string, - history: BaseMessage[], - llm: BaseChatModel, - embeddings: Embeddings, -) => { - const emitter = new eventEmitter(); - - try { - const basicAcademicSearchAnsweringChain = - createBasicAcademicSearchAnsweringChain(llm, embeddings); - - const stream = basicAcademicSearchAnsweringChain.streamEvents( - { - chat_history: history, - query: query, - }, - { - version: 'v1', - }, - ); - - handleStream(stream, emitter); - } catch (err) { - emitter.emit( - 'error', - JSON.stringify({ data: 'An error has occurred please try again later' }), - ); - logger.error(`Error in academic search: ${err}`); - } - - return emitter; -}; - -const handleAcademicSearch = ( - message: string, - history: BaseMessage[], - llm: BaseChatModel, - embeddings: Embeddings, -) => { - const emitter = basicAcademicSearch(message, history, llm, embeddings); - return emitter; -}; - -export default handleAcademicSearch; diff --git a/src/agents/redditSearchAgent.ts b/src/agents/redditSearchAgent.ts deleted file mode 100644 index 34e9ec2..0000000 --- a/src/agents/redditSearchAgent.ts +++ /dev/null @@ -1,260 +0,0 @@ -import { BaseMessage } from '@langchain/core/messages'; -import { - PromptTemplate, - ChatPromptTemplate, - MessagesPlaceholder, -} from '@langchain/core/prompts'; -import { - RunnableSequence, - RunnableMap, - RunnableLambda, -} from '@langchain/core/runnables'; -import { StringOutputParser } from '@langchain/core/output_parsers'; -import { Document } from '@langchain/core/documents'; -import { searchSearxng } from '../lib/searxng'; -import type { StreamEvent } from '@langchain/core/tracers/log_stream'; -import type { BaseChatModel } from '@langchain/core/language_models/chat_models'; -import type { Embeddings } from '@langchain/core/embeddings'; -import formatChatHistoryAsString from '../utils/formatHistory'; -import eventEmitter from 'events'; -import computeSimilarity from '../utils/computeSimilarity'; -import logger from '../utils/logger'; - -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. -If it is a writing task or a simple hi, hello rather than a question, you need to return \`not_needed\` as the response. - -Example: -1. Follow up question: Which company is most likely to create an AGI -Rephrased: Which company is most likely to create an AGI - -2. Follow up question: Is Earth flat? -Rephrased: Is Earth flat? - -3. Follow up question: Is there life on Mars? -Rephrased: Is there life on Mars? - -Conversation: -{chat_history} - -Follow up question: {query} -Rephrased question: -`; - -const basicRedditSearchResponsePrompt = ` - You are Perplexica, an AI model who is expert at searching the web and answering user's queries. You are set on focus mode 'Reddit', this means you will be searching for information, opinions and discussions on the web using Reddit. - - Generate a response that is informative and relevant to the user's query based on provided context (the context consits of search results containg a brief description of the content of that page). - You must use this context to answer the user's query in the best way possible. Use an unbaised and journalistic tone in your response. Do not repeat the text. - You must not tell the user to open any link or visit any website to get the answer. You must provide the answer in the response itself. If the user asks for links you can provide them. - Your responses should be medium to long in length be informative and relevant to the user's query. You can use markdowns to format your response. You should use bullet points to list the information. Make sure the answer is not short and is informative. - You have to cite the answer using [number] notation. You must cite the sentences with their relevent context number. You must cite each and every part of the answer so the user can know where the information is coming from. - Place these citations at the end of that particular sentence. You can cite the same sentence multiple times if it is relevant to the user's query like [number1][number2]. - However you do not need to cite it using the same number. You can use different numbers to cite the same sentence multiple times. The number refers to the number of the search result (passed in the context) used to generate that part of the answer. - - Aything inside the following \`context\` HTML block provided below is for your knowledge returned by Reddit and is not shared by the user. You have to answer question on the basis of it and cite the relevant information from it but you do not have to - talk about the context in your response. - - - {context} - - - If you think there's nothing relevant in the search results, you can say that 'Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?'. - Anything between the \`context\` is retrieved from Reddit and is not a part of the conversation with the user. Today's date is ${new Date().toISOString()} -`; - -const strParser = new StringOutputParser(); - -const handleStream = async ( - stream: AsyncGenerator, - emitter: eventEmitter, -) => { - for await (const event of stream) { - if ( - event.event === 'on_chain_end' && - event.name === 'FinalSourceRetriever' - ) { - emitter.emit( - 'data', - JSON.stringify({ type: 'sources', data: event.data.output }), - ); - } - if ( - event.event === 'on_chain_stream' && - event.name === 'FinalResponseGenerator' - ) { - emitter.emit( - 'data', - JSON.stringify({ type: 'response', data: event.data.chunk }), - ); - } - if ( - event.event === 'on_chain_end' && - event.name === 'FinalResponseGenerator' - ) { - emitter.emit('end'); - } - } -}; - -type BasicChainInput = { - chat_history: BaseMessage[]; - query: string; -}; - -const createBasicRedditSearchRetrieverChain = (llm: BaseChatModel) => { - return RunnableSequence.from([ - PromptTemplate.fromTemplate(basicRedditSearchRetrieverPrompt), - llm, - strParser, - RunnableLambda.from(async (input: string) => { - if (input === 'not_needed') { - return { query: '', docs: [] }; - } - - const res = await searchSearxng(input, { - language: 'en', - engines: ['reddit'], - }); - - const documents = res.results.map( - (result) => - new Document({ - pageContent: result.content ? result.content : result.title, - metadata: { - title: result.title, - url: result.url, - ...(result.img_src && { img_src: result.img_src }), - }, - }), - ); - - return { query: input, docs: documents }; - }), - ]); -}; - -const createBasicRedditSearchAnsweringChain = ( - llm: BaseChatModel, - embeddings: Embeddings, -) => { - const basicRedditSearchRetrieverChain = - createBasicRedditSearchRetrieverChain(llm); - - const processDocs = async (docs: Document[]) => { - return docs - .map((_, index) => `${index + 1}. ${docs[index].pageContent}`) - .join('\n'); - }; - - const rerankDocs = async ({ - query, - docs, - }: { - query: string; - docs: Document[]; - }) => { - if (docs.length === 0) { - return docs; - } - - const docsWithContent = docs.filter( - (doc) => doc.pageContent && doc.pageContent.length > 0, - ); - - const [docEmbeddings, queryEmbedding] = await Promise.all([ - embeddings.embedDocuments(docsWithContent.map((doc) => doc.pageContent)), - embeddings.embedQuery(query), - ]); - - const similarity = docEmbeddings.map((docEmbedding, i) => { - const sim = computeSimilarity(queryEmbedding, docEmbedding); - - return { - index: i, - similarity: sim, - }; - }); - - const sortedDocs = similarity - .sort((a, b) => b.similarity - a.similarity) - .slice(0, 15) - .filter((sim) => sim.similarity > 0.3) - .map((sim) => docsWithContent[sim.index]); - - return sortedDocs; - }; - - return RunnableSequence.from([ - RunnableMap.from({ - query: (input: BasicChainInput) => input.query, - chat_history: (input: BasicChainInput) => input.chat_history, - context: RunnableSequence.from([ - (input) => ({ - query: input.query, - chat_history: formatChatHistoryAsString(input.chat_history), - }), - basicRedditSearchRetrieverChain - .pipe(rerankDocs) - .withConfig({ - runName: 'FinalSourceRetriever', - }) - .pipe(processDocs), - ]), - }), - ChatPromptTemplate.fromMessages([ - ['system', basicRedditSearchResponsePrompt], - new MessagesPlaceholder('chat_history'), - ['user', '{query}'], - ]), - llm, - strParser, - ]).withConfig({ - runName: 'FinalResponseGenerator', - }); -}; - -const basicRedditSearch = ( - query: string, - history: BaseMessage[], - llm: BaseChatModel, - embeddings: Embeddings, -) => { - const emitter = new eventEmitter(); - - try { - const basicRedditSearchAnsweringChain = - createBasicRedditSearchAnsweringChain(llm, embeddings); - const stream = basicRedditSearchAnsweringChain.streamEvents( - { - chat_history: history, - query: query, - }, - { - version: 'v1', - }, - ); - - handleStream(stream, emitter); - } catch (err) { - emitter.emit( - 'error', - JSON.stringify({ data: 'An error has occurred please try again later' }), - ); - logger.error(`Error in RedditSearch: ${err}`); - } - - return emitter; -}; - -const handleRedditSearch = ( - message: string, - history: BaseMessage[], - llm: BaseChatModel, - embeddings: Embeddings, -) => { - const emitter = basicRedditSearch(message, history, llm, embeddings); - return emitter; -}; - -export default handleRedditSearch; diff --git a/src/agents/webSearchAgent.ts b/src/agents/webSearchAgent.ts deleted file mode 100644 index 1364742..0000000 --- a/src/agents/webSearchAgent.ts +++ /dev/null @@ -1,261 +0,0 @@ -import { BaseMessage } from '@langchain/core/messages'; -import { - PromptTemplate, - ChatPromptTemplate, - MessagesPlaceholder, -} from '@langchain/core/prompts'; -import { - RunnableSequence, - RunnableMap, - RunnableLambda, -} from '@langchain/core/runnables'; -import { StringOutputParser } from '@langchain/core/output_parsers'; -import { Document } from '@langchain/core/documents'; -import { searchSearxng } from '../lib/searxng'; -import type { StreamEvent } from '@langchain/core/tracers/log_stream'; -import type { BaseChatModel } from '@langchain/core/language_models/chat_models'; -import type { Embeddings } from '@langchain/core/embeddings'; -import formatChatHistoryAsString from '../utils/formatHistory'; -import eventEmitter from 'events'; -import computeSimilarity from '../utils/computeSimilarity'; -import logger from '../utils/logger'; - -const basicSearchRetrieverPrompt = ` -You will be given a conversation below and a follow up question. You need to rephrase the follow-up question if needed so it is a standalone question that can be used by the LLM to search the web for information. -If it is a writing task or a simple hi, hello rather than a question, you need to return \`not_needed\` as the response. - -Example: -1. Follow up question: What is the capital of France? -Rephrased: Capital of france - -2. Follow up question: What is the population of New York City? -Rephrased: Population of New York City - -3. Follow up question: What is Docker? -Rephrased: What is Docker - -Conversation: -{chat_history} - -Follow up question: {query} -Rephrased question: -`; - -const basicWebSearchResponsePrompt = ` - You are Perplexica, an AI model who is expert at searching the web and answering user's queries. - - Generate a response that is informative and relevant to the user's query based on provided context (the context consits of search results containg a brief description of the content of that page). - You must use this context to answer the user's query in the best way possible. Use an unbaised and journalistic tone in your response. Do not repeat the text. - You must not tell the user to open any link or visit any website to get the answer. You must provide the answer in the response itself. If the user asks for links you can provide them. - Your responses should be medium to long in length be informative and relevant to the user's query. You can use markdowns to format your response. You should use bullet points to list the information. Make sure the answer is not short and is informative. - You have to cite the answer using [number] notation. You must cite the sentences with their relevent context number. You must cite each and every part of the answer so the user can know where the information is coming from. - Place these citations at the end of that particular sentence. You can cite the same sentence multiple times if it is relevant to the user's query like [number1][number2]. - However you do not need to cite it using the same number. You can use different numbers to cite the same sentence multiple times. The number refers to the number of the search result (passed in the context) used to generate that part of the answer. - - Aything inside the following \`context\` HTML block provided below is for your knowledge returned by the search engine and is not shared by the user. You have to answer question on the basis of it and cite the relevant information from it but you do not have to - talk about the context in your response. - - - {context} - - - If you think there's nothing relevant in the search results, you can say that 'Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?'. - Anything between the \`context\` is retrieved from a search engine and is not a part of the conversation with the user. Today's date is ${new Date().toISOString()} -`; - -const strParser = new StringOutputParser(); - -const handleStream = async ( - stream: AsyncGenerator, - emitter: eventEmitter, -) => { - for await (const event of stream) { - if ( - event.event === 'on_chain_end' && - event.name === 'FinalSourceRetriever' - ) { - emitter.emit( - 'data', - JSON.stringify({ type: 'sources', data: event.data.output }), - ); - } - if ( - event.event === 'on_chain_stream' && - event.name === 'FinalResponseGenerator' - ) { - emitter.emit( - 'data', - JSON.stringify({ type: 'response', data: event.data.chunk }), - ); - } - if ( - event.event === 'on_chain_end' && - event.name === 'FinalResponseGenerator' - ) { - emitter.emit('end'); - } - } -}; - -type BasicChainInput = { - chat_history: BaseMessage[]; - query: string; -}; - -const createBasicWebSearchRetrieverChain = (llm: BaseChatModel) => { - return RunnableSequence.from([ - PromptTemplate.fromTemplate(basicSearchRetrieverPrompt), - llm, - strParser, - RunnableLambda.from(async (input: string) => { - if (input === 'not_needed') { - return { query: '', docs: [] }; - } - - const res = await searchSearxng(input, { - language: 'en', - }); - - const documents = res.results.map( - (result) => - new Document({ - pageContent: result.content, - metadata: { - title: result.title, - url: result.url, - ...(result.img_src && { img_src: result.img_src }), - }, - }), - ); - - return { query: input, docs: documents }; - }), - ]); -}; - -const createBasicWebSearchAnsweringChain = ( - llm: BaseChatModel, - embeddings: Embeddings, -) => { - const basicWebSearchRetrieverChain = createBasicWebSearchRetrieverChain(llm); - - const processDocs = async (docs: Document[]) => { - return docs - .map((_, index) => `${index + 1}. ${docs[index].pageContent}`) - .join('\n'); - }; - - const rerankDocs = async ({ - query, - docs, - }: { - query: string; - docs: Document[]; - }) => { - if (docs.length === 0) { - return docs; - } - - const docsWithContent = docs.filter( - (doc) => doc.pageContent && doc.pageContent.length > 0, - ); - - const [docEmbeddings, queryEmbedding] = await Promise.all([ - embeddings.embedDocuments(docsWithContent.map((doc) => doc.pageContent)), - embeddings.embedQuery(query), - ]); - - const similarity = docEmbeddings.map((docEmbedding, i) => { - const sim = computeSimilarity(queryEmbedding, docEmbedding); - - return { - index: i, - similarity: sim, - }; - }); - - const sortedDocs = similarity - .sort((a, b) => b.similarity - a.similarity) - .filter((sim) => sim.similarity > 0.5) - .slice(0, 15) - .map((sim) => docsWithContent[sim.index]); - - return sortedDocs; - }; - - return RunnableSequence.from([ - RunnableMap.from({ - query: (input: BasicChainInput) => input.query, - chat_history: (input: BasicChainInput) => input.chat_history, - context: RunnableSequence.from([ - (input) => ({ - query: input.query, - chat_history: formatChatHistoryAsString(input.chat_history), - }), - basicWebSearchRetrieverChain - .pipe(rerankDocs) - .withConfig({ - runName: 'FinalSourceRetriever', - }) - .pipe(processDocs), - ]), - }), - ChatPromptTemplate.fromMessages([ - ['system', basicWebSearchResponsePrompt], - new MessagesPlaceholder('chat_history'), - ['user', '{query}'], - ]), - llm, - strParser, - ]).withConfig({ - runName: 'FinalResponseGenerator', - }); -}; - -const basicWebSearch = ( - query: string, - history: BaseMessage[], - llm: BaseChatModel, - embeddings: Embeddings, -) => { - const emitter = new eventEmitter(); - - try { - const basicWebSearchAnsweringChain = createBasicWebSearchAnsweringChain( - llm, - embeddings, - ); - - const stream = basicWebSearchAnsweringChain.streamEvents( - { - chat_history: history, - query: query, - }, - { - version: 'v1', - }, - ); - - handleStream(stream, emitter); - } catch (err) { - emitter.emit( - 'error', - JSON.stringify({ data: 'An error has occurred please try again later' }), - ); - logger.error(`Error in websearch: ${err}`); - } - - return emitter; -}; - -const handleWebSearch = ( - message: string, - history: BaseMessage[], - llm: BaseChatModel, - embeddings: Embeddings, -) => { - const emitter = basicWebSearch(message, history, llm, embeddings); - return emitter; -}; - -export default handleWebSearch; diff --git a/src/agents/wolframAlphaSearchAgent.ts b/src/agents/wolframAlphaSearchAgent.ts deleted file mode 100644 index f810a1e..0000000 --- a/src/agents/wolframAlphaSearchAgent.ts +++ /dev/null @@ -1,219 +0,0 @@ -import { BaseMessage } from '@langchain/core/messages'; -import { - PromptTemplate, - ChatPromptTemplate, - MessagesPlaceholder, -} from '@langchain/core/prompts'; -import { - RunnableSequence, - RunnableMap, - RunnableLambda, -} from '@langchain/core/runnables'; -import { StringOutputParser } from '@langchain/core/output_parsers'; -import { Document } from '@langchain/core/documents'; -import { searchSearxng } from '../lib/searxng'; -import type { StreamEvent } from '@langchain/core/tracers/log_stream'; -import type { BaseChatModel } from '@langchain/core/language_models/chat_models'; -import type { Embeddings } from '@langchain/core/embeddings'; -import formatChatHistoryAsString from '../utils/formatHistory'; -import eventEmitter from 'events'; -import logger from '../utils/logger'; - -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. -If it is a writing task or a simple hi, hello rather than a question, you need to return \`not_needed\` as the response. - -Example: -1. Follow up question: What is the atomic radius of S? -Rephrased: Atomic radius of S - -2. Follow up question: What is linear algebra? -Rephrased: Linear algebra - -3. Follow up question: What is the third law of thermodynamics? -Rephrased: Third law of thermodynamics - -Conversation: -{chat_history} - -Follow up question: {query} -Rephrased question: -`; - -const basicWolframAlphaSearchResponsePrompt = ` - You are Perplexica, an AI model who is expert at searching the web and answering user's queries. You are set on focus mode 'Wolfram Alpha', this means you will be searching for information on the web using Wolfram Alpha. It is a computational knowledge engine that can answer factual queries and perform computations. - - Generate a response that is informative and relevant to the user's query based on provided context (the context consits of search results containg a brief description of the content of that page). - You must use this context to answer the user's query in the best way possible. Use an unbaised and journalistic tone in your response. Do not repeat the text. - You must not tell the user to open any link or visit any website to get the answer. You must provide the answer in the response itself. If the user asks for links you can provide them. - Your responses should be medium to long in length be informative and relevant to the user's query. You can use markdowns to format your response. You should use bullet points to list the information. Make sure the answer is not short and is informative. - You have to cite the answer using [number] notation. You must cite the sentences with their relevent context number. You must cite each and every part of the answer so the user can know where the information is coming from. - Place these citations at the end of that particular sentence. You can cite the same sentence multiple times if it is relevant to the user's query like [number1][number2]. - However you do not need to cite it using the same number. You can use different numbers to cite the same sentence multiple times. The number refers to the number of the search result (passed in the context) used to generate that part of the answer. - - Aything inside the following \`context\` HTML block provided below is for your knowledge returned by Wolfram Alpha and is not shared by the user. You have to answer question on the basis of it and cite the relevant information from it but you do not have to - talk about the context in your response. - - - {context} - - - If you think there's nothing relevant in the search results, you can say that 'Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?'. - Anything between the \`context\` is retrieved from Wolfram Alpha and is not a part of the conversation with the user. Today's date is ${new Date().toISOString()} -`; - -const strParser = new StringOutputParser(); - -const handleStream = async ( - stream: AsyncGenerator, - emitter: eventEmitter, -) => { - for await (const event of stream) { - if ( - event.event === 'on_chain_end' && - event.name === 'FinalSourceRetriever' - ) { - emitter.emit( - 'data', - JSON.stringify({ type: 'sources', data: event.data.output }), - ); - } - if ( - event.event === 'on_chain_stream' && - event.name === 'FinalResponseGenerator' - ) { - emitter.emit( - 'data', - JSON.stringify({ type: 'response', data: event.data.chunk }), - ); - } - if ( - event.event === 'on_chain_end' && - event.name === 'FinalResponseGenerator' - ) { - emitter.emit('end'); - } - } -}; - -type BasicChainInput = { - chat_history: BaseMessage[]; - query: string; -}; - -const createBasicWolframAlphaSearchRetrieverChain = (llm: BaseChatModel) => { - return RunnableSequence.from([ - PromptTemplate.fromTemplate(basicWolframAlphaSearchRetrieverPrompt), - llm, - strParser, - RunnableLambda.from(async (input: string) => { - if (input === 'not_needed') { - return { query: '', docs: [] }; - } - - const res = await searchSearxng(input, { - language: 'en', - engines: ['wolframalpha'], - }); - - const documents = res.results.map( - (result) => - new Document({ - pageContent: result.content, - metadata: { - title: result.title, - url: result.url, - ...(result.img_src && { img_src: result.img_src }), - }, - }), - ); - - return { query: input, docs: documents }; - }), - ]); -}; - -const createBasicWolframAlphaSearchAnsweringChain = (llm: BaseChatModel) => { - const basicWolframAlphaSearchRetrieverChain = - createBasicWolframAlphaSearchRetrieverChain(llm); - - const processDocs = (docs: Document[]) => { - return docs - .map((_, index) => `${index + 1}. ${docs[index].pageContent}`) - .join('\n'); - }; - - return RunnableSequence.from([ - RunnableMap.from({ - query: (input: BasicChainInput) => input.query, - chat_history: (input: BasicChainInput) => input.chat_history, - context: RunnableSequence.from([ - (input) => ({ - query: input.query, - chat_history: formatChatHistoryAsString(input.chat_history), - }), - basicWolframAlphaSearchRetrieverChain - .pipe(({ query, docs }) => { - return docs; - }) - .withConfig({ - runName: 'FinalSourceRetriever', - }) - .pipe(processDocs), - ]), - }), - ChatPromptTemplate.fromMessages([ - ['system', basicWolframAlphaSearchResponsePrompt], - new MessagesPlaceholder('chat_history'), - ['user', '{query}'], - ]), - llm, - strParser, - ]).withConfig({ - runName: 'FinalResponseGenerator', - }); -}; - -const basicWolframAlphaSearch = ( - query: string, - history: BaseMessage[], - llm: BaseChatModel, -) => { - const emitter = new eventEmitter(); - - try { - const basicWolframAlphaSearchAnsweringChain = - createBasicWolframAlphaSearchAnsweringChain(llm); - const stream = basicWolframAlphaSearchAnsweringChain.streamEvents( - { - chat_history: history, - query: query, - }, - { - version: 'v1', - }, - ); - - handleStream(stream, emitter); - } catch (err) { - emitter.emit( - 'error', - JSON.stringify({ data: 'An error has occurred please try again later' }), - ); - logger.error(`Error in WolframAlphaSearch: ${err}`); - } - - return emitter; -}; - -const handleWolframAlphaSearch = ( - message: string, - history: BaseMessage[], - llm: BaseChatModel, - embeddings: Embeddings, -) => { - const emitter = basicWolframAlphaSearch(message, history, llm); - return emitter; -}; - -export default handleWolframAlphaSearch; diff --git a/src/agents/writingAssistant.ts b/src/agents/writingAssistant.ts deleted file mode 100644 index 7c2cb49..0000000 --- a/src/agents/writingAssistant.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { BaseMessage } from '@langchain/core/messages'; -import { - ChatPromptTemplate, - MessagesPlaceholder, -} from '@langchain/core/prompts'; -import { RunnableSequence } from '@langchain/core/runnables'; -import { StringOutputParser } from '@langchain/core/output_parsers'; -import type { StreamEvent } from '@langchain/core/tracers/log_stream'; -import eventEmitter from 'events'; -import type { BaseChatModel } from '@langchain/core/language_models/chat_models'; -import type { Embeddings } from '@langchain/core/embeddings'; -import logger from '../utils/logger'; - -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. -Since you are a writing assistant, you would not perform web searches. If you think you lack information to answer the query, you can ask the user for more information or suggest them to switch to a different focus mode. -`; - -const strParser = new StringOutputParser(); - -const handleStream = async ( - stream: AsyncGenerator, - emitter: eventEmitter, -) => { - for await (const event of stream) { - if ( - event.event === 'on_chain_stream' && - event.name === 'FinalResponseGenerator' - ) { - emitter.emit( - 'data', - JSON.stringify({ type: 'response', data: event.data.chunk }), - ); - } - if ( - event.event === 'on_chain_end' && - event.name === 'FinalResponseGenerator' - ) { - emitter.emit('end'); - } - } -}; - -const createWritingAssistantChain = (llm: BaseChatModel) => { - return RunnableSequence.from([ - ChatPromptTemplate.fromMessages([ - ['system', writingAssistantPrompt], - new MessagesPlaceholder('chat_history'), - ['user', '{query}'], - ]), - llm, - strParser, - ]).withConfig({ - runName: 'FinalResponseGenerator', - }); -}; - -const handleWritingAssistant = ( - query: string, - history: BaseMessage[], - llm: BaseChatModel, - embeddings: Embeddings, -) => { - const emitter = new eventEmitter(); - - try { - const writingAssistantChain = createWritingAssistantChain(llm); - const stream = writingAssistantChain.streamEvents( - { - chat_history: history, - query: query, - }, - { - version: 'v1', - }, - ); - - handleStream(stream, emitter); - } catch (err) { - emitter.emit( - 'error', - JSON.stringify({ data: 'An error has occurred please try again later' }), - ); - logger.error(`Error in writing assistant: ${err}`); - } - - return emitter; -}; - -export default handleWritingAssistant; diff --git a/src/agents/youtubeSearchAgent.ts b/src/agents/youtubeSearchAgent.ts deleted file mode 100644 index 4e82cc7..0000000 --- a/src/agents/youtubeSearchAgent.ts +++ /dev/null @@ -1,261 +0,0 @@ -import { BaseMessage } from '@langchain/core/messages'; -import { - PromptTemplate, - ChatPromptTemplate, - MessagesPlaceholder, -} from '@langchain/core/prompts'; -import { - RunnableSequence, - RunnableMap, - RunnableLambda, -} from '@langchain/core/runnables'; -import { StringOutputParser } from '@langchain/core/output_parsers'; -import { Document } from '@langchain/core/documents'; -import { searchSearxng } from '../lib/searxng'; -import type { StreamEvent } from '@langchain/core/tracers/log_stream'; -import type { BaseChatModel } from '@langchain/core/language_models/chat_models'; -import type { Embeddings } from '@langchain/core/embeddings'; -import formatChatHistoryAsString from '../utils/formatHistory'; -import eventEmitter from 'events'; -import computeSimilarity from '../utils/computeSimilarity'; -import logger from '../utils/logger'; - -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. -If it is a writing task or a simple hi, hello rather than a question, you need to return \`not_needed\` as the response. - -Example: -1. Follow up question: How does an A.C work? -Rephrased: A.C working - -2. Follow up question: Linear algebra explanation video -Rephrased: What is linear algebra? - -3. Follow up question: What is theory of relativity? -Rephrased: What is theory of relativity? - -Conversation: -{chat_history} - -Follow up question: {query} -Rephrased question: -`; - -const basicYoutubeSearchResponsePrompt = ` - You are Perplexica, an AI model who is expert at searching the web and answering user's queries. You are set on focus mode 'Youtube', this means you will be searching for videos on the web using Youtube and providing information based on the video's transcript. - - Generate a response that is informative and relevant to the user's query based on provided context (the context consits of search results containg a brief description of the content of that page). - You must use this context to answer the user's query in the best way possible. Use an unbaised and journalistic tone in your response. Do not repeat the text. - You must not tell the user to open any link or visit any website to get the answer. You must provide the answer in the response itself. If the user asks for links you can provide them. - Your responses should be medium to long in length be informative and relevant to the user's query. You can use markdowns to format your response. You should use bullet points to list the information. Make sure the answer is not short and is informative. - You have to cite the answer using [number] notation. You must cite the sentences with their relevent context number. You must cite each and every part of the answer so the user can know where the information is coming from. - Place these citations at the end of that particular sentence. You can cite the same sentence multiple times if it is relevant to the user's query like [number1][number2]. - However you do not need to cite it using the same number. You can use different numbers to cite the same sentence multiple times. The number refers to the number of the search result (passed in the context) used to generate that part of the answer. - - Aything inside the following \`context\` HTML block provided below is for your knowledge returned by Youtube and is not shared by the user. You have to answer question on the basis of it and cite the relevant information from it but you do not have to - talk about the context in your response. - - - {context} - - - If you think there's nothing relevant in the search results, you can say that 'Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?'. - Anything between the \`context\` is retrieved from Youtube and is not a part of the conversation with the user. Today's date is ${new Date().toISOString()} -`; - -const strParser = new StringOutputParser(); - -const handleStream = async ( - stream: AsyncGenerator, - emitter: eventEmitter, -) => { - for await (const event of stream) { - if ( - event.event === 'on_chain_end' && - event.name === 'FinalSourceRetriever' - ) { - emitter.emit( - 'data', - JSON.stringify({ type: 'sources', data: event.data.output }), - ); - } - if ( - event.event === 'on_chain_stream' && - event.name === 'FinalResponseGenerator' - ) { - emitter.emit( - 'data', - JSON.stringify({ type: 'response', data: event.data.chunk }), - ); - } - if ( - event.event === 'on_chain_end' && - event.name === 'FinalResponseGenerator' - ) { - emitter.emit('end'); - } - } -}; - -type BasicChainInput = { - chat_history: BaseMessage[]; - query: string; -}; - -const createBasicYoutubeSearchRetrieverChain = (llm: BaseChatModel) => { - return RunnableSequence.from([ - PromptTemplate.fromTemplate(basicYoutubeSearchRetrieverPrompt), - llm, - strParser, - RunnableLambda.from(async (input: string) => { - if (input === 'not_needed') { - return { query: '', docs: [] }; - } - - const res = await searchSearxng(input, { - language: 'en', - engines: ['youtube'], - }); - - const documents = res.results.map( - (result) => - new Document({ - pageContent: result.content ? result.content : result.title, - metadata: { - title: result.title, - url: result.url, - ...(result.img_src && { img_src: result.img_src }), - }, - }), - ); - - return { query: input, docs: documents }; - }), - ]); -}; - -const createBasicYoutubeSearchAnsweringChain = ( - llm: BaseChatModel, - embeddings: Embeddings, -) => { - const basicYoutubeSearchRetrieverChain = - createBasicYoutubeSearchRetrieverChain(llm); - - const processDocs = async (docs: Document[]) => { - return docs - .map((_, index) => `${index + 1}. ${docs[index].pageContent}`) - .join('\n'); - }; - - const rerankDocs = async ({ - query, - docs, - }: { - query: string; - docs: Document[]; - }) => { - if (docs.length === 0) { - return docs; - } - - const docsWithContent = docs.filter( - (doc) => doc.pageContent && doc.pageContent.length > 0, - ); - - const [docEmbeddings, queryEmbedding] = await Promise.all([ - embeddings.embedDocuments(docsWithContent.map((doc) => doc.pageContent)), - embeddings.embedQuery(query), - ]); - - const similarity = docEmbeddings.map((docEmbedding, i) => { - const sim = computeSimilarity(queryEmbedding, docEmbedding); - - return { - index: i, - similarity: sim, - }; - }); - - const sortedDocs = similarity - .sort((a, b) => b.similarity - a.similarity) - .slice(0, 15) - .filter((sim) => sim.similarity > 0.3) - .map((sim) => docsWithContent[sim.index]); - - return sortedDocs; - }; - - return RunnableSequence.from([ - RunnableMap.from({ - query: (input: BasicChainInput) => input.query, - chat_history: (input: BasicChainInput) => input.chat_history, - context: RunnableSequence.from([ - (input) => ({ - query: input.query, - chat_history: formatChatHistoryAsString(input.chat_history), - }), - basicYoutubeSearchRetrieverChain - .pipe(rerankDocs) - .withConfig({ - runName: 'FinalSourceRetriever', - }) - .pipe(processDocs), - ]), - }), - ChatPromptTemplate.fromMessages([ - ['system', basicYoutubeSearchResponsePrompt], - new MessagesPlaceholder('chat_history'), - ['user', '{query}'], - ]), - llm, - strParser, - ]).withConfig({ - runName: 'FinalResponseGenerator', - }); -}; - -const basicYoutubeSearch = ( - query: string, - history: BaseMessage[], - llm: BaseChatModel, - embeddings: Embeddings, -) => { - const emitter = new eventEmitter(); - - try { - const basicYoutubeSearchAnsweringChain = - createBasicYoutubeSearchAnsweringChain(llm, embeddings); - - const stream = basicYoutubeSearchAnsweringChain.streamEvents( - { - chat_history: history, - query: query, - }, - { - version: 'v1', - }, - ); - - handleStream(stream, emitter); - } catch (err) { - emitter.emit( - 'error', - JSON.stringify({ data: 'An error has occurred please try again later' }), - ); - logger.error(`Error in youtube search: ${err}`); - } - - return emitter; -}; - -const handleYoutubeSearch = ( - message: string, - history: BaseMessage[], - llm: BaseChatModel, - embeddings: Embeddings, -) => { - const emitter = basicYoutubeSearch(message, history, llm, embeddings); - return emitter; -}; - -export default handleYoutubeSearch; diff --git a/src/app.ts b/src/app.ts index b8c2371..96b3a0c 100644 --- a/src/app.ts +++ b/src/app.ts @@ -28,3 +28,11 @@ server.listen(port, () => { }); startWebSocketServer(server); + +process.on('uncaughtException', (err, origin) => { + logger.error(`Uncaught Exception at ${origin}: ${err}`); +}); + +process.on('unhandledRejection', (reason, promise) => { + logger.error(`Unhandled Rejection at: ${promise}, reason: ${reason}`); +}); diff --git a/src/agents/imageSearchAgent.ts b/src/chains/imageSearchAgent.ts similarity index 100% rename from src/agents/imageSearchAgent.ts rename to src/chains/imageSearchAgent.ts diff --git a/src/agents/suggestionGeneratorAgent.ts b/src/chains/suggestionGeneratorAgent.ts similarity index 97% rename from src/agents/suggestionGeneratorAgent.ts rename to src/chains/suggestionGeneratorAgent.ts index 0efdfa9..6ba255d 100644 --- a/src/agents/suggestionGeneratorAgent.ts +++ b/src/chains/suggestionGeneratorAgent.ts @@ -47,7 +47,7 @@ const generateSuggestions = ( input: SuggestionGeneratorInput, llm: BaseChatModel, ) => { - (llm as ChatOpenAI).temperature = 0; + (llm as unknown as ChatOpenAI).temperature = 0; const suggestionGeneratorChain = createSuggestionGeneratorChain(llm); return suggestionGeneratorChain.invoke(input); }; diff --git a/src/agents/videoSearchAgent.ts b/src/chains/videoSearchAgent.ts similarity index 100% rename from src/agents/videoSearchAgent.ts rename to src/chains/videoSearchAgent.ts diff --git a/src/config.ts b/src/config.ts index 7c0c7f1..001c259 100644 --- a/src/config.ts +++ b/src/config.ts @@ -8,10 +8,13 @@ interface Config { GENERAL: { PORT: number; SIMILARITY_MEASURE: string; + KEEP_ALIVE: string; }; API_KEYS: { OPENAI: string; GROQ: string; + ANTHROPIC: string; + GEMINI: string; }; API_ENDPOINTS: { SEARXNG: string; @@ -33,11 +36,18 @@ export const getPort = () => loadConfig().GENERAL.PORT; export const getSimilarityMeasure = () => loadConfig().GENERAL.SIMILARITY_MEASURE; +export const getKeepAlive = () => loadConfig().GENERAL.KEEP_ALIVE; + export const getOpenaiApiKey = () => loadConfig().API_KEYS.OPENAI; export const getGroqApiKey = () => loadConfig().API_KEYS.GROQ; -export const getSearxngApiEndpoint = () => loadConfig().API_ENDPOINTS.SEARXNG; +export const getAnthropicApiKey = () => loadConfig().API_KEYS.ANTHROPIC; + +export const getGeminiApiKey = () => loadConfig().API_KEYS.GEMINI; + +export const getSearxngApiEndpoint = () => + process.env.SEARXNG_API_URL || loadConfig().API_ENDPOINTS.SEARXNG; export const getOllamaApiEndpoint = () => loadConfig().API_ENDPOINTS.OLLAMA; diff --git a/src/db/index.ts b/src/db/index.ts new file mode 100644 index 0000000..b431b47 --- /dev/null +++ b/src/db/index.ts @@ -0,0 +1,10 @@ +import { drizzle } from 'drizzle-orm/better-sqlite3'; +import Database from 'better-sqlite3'; +import * as schema from './schema'; + +const sqlite = new Database('data/db.sqlite'); +const db = drizzle(sqlite, { + schema: schema, +}); + +export default db; diff --git a/src/db/schema.ts b/src/db/schema.ts new file mode 100644 index 0000000..cee9660 --- /dev/null +++ b/src/db/schema.ts @@ -0,0 +1,28 @@ +import { sql } from 'drizzle-orm'; +import { text, integer, sqliteTable } from 'drizzle-orm/sqlite-core'; + +export const messages = sqliteTable('messages', { + id: integer('id').primaryKey(), + content: text('content').notNull(), + chatId: text('chatId').notNull(), + messageId: text('messageId').notNull(), + role: text('type', { enum: ['assistant', 'user'] }), + metadata: text('metadata', { + mode: 'json', + }), +}); + +interface File { + name: string; + fileId: string; +} + +export const chats = sqliteTable('chats', { + id: text('id').primaryKey(), + title: text('title').notNull(), + createdAt: text('createdAt').notNull(), + focusMode: text('focusMode').notNull(), + files: text('files', { mode: 'json' }) + .$type() + .default(sql`'[]'`), +}); diff --git a/src/lib/outputParsers/lineOutputParser.ts b/src/lib/outputParsers/lineOutputParser.ts new file mode 100644 index 0000000..08711aa --- /dev/null +++ b/src/lib/outputParsers/lineOutputParser.ts @@ -0,0 +1,48 @@ +import { BaseOutputParser } from '@langchain/core/output_parsers'; + +interface LineOutputParserArgs { + key?: string; +} + +class LineOutputParser extends BaseOutputParser { + private key = 'questions'; + + constructor(args?: LineOutputParserArgs) { + super(); + this.key = args.key ?? this.key; + } + + static lc_name() { + return 'LineOutputParser'; + } + + lc_namespace = ['langchain', 'output_parsers', 'line_output_parser']; + + async parse(text: string): Promise { + text = text.trim() || ''; + + const regex = /^(\s*(-|\*|\d+\.\s|\d+\)\s|\u2022)\s*)+/; + const startKeyIndex = text.indexOf(`<${this.key}>`); + const endKeyIndex = text.indexOf(``); + + if (startKeyIndex === -1 || endKeyIndex === -1) { + return ''; + } + + const questionsStartIndex = + startKeyIndex === -1 ? 0 : startKeyIndex + `<${this.key}>`.length; + const questionsEndIndex = endKeyIndex === -1 ? text.length : endKeyIndex; + const line = text + .slice(questionsStartIndex, questionsEndIndex) + .trim() + .replace(regex, ''); + + return line; + } + + getFormatInstructions(): string { + throw new Error('Not implemented.'); + } +} + +export default LineOutputParser; diff --git a/src/lib/outputParsers/listLineOutputParser.ts b/src/lib/outputParsers/listLineOutputParser.ts index 57a9bbc..f465ef1 100644 --- a/src/lib/outputParsers/listLineOutputParser.ts +++ b/src/lib/outputParsers/listLineOutputParser.ts @@ -19,9 +19,16 @@ class LineListOutputParser extends BaseOutputParser { lc_namespace = ['langchain', 'output_parsers', 'line_list_output_parser']; async parse(text: string): Promise { + text = text.trim() || ''; + const regex = /^(\s*(-|\*|\d+\.\s|\d+\)\s|\u2022)\s*)+/; const startKeyIndex = text.indexOf(`<${this.key}>`); const endKeyIndex = text.indexOf(``); + + if (startKeyIndex === -1 || endKeyIndex === -1) { + return []; + } + const questionsStartIndex = startKeyIndex === -1 ? 0 : startKeyIndex + `<${this.key}>`.length; const questionsEndIndex = endKeyIndex === -1 ? text.length : endKeyIndex; diff --git a/src/lib/providers.ts b/src/lib/providers.ts deleted file mode 100644 index 3223193..0000000 --- a/src/lib/providers.ts +++ /dev/null @@ -1,187 +0,0 @@ -import { ChatOpenAI, OpenAIEmbeddings } from '@langchain/openai'; -import { ChatOllama } from '@langchain/community/chat_models/ollama'; -import { OllamaEmbeddings } from '@langchain/community/embeddings/ollama'; -import { HuggingFaceTransformersEmbeddings } from './huggingfaceTransformer'; -import { - getGroqApiKey, - getOllamaApiEndpoint, - getOpenaiApiKey, -} from '../config'; -import logger from '../utils/logger'; - -export const getAvailableChatModelProviders = async () => { - const openAIApiKey = getOpenaiApiKey(); - const groqApiKey = getGroqApiKey(); - const ollamaEndpoint = getOllamaApiEndpoint(); - - const models = {}; - - if (openAIApiKey) { - try { - models['openai'] = { - 'GPT-3.5 turbo': new ChatOpenAI({ - openAIApiKey, - modelName: 'gpt-3.5-turbo', - temperature: 0.7, - }), - 'GPT-4': new ChatOpenAI({ - openAIApiKey, - modelName: 'gpt-4', - temperature: 0.7, - }), - 'GPT-4 turbo': new ChatOpenAI({ - openAIApiKey, - modelName: 'gpt-4-turbo', - temperature: 0.7, - }), - 'GPT-4 omni': new ChatOpenAI({ - openAIApiKey, - modelName: 'gpt-4o', - temperature: 0.7, - }), - }; - } catch (err) { - logger.error(`Error loading OpenAI models: ${err}`); - } - } - - if (groqApiKey) { - try { - models['groq'] = { - 'LLaMA3 8b': new ChatOpenAI( - { - openAIApiKey: groqApiKey, - modelName: 'llama3-8b-8192', - temperature: 0.7, - }, - { - baseURL: 'https://api.groq.com/openai/v1', - }, - ), - 'LLaMA3 70b': new ChatOpenAI( - { - openAIApiKey: groqApiKey, - modelName: 'llama3-70b-8192', - temperature: 0.7, - }, - { - baseURL: 'https://api.groq.com/openai/v1', - }, - ), - 'Mixtral 8x7b': new ChatOpenAI( - { - openAIApiKey: groqApiKey, - modelName: 'mixtral-8x7b-32768', - temperature: 0.7, - }, - { - baseURL: 'https://api.groq.com/openai/v1', - }, - ), - 'Gemma 7b': new ChatOpenAI( - { - openAIApiKey: groqApiKey, - modelName: 'gemma-7b-it', - temperature: 0.7, - }, - { - baseURL: 'https://api.groq.com/openai/v1', - }, - ), - }; - } catch (err) { - logger.error(`Error loading Groq models: ${err}`); - } - } - - if (ollamaEndpoint) { - try { - const response = await fetch(`${ollamaEndpoint}/api/tags`, { - headers: { - 'Content-Type': 'application/json', - }, - }); - - const { models: ollamaModels } = (await response.json()) as any; - - models['ollama'] = ollamaModels.reduce((acc, model) => { - acc[model.model] = new ChatOllama({ - baseUrl: ollamaEndpoint, - model: model.model, - temperature: 0.7, - }); - return acc; - }, {}); - } catch (err) { - logger.error(`Error loading Ollama models: ${err}`); - } - } - - models['custom_openai'] = {}; - - return models; -}; - -export const getAvailableEmbeddingModelProviders = async () => { - const openAIApiKey = getOpenaiApiKey(); - const ollamaEndpoint = getOllamaApiEndpoint(); - - const models = {}; - - if (openAIApiKey) { - try { - models['openai'] = { - 'Text embedding 3 small': new OpenAIEmbeddings({ - openAIApiKey, - modelName: 'text-embedding-3-small', - }), - 'Text embedding 3 large': new OpenAIEmbeddings({ - openAIApiKey, - modelName: 'text-embedding-3-large', - }), - }; - } catch (err) { - logger.error(`Error loading OpenAI embeddings: ${err}`); - } - } - - if (ollamaEndpoint) { - try { - const response = await fetch(`${ollamaEndpoint}/api/tags`, { - headers: { - 'Content-Type': 'application/json', - }, - }); - - const { models: ollamaModels } = (await response.json()) as any; - - models['ollama'] = ollamaModels.reduce((acc, model) => { - acc[model.model] = new OllamaEmbeddings({ - baseUrl: ollamaEndpoint, - model: model.model, - }); - return acc; - }, {}); - } catch (err) { - logger.error(`Error loading Ollama embeddings: ${err}`); - } - } - - try { - models['local'] = { - 'BGE Small': new HuggingFaceTransformersEmbeddings({ - modelName: 'Xenova/bge-small-en-v1.5', - }), - 'GTE Small': new HuggingFaceTransformersEmbeddings({ - modelName: 'Xenova/gte-small', - }), - 'Bert Multilingual': new HuggingFaceTransformersEmbeddings({ - modelName: 'Xenova/bert-base-multilingual-uncased', - }), - }; - } catch (err) { - logger.error(`Error loading local embeddings: ${err}`); - } - - return models; -}; diff --git a/src/lib/providers/anthropic.ts b/src/lib/providers/anthropic.ts new file mode 100644 index 0000000..642a6cb --- /dev/null +++ b/src/lib/providers/anthropic.ts @@ -0,0 +1,59 @@ +import { ChatAnthropic } from '@langchain/anthropic'; +import { getAnthropicApiKey } from '../../config'; +import logger from '../../utils/logger'; + +export const loadAnthropicChatModels = async () => { + const anthropicApiKey = getAnthropicApiKey(); + + if (!anthropicApiKey) return {}; + + try { + const chatModels = { + 'claude-3-5-sonnet-20241022': { + displayName: 'Claude 3.5 Sonnet', + model: new ChatAnthropic({ + temperature: 0.7, + anthropicApiKey: anthropicApiKey, + model: 'claude-3-5-sonnet-20241022', + }), + }, + 'claude-3-5-haiku-20241022': { + displayName: 'Claude 3.5 Haiku', + model: new ChatAnthropic({ + temperature: 0.7, + anthropicApiKey: anthropicApiKey, + model: 'claude-3-5-haiku-20241022', + }), + }, + 'claude-3-opus-20240229': { + displayName: 'Claude 3 Opus', + model: new ChatAnthropic({ + temperature: 0.7, + anthropicApiKey: anthropicApiKey, + model: 'claude-3-opus-20240229', + }), + }, + 'claude-3-sonnet-20240229': { + displayName: 'Claude 3 Sonnet', + model: new ChatAnthropic({ + 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; + } catch (err) { + logger.error(`Error loading Anthropic models: ${err}`); + return {}; + } +}; diff --git a/src/lib/providers/gemini.ts b/src/lib/providers/gemini.ts new file mode 100644 index 0000000..d20c9b8 --- /dev/null +++ b/src/lib/providers/gemini.ts @@ -0,0 +1,85 @@ +import { + ChatGoogleGenerativeAI, + GoogleGenerativeAIEmbeddings, +} from '@langchain/google-genai'; +import { getGeminiApiKey } from '../../config'; +import logger from '../../utils/logger'; + +export const loadGeminiChatModels = async () => { + const geminiApiKey = getGeminiApiKey(); + + if (!geminiApiKey) return {}; + + try { + const chatModels = { + 'gemini-1.5-flash': { + displayName: 'Gemini 1.5 Flash', + model: new ChatGoogleGenerativeAI({ + modelName: 'gemini-1.5-flash', + temperature: 0.7, + apiKey: geminiApiKey, + }), + }, + 'gemini-1.5-flash-8b': { + displayName: 'Gemini 1.5 Flash 8B', + model: new ChatGoogleGenerativeAI({ + modelName: 'gemini-1.5-flash-8b', + temperature: 0.7, + apiKey: geminiApiKey, + }), + }, + 'gemini-1.5-pro': { + displayName: 'Gemini 1.5 Pro', + model: new ChatGoogleGenerativeAI({ + modelName: 'gemini-1.5-pro', + temperature: 0.7, + apiKey: geminiApiKey, + }), + }, + 'gemini-2.0-flash-exp': { + displayName: 'Gemini 2.0 Flash Exp', + model: new ChatGoogleGenerativeAI({ + modelName: 'gemini-2.0-flash-exp', + temperature: 0.7, + apiKey: geminiApiKey, + }), + }, + 'gemini-2.0-flash-thinking-exp-01-21': { + displayName: 'Gemini 2.0 Flash Thinking Exp 01-21', + model: new ChatGoogleGenerativeAI({ + modelName: 'gemini-2.0-flash-thinking-exp-01-21', + temperature: 0.7, + apiKey: geminiApiKey, + }), + }, + }; + + return chatModels; + } catch (err) { + logger.error(`Error loading Gemini models: ${err}`); + return {}; + } +}; + +export const loadGeminiEmbeddingsModels = async () => { + const geminiApiKey = getGeminiApiKey(); + + if (!geminiApiKey) return {}; + + try { + const embeddingModels = { + 'text-embedding-004': { + displayName: 'Text Embedding', + model: new GoogleGenerativeAIEmbeddings({ + apiKey: geminiApiKey, + modelName: 'text-embedding-004', + }), + }, + }; + + return embeddingModels; + } catch (err) { + logger.error(`Error loading Gemini embeddings model: ${err}`); + return {}; + } +}; diff --git a/src/lib/providers/groq.ts b/src/lib/providers/groq.ts new file mode 100644 index 0000000..41004ec --- /dev/null +++ b/src/lib/providers/groq.ts @@ -0,0 +1,136 @@ +import { ChatOpenAI } from '@langchain/openai'; +import { getGroqApiKey } from '../../config'; +import logger from '../../utils/logger'; + +export const loadGroqChatModels = async () => { + const groqApiKey = getGroqApiKey(); + + if (!groqApiKey) return {}; + + try { + const chatModels = { + 'llama-3.3-70b-versatile': { + displayName: 'Llama 3.3 70B', + model: new ChatOpenAI( + { + openAIApiKey: groqApiKey, + modelName: 'llama-3.3-70b-versatile', + temperature: 0.7, + }, + { + baseURL: 'https://api.groq.com/openai/v1', + }, + ), + }, + 'llama-3.2-3b-preview': { + displayName: 'Llama 3.2 3B', + model: new ChatOpenAI( + { + openAIApiKey: groqApiKey, + modelName: 'llama-3.2-3b-preview', + temperature: 0.7, + }, + { + baseURL: 'https://api.groq.com/openai/v1', + }, + ), + }, + 'llama-3.2-11b-vision-preview': { + displayName: 'Llama 3.2 11B Vision', + model: new ChatOpenAI( + { + openAIApiKey: groqApiKey, + modelName: 'llama-3.2-11b-vision-preview', + temperature: 0.7, + }, + { + baseURL: 'https://api.groq.com/openai/v1', + }, + ), + }, + 'llama-3.2-90b-vision-preview': { + displayName: 'Llama 3.2 90B Vision', + model: new ChatOpenAI( + { + openAIApiKey: groqApiKey, + modelName: 'llama-3.2-90b-vision-preview', + temperature: 0.7, + }, + { + baseURL: 'https://api.groq.com/openai/v1', + }, + ), + }, + 'llama-3.1-8b-instant': { + displayName: 'Llama 3.1 8B', + model: new ChatOpenAI( + { + openAIApiKey: groqApiKey, + modelName: 'llama-3.1-8b-instant', + temperature: 0.7, + }, + { + baseURL: 'https://api.groq.com/openai/v1', + }, + ), + }, + 'llama3-8b-8192': { + displayName: 'LLaMA3 8B', + model: new ChatOpenAI( + { + 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', + }, + ), + }, + '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; + } catch (err) { + logger.error(`Error loading Groq models: ${err}`); + return {}; + } +}; diff --git a/src/lib/providers/index.ts b/src/lib/providers/index.ts new file mode 100644 index 0000000..98846e7 --- /dev/null +++ b/src/lib/providers/index.ts @@ -0,0 +1,49 @@ +import { loadGroqChatModels } from './groq'; +import { loadOllamaChatModels, loadOllamaEmbeddingsModels } from './ollama'; +import { loadOpenAIChatModels, loadOpenAIEmbeddingsModels } from './openai'; +import { loadAnthropicChatModels } from './anthropic'; +import { loadTransformersEmbeddingsModels } from './transformers'; +import { loadGeminiChatModels, loadGeminiEmbeddingsModels } from './gemini'; + +const chatModelProviders = { + openai: loadOpenAIChatModels, + groq: loadGroqChatModels, + ollama: loadOllamaChatModels, + anthropic: loadAnthropicChatModels, + gemini: loadGeminiChatModels, +}; + +const embeddingModelProviders = { + openai: loadOpenAIEmbeddingsModels, + local: loadTransformersEmbeddingsModels, + ollama: loadOllamaEmbeddingsModels, + gemini: loadGeminiEmbeddingsModels, +}; + +export const getAvailableChatModelProviders = async () => { + const models = {}; + + for (const provider in chatModelProviders) { + const providerModels = await chatModelProviders[provider](); + if (Object.keys(providerModels).length > 0) { + models[provider] = providerModels; + } + } + + models['custom_openai'] = {}; + + return models; +}; + +export const getAvailableEmbeddingModelProviders = async () => { + const models = {}; + + for (const provider in embeddingModelProviders) { + const providerModels = await embeddingModelProviders[provider](); + if (Object.keys(providerModels).length > 0) { + models[provider] = providerModels; + } + } + + return models; +}; diff --git a/src/lib/providers/ollama.ts b/src/lib/providers/ollama.ts new file mode 100644 index 0000000..7277b27 --- /dev/null +++ b/src/lib/providers/ollama.ts @@ -0,0 +1,74 @@ +import { OllamaEmbeddings } from '@langchain/community/embeddings/ollama'; +import { getKeepAlive, getOllamaApiEndpoint } from '../../config'; +import logger from '../../utils/logger'; +import { ChatOllama } from '@langchain/community/chat_models/ollama'; +import axios from 'axios'; + +export const loadOllamaChatModels = async () => { + const ollamaEndpoint = getOllamaApiEndpoint(); + const keepAlive = getKeepAlive(); + + if (!ollamaEndpoint) return {}; + + try { + const response = await axios.get(`${ollamaEndpoint}/api/tags`, { + headers: { + 'Content-Type': 'application/json', + }, + }); + + const { models: ollamaModels } = response.data; + + const chatModels = ollamaModels.reduce((acc, model) => { + acc[model.model] = { + displayName: model.name, + model: new ChatOllama({ + baseUrl: ollamaEndpoint, + model: model.model, + temperature: 0.7, + keepAlive: keepAlive, + }), + }; + + return acc; + }, {}); + + return chatModels; + } catch (err) { + logger.error(`Error loading Ollama models: ${err}`); + return {}; + } +}; + +export const loadOllamaEmbeddingsModels = async () => { + const ollamaEndpoint = getOllamaApiEndpoint(); + + if (!ollamaEndpoint) return {}; + + try { + const response = await axios.get(`${ollamaEndpoint}/api/tags`, { + headers: { + 'Content-Type': 'application/json', + }, + }); + + const { models: ollamaModels } = response.data; + + const embeddingsModels = ollamaModels.reduce((acc, model) => { + acc[model.model] = { + displayName: model.name, + model: new OllamaEmbeddings({ + baseUrl: ollamaEndpoint, + model: model.model, + }), + }; + + return acc; + }, {}); + + return embeddingsModels; + } catch (err) { + logger.error(`Error loading Ollama embeddings model: ${err}`); + return {}; + } +}; diff --git a/src/lib/providers/openai.ts b/src/lib/providers/openai.ts new file mode 100644 index 0000000..3747e37 --- /dev/null +++ b/src/lib/providers/openai.ts @@ -0,0 +1,89 @@ +import { ChatOpenAI, OpenAIEmbeddings } from '@langchain/openai'; +import { getOpenaiApiKey } from '../../config'; +import logger from '../../utils/logger'; + +export const loadOpenAIChatModels = async () => { + const openAIApiKey = getOpenaiApiKey(); + + if (!openAIApiKey) return {}; + + try { + const chatModels = { + 'gpt-3.5-turbo': { + displayName: 'GPT-3.5 Turbo', + model: new ChatOpenAI({ + openAIApiKey, + modelName: 'gpt-3.5-turbo', + temperature: 0.7, + }), + }, + 'gpt-4': { + displayName: 'GPT-4', + model: new ChatOpenAI({ + openAIApiKey, + modelName: 'gpt-4', + temperature: 0.7, + }), + }, + 'gpt-4-turbo': { + displayName: 'GPT-4 turbo', + model: new ChatOpenAI({ + openAIApiKey, + modelName: 'gpt-4-turbo', + 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; + } catch (err) { + logger.error(`Error loading OpenAI models: ${err}`); + return {}; + } +}; + +export const loadOpenAIEmbeddingsModels = async () => { + const openAIApiKey = getOpenaiApiKey(); + + if (!openAIApiKey) return {}; + + try { + const embeddingModels = { + 'text-embedding-3-small': { + displayName: 'Text Embedding 3 Small', + model: new OpenAIEmbeddings({ + openAIApiKey, + modelName: 'text-embedding-3-small', + }), + }, + 'text-embedding-3-large': { + displayName: 'Text Embedding 3 Large', + model: new OpenAIEmbeddings({ + openAIApiKey, + modelName: 'text-embedding-3-large', + }), + }, + }; + + return embeddingModels; + } catch (err) { + logger.error(`Error loading OpenAI embeddings model: ${err}`); + return {}; + } +}; diff --git a/src/lib/providers/transformers.ts b/src/lib/providers/transformers.ts new file mode 100644 index 0000000..8a3417d --- /dev/null +++ b/src/lib/providers/transformers.ts @@ -0,0 +1,32 @@ +import logger from '../../utils/logger'; +import { HuggingFaceTransformersEmbeddings } from '../huggingfaceTransformer'; + +export const loadTransformersEmbeddingsModels = async () => { + try { + const embeddingModels = { + 'xenova-bge-small-en-v1.5': { + displayName: 'BGE Small', + model: new HuggingFaceTransformersEmbeddings({ + modelName: 'Xenova/bge-small-en-v1.5', + }), + }, + 'xenova-gte-small': { + displayName: 'GTE Small', + 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; + } catch (err) { + logger.error(`Error loading Transformers embeddings model: ${err}`); + return {}; + } +}; diff --git a/src/prompts/academicSearch.ts b/src/prompts/academicSearch.ts new file mode 100644 index 0000000..c2946ff --- /dev/null +++ b/src/prompts/academicSearch.ts @@ -0,0 +1,65 @@ +export const academicSearchRetrieverPrompt = ` +You will be given a conversation below and a follow up question. You need to rephrase the follow-up question if needed so it is a standalone question that can be used by the LLM to search the web for information. +If it is a writing task or a simple hi, hello rather than a question, you need to return \`not_needed\` as the response. + +Example: +1. Follow up question: How does stable diffusion work? +Rephrased: Stable diffusion working + +2. Follow up question: What is linear algebra? +Rephrased: Linear algebra + +3. Follow up question: What is the third law of thermodynamics? +Rephrased: Third law of thermodynamics + +Conversation: +{chat_history} + +Follow up question: {query} +Rephrased question: +`; + +export const academicSearchResponsePrompt = ` + You are Perplexica, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses. + + Your task is to provide answers that are: + - **Informative and relevant**: Thoroughly address the user's query using the given context. + - **Well-structured**: Include clear headings and subheadings, and use a professional tone to present information concisely and logically. + - **Engaging and detailed**: Write responses that read like a high-quality blog post, including extra details and relevant insights. + - **Cited and credible**: Use inline citations with [number] notation to refer to the context source(s) for each fact or detail included. + - **Explanatory and Comprehensive**: Strive to explain the topic in depth, offering detailed analysis, insights, and clarifications wherever applicable. + + ### Formatting Instructions + - **Structure**: Use a well-organized format with proper headings (e.g., "## Example heading 1" or "## Example heading 2"). Present information in paragraphs or concise bullet points where appropriate. + - **Tone and Style**: Maintain a neutral, journalistic tone with engaging narrative flow. Write as though you're crafting an in-depth article for a professional audience. + - **Markdown Usage**: Format your response with Markdown for clarity. Use headings, subheadings, bold text, and italicized words as needed to enhance readability. + - **Length and Depth**: Provide comprehensive coverage of the topic. Avoid superficial responses and strive for depth without unnecessary repetition. Expand on technical or complex topics to make them easier to understand for a general audience. + - **No main heading/title**: Start your response directly with the introduction unless asked to provide a specific title. + - **Conclusion or Summary**: Include a concluding paragraph that synthesizes the provided information or suggests potential next steps, where appropriate. + + ### Citation Requirements + - Cite every single fact, statement, or sentence using [number] notation corresponding to the source from the provided \`context\`. + - Integrate citations naturally at the end of sentences or clauses as appropriate. For example, "The Eiffel Tower is one of the most visited landmarks in the world[1]." + - Ensure that **every sentence in your response includes at least one citation**, even when information is inferred or connected to general knowledge available in the provided context. + - Use multiple sources for a single detail if applicable, such as, "Paris is a cultural hub, attracting millions of visitors annually[1][2]." + - Always prioritize credibility and accuracy by linking all statements back to their respective context sources. + - Avoid citing unsupported assumptions or personal interpretations; if no source supports a statement, clearly indicate the limitation. + + ### Special Instructions + - If the query involves technical, historical, or complex topics, provide detailed background and explanatory sections to ensure clarity. + - If the user provides vague input or if relevant information is missing, explain what additional details might help refine the search. + - If no relevant information is found, say: "Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?" Be transparent about limitations and suggest alternatives or ways to reframe the query. + - You are set on focus mode 'Academic', this means you will be searching for academic papers and articles on the web. + + ### Example Output + - Begin with a brief introduction summarizing the event or query topic. + - Follow with detailed sections under clear headings, covering all aspects of the query if possible. + - Provide explanations or historical context as needed to enhance understanding. + - End with a conclusion or overall perspective if relevant. + + + {context} + + + Current date & time in ISO format (UTC timezone) is: {date}. +`; diff --git a/src/prompts/index.ts b/src/prompts/index.ts new file mode 100644 index 0000000..f479185 --- /dev/null +++ b/src/prompts/index.ts @@ -0,0 +1,32 @@ +import { + academicSearchResponsePrompt, + academicSearchRetrieverPrompt, +} from './academicSearch'; +import { + redditSearchResponsePrompt, + redditSearchRetrieverPrompt, +} from './redditSearch'; +import { webSearchResponsePrompt, webSearchRetrieverPrompt } from './webSearch'; +import { + wolframAlphaSearchResponsePrompt, + wolframAlphaSearchRetrieverPrompt, +} from './wolframAlpha'; +import { writingAssistantPrompt } from './writingAssistant'; +import { + youtubeSearchResponsePrompt, + youtubeSearchRetrieverPrompt, +} from './youtubeSearch'; + +export default { + webSearchResponsePrompt, + webSearchRetrieverPrompt, + academicSearchResponsePrompt, + academicSearchRetrieverPrompt, + redditSearchResponsePrompt, + redditSearchRetrieverPrompt, + wolframAlphaSearchResponsePrompt, + wolframAlphaSearchRetrieverPrompt, + writingAssistantPrompt, + youtubeSearchResponsePrompt, + youtubeSearchRetrieverPrompt, +}; diff --git a/src/prompts/redditSearch.ts b/src/prompts/redditSearch.ts new file mode 100644 index 0000000..fc71957 --- /dev/null +++ b/src/prompts/redditSearch.ts @@ -0,0 +1,65 @@ +export const redditSearchRetrieverPrompt = ` +You will be given a conversation below and a follow up question. You need to rephrase the follow-up question if needed so it is a standalone question that can be used by the LLM to search the web for information. +If it is a writing task or a simple hi, hello rather than a question, you need to return \`not_needed\` as the response. + +Example: +1. Follow up question: Which company is most likely to create an AGI +Rephrased: Which company is most likely to create an AGI + +2. Follow up question: Is Earth flat? +Rephrased: Is Earth flat? + +3. Follow up question: Is there life on Mars? +Rephrased: Is there life on Mars? + +Conversation: +{chat_history} + +Follow up question: {query} +Rephrased question: +`; + +export const redditSearchResponsePrompt = ` + You are Perplexica, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses. + + Your task is to provide answers that are: + - **Informative and relevant**: Thoroughly address the user's query using the given context. + - **Well-structured**: Include clear headings and subheadings, and use a professional tone to present information concisely and logically. + - **Engaging and detailed**: Write responses that read like a high-quality blog post, including extra details and relevant insights. + - **Cited and credible**: Use inline citations with [number] notation to refer to the context source(s) for each fact or detail included. + - **Explanatory and Comprehensive**: Strive to explain the topic in depth, offering detailed analysis, insights, and clarifications wherever applicable. + + ### Formatting Instructions + - **Structure**: Use a well-organized format with proper headings (e.g., "## Example heading 1" or "## Example heading 2"). Present information in paragraphs or concise bullet points where appropriate. + - **Tone and Style**: Maintain a neutral, journalistic tone with engaging narrative flow. Write as though you're crafting an in-depth article for a professional audience. + - **Markdown Usage**: Format your response with Markdown for clarity. Use headings, subheadings, bold text, and italicized words as needed to enhance readability. + - **Length and Depth**: Provide comprehensive coverage of the topic. Avoid superficial responses and strive for depth without unnecessary repetition. Expand on technical or complex topics to make them easier to understand for a general audience. + - **No main heading/title**: Start your response directly with the introduction unless asked to provide a specific title. + - **Conclusion or Summary**: Include a concluding paragraph that synthesizes the provided information or suggests potential next steps, where appropriate. + + ### Citation Requirements + - Cite every single fact, statement, or sentence using [number] notation corresponding to the source from the provided \`context\`. + - Integrate citations naturally at the end of sentences or clauses as appropriate. For example, "The Eiffel Tower is one of the most visited landmarks in the world[1]." + - Ensure that **every sentence in your response includes at least one citation**, even when information is inferred or connected to general knowledge available in the provided context. + - Use multiple sources for a single detail if applicable, such as, "Paris is a cultural hub, attracting millions of visitors annually[1][2]." + - Always prioritize credibility and accuracy by linking all statements back to their respective context sources. + - Avoid citing unsupported assumptions or personal interpretations; if no source supports a statement, clearly indicate the limitation. + + ### Special Instructions + - If the query involves technical, historical, or complex topics, provide detailed background and explanatory sections to ensure clarity. + - If the user provides vague input or if relevant information is missing, explain what additional details might help refine the search. + - If no relevant information is found, say: "Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?" Be transparent about limitations and suggest alternatives or ways to reframe the query. + - You are set on focus mode 'Reddit', this means you will be searching for information, opinions and discussions on the web using Reddit. + + ### Example Output + - Begin with a brief introduction summarizing the event or query topic. + - Follow with detailed sections under clear headings, covering all aspects of the query if possible. + - Provide explanations or historical context as needed to enhance understanding. + - End with a conclusion or overall perspective if relevant. + + + {context} + + + Current date & time in ISO format (UTC timezone) is: {date}. +`; diff --git a/src/prompts/webSearch.ts b/src/prompts/webSearch.ts new file mode 100644 index 0000000..d8269c8 --- /dev/null +++ b/src/prompts/webSearch.ts @@ -0,0 +1,106 @@ +export const webSearchRetrieverPrompt = ` +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. +If it is a smple writing task or a greeting (unless the greeting contains a question after it) like Hi, Hello, How are you, etc. than a question then you need to return \`not_needed\` as the response (This is because the LLM won't need to search the web for finding information on this topic). +If the user asks some question from some URL or wants you to summarize a PDF or a webpage (via URL) you need to return the links inside the \`links\` XML block and the question inside the \`question\` XML block. If the user wants to you to summarize the webpage or the PDF you need to return \`summarize\` inside the \`question\` XML block in place of a question and the link to summarize in the \`links\` XML block. +You must always return the rephrased question inside the \`question\` XML block, if there are no links in the follow-up question then don't insert a \`links\` XML block in your response. + +There are several examples attached for your reference inside the below \`examples\` XML block + + +1. Follow up question: What is the capital of France +Rephrased question:\` + +Capital of france + +\` + +2. Hi, how are you? +Rephrased question\` + +not_needed + +\` + +3. Follow up question: What is Docker? +Rephrased question: \` + +What is Docker + +\` + +4. Follow up question: Can you tell me what is X from https://example.com +Rephrased question: \` + +Can you tell me what is X? + + + +https://example.com + +\` + +5. Follow up question: Summarize the content from https://example.com +Rephrased question: \` + +summarize + + + +https://example.com + +\` + + +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. + + +{chat_history} + + +Follow up question: {query} +Rephrased question: +`; + +export const webSearchResponsePrompt = ` + You are Perplexica, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses. + + Your task is to provide answers that are: + - **Informative and relevant**: Thoroughly address the user's query using the given context. + - **Well-structured**: Include clear headings and subheadings, and use a professional tone to present information concisely and logically. + - **Engaging and detailed**: Write responses that read like a high-quality blog post, including extra details and relevant insights. + - **Cited and credible**: Use inline citations with [number] notation to refer to the context source(s) for each fact or detail included. + - **Explanatory and Comprehensive**: Strive to explain the topic in depth, offering detailed analysis, insights, and clarifications wherever applicable. + + ### Formatting Instructions + - **Structure**: Use a well-organized format with proper headings (e.g., "## Example heading 1" or "## Example heading 2"). Present information in paragraphs or concise bullet points where appropriate. + - **Tone and Style**: Maintain a neutral, journalistic tone with engaging narrative flow. Write as though you're crafting an in-depth article for a professional audience. + - **Markdown Usage**: Format your response with Markdown for clarity. Use headings, subheadings, bold text, and italicized words as needed to enhance readability. + - **Length and Depth**: Provide comprehensive coverage of the topic. Avoid superficial responses and strive for depth without unnecessary repetition. Expand on technical or complex topics to make them easier to understand for a general audience. + - **No main heading/title**: Start your response directly with the introduction unless asked to provide a specific title. + - **Conclusion or Summary**: Include a concluding paragraph that synthesizes the provided information or suggests potential next steps, where appropriate. + + ### Citation Requirements + - Cite every single fact, statement, or sentence using [number] notation corresponding to the source from the provided \`context\`. + - Integrate citations naturally at the end of sentences or clauses as appropriate. For example, "The Eiffel Tower is one of the most visited landmarks in the world[1]." + - Ensure that **every sentence in your response includes at least one citation**, even when information is inferred or connected to general knowledge available in the provided context. + - Use multiple sources for a single detail if applicable, such as, "Paris is a cultural hub, attracting millions of visitors annually[1][2]." + - Always prioritize credibility and accuracy by linking all statements back to their respective context sources. + - Avoid citing unsupported assumptions or personal interpretations; if no source supports a statement, clearly indicate the limitation. + + ### Special Instructions + - If the query involves technical, historical, or complex topics, provide detailed background and explanatory sections to ensure clarity. + - If the user provides vague input or if relevant information is missing, explain what additional details might help refine the search. + - If no relevant information is found, say: "Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?" Be transparent about limitations and suggest alternatives or ways to reframe the query. + + ### Example Output + - Begin with a brief introduction summarizing the event or query topic. + - Follow with detailed sections under clear headings, covering all aspects of the query if possible. + - Provide explanations or historical context as needed to enhance understanding. + - End with a conclusion or overall perspective if relevant. + + + {context} + + + Current date & time in ISO format (UTC timezone) is: {date}. +`; diff --git a/src/prompts/wolframAlpha.ts b/src/prompts/wolframAlpha.ts new file mode 100644 index 0000000..40410c1 --- /dev/null +++ b/src/prompts/wolframAlpha.ts @@ -0,0 +1,65 @@ +export const wolframAlphaSearchRetrieverPrompt = ` +You will be given a conversation below and a follow up question. You need to rephrase the follow-up question if needed so it is a standalone question that can be used by the LLM to search the web for information. +If it is a writing task or a simple hi, hello rather than a question, you need to return \`not_needed\` as the response. + +Example: +1. Follow up question: What is the atomic radius of S? +Rephrased: Atomic radius of S + +2. Follow up question: What is linear algebra? +Rephrased: Linear algebra + +3. Follow up question: What is the third law of thermodynamics? +Rephrased: Third law of thermodynamics + +Conversation: +{chat_history} + +Follow up question: {query} +Rephrased question: +`; + +export const wolframAlphaSearchResponsePrompt = ` + You are Perplexica, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses. + + Your task is to provide answers that are: + - **Informative and relevant**: Thoroughly address the user's query using the given context. + - **Well-structured**: Include clear headings and subheadings, and use a professional tone to present information concisely and logically. + - **Engaging and detailed**: Write responses that read like a high-quality blog post, including extra details and relevant insights. + - **Cited and credible**: Use inline citations with [number] notation to refer to the context source(s) for each fact or detail included. + - **Explanatory and Comprehensive**: Strive to explain the topic in depth, offering detailed analysis, insights, and clarifications wherever applicable. + + ### Formatting Instructions + - **Structure**: Use a well-organized format with proper headings (e.g., "## Example heading 1" or "## Example heading 2"). Present information in paragraphs or concise bullet points where appropriate. + - **Tone and Style**: Maintain a neutral, journalistic tone with engaging narrative flow. Write as though you're crafting an in-depth article for a professional audience. + - **Markdown Usage**: Format your response with Markdown for clarity. Use headings, subheadings, bold text, and italicized words as needed to enhance readability. + - **Length and Depth**: Provide comprehensive coverage of the topic. Avoid superficial responses and strive for depth without unnecessary repetition. Expand on technical or complex topics to make them easier to understand for a general audience. + - **No main heading/title**: Start your response directly with the introduction unless asked to provide a specific title. + - **Conclusion or Summary**: Include a concluding paragraph that synthesizes the provided information or suggests potential next steps, where appropriate. + + ### Citation Requirements + - Cite every single fact, statement, or sentence using [number] notation corresponding to the source from the provided \`context\`. + - Integrate citations naturally at the end of sentences or clauses as appropriate. For example, "The Eiffel Tower is one of the most visited landmarks in the world[1]." + - Ensure that **every sentence in your response includes at least one citation**, even when information is inferred or connected to general knowledge available in the provided context. + - Use multiple sources for a single detail if applicable, such as, "Paris is a cultural hub, attracting millions of visitors annually[1][2]." + - Always prioritize credibility and accuracy by linking all statements back to their respective context sources. + - Avoid citing unsupported assumptions or personal interpretations; if no source supports a statement, clearly indicate the limitation. + + ### Special Instructions + - If the query involves technical, historical, or complex topics, provide detailed background and explanatory sections to ensure clarity. + - If the user provides vague input or if relevant information is missing, explain what additional details might help refine the search. + - If no relevant information is found, say: "Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?" Be transparent about limitations and suggest alternatives or ways to reframe the query. + - You are set on focus mode 'Wolfram Alpha', this means you will be searching for information on the web using Wolfram Alpha. It is a computational knowledge engine that can answer factual queries and perform computations. + + ### Example Output + - Begin with a brief introduction summarizing the event or query topic. + - Follow with detailed sections under clear headings, covering all aspects of the query if possible. + - Provide explanations or historical context as needed to enhance understanding. + - End with a conclusion or overall perspective if relevant. + + + {context} + + + Current date & time in ISO format (UTC timezone) is: {date}. +`; diff --git a/src/prompts/writingAssistant.ts b/src/prompts/writingAssistant.ts new file mode 100644 index 0000000..f56bf47 --- /dev/null +++ b/src/prompts/writingAssistant.ts @@ -0,0 +1,13 @@ +export const writingAssistantPrompt = ` +You are Perplexica, an AI model who is expert at searching the web and answering user's queries. You are currently set on focus mode 'Writing Assistant', this means you will be helping the user write a response to a given query. +Since you are a writing assistant, you would not perform web searches. If you think you lack information to answer the query, you can ask the user for more information or suggest them to switch to a different focus mode. +You will be shared a context that can contain information from files user has uploaded to get answers from. You will have to generate answers upon that. + +You have to cite the answer using [number] notation. You must cite the sentences with their relevent context number. You must cite each and every part of the answer so the user can know where the information is coming from. +Place these citations at the end of that particular sentence. You can cite the same sentence multiple times if it is relevant to the user's query like [number1][number2]. +However you do not need to cite it using the same number. You can use different numbers to cite the same sentence multiple times. The number refers to the number of the search result (passed in the context) used to generate that part of the answer. + + +{context} + +`; diff --git a/src/prompts/youtubeSearch.ts b/src/prompts/youtubeSearch.ts new file mode 100644 index 0000000..5805b54 --- /dev/null +++ b/src/prompts/youtubeSearch.ts @@ -0,0 +1,65 @@ +export const youtubeSearchRetrieverPrompt = ` +You will be given a conversation below and a follow up question. You need to rephrase the follow-up question if needed so it is a standalone question that can be used by the LLM to search the web for information. +If it is a writing task or a simple hi, hello rather than a question, you need to return \`not_needed\` as the response. + +Example: +1. Follow up question: How does an A.C work? +Rephrased: A.C working + +2. Follow up question: Linear algebra explanation video +Rephrased: What is linear algebra? + +3. Follow up question: What is theory of relativity? +Rephrased: What is theory of relativity? + +Conversation: +{chat_history} + +Follow up question: {query} +Rephrased question: +`; + +export const youtubeSearchResponsePrompt = ` + You are Perplexica, an AI model skilled in web search and crafting detailed, engaging, and well-structured answers. You excel at summarizing web pages and extracting relevant information to create professional, blog-style responses. + + Your task is to provide answers that are: + - **Informative and relevant**: Thoroughly address the user's query using the given context. + - **Well-structured**: Include clear headings and subheadings, and use a professional tone to present information concisely and logically. + - **Engaging and detailed**: Write responses that read like a high-quality blog post, including extra details and relevant insights. + - **Cited and credible**: Use inline citations with [number] notation to refer to the context source(s) for each fact or detail included. + - **Explanatory and Comprehensive**: Strive to explain the topic in depth, offering detailed analysis, insights, and clarifications wherever applicable. + + ### Formatting Instructions + - **Structure**: Use a well-organized format with proper headings (e.g., "## Example heading 1" or "## Example heading 2"). Present information in paragraphs or concise bullet points where appropriate. + - **Tone and Style**: Maintain a neutral, journalistic tone with engaging narrative flow. Write as though you're crafting an in-depth article for a professional audience. + - **Markdown Usage**: Format your response with Markdown for clarity. Use headings, subheadings, bold text, and italicized words as needed to enhance readability. + - **Length and Depth**: Provide comprehensive coverage of the topic. Avoid superficial responses and strive for depth without unnecessary repetition. Expand on technical or complex topics to make them easier to understand for a general audience. + - **No main heading/title**: Start your response directly with the introduction unless asked to provide a specific title. + - **Conclusion or Summary**: Include a concluding paragraph that synthesizes the provided information or suggests potential next steps, where appropriate. + + ### Citation Requirements + - Cite every single fact, statement, or sentence using [number] notation corresponding to the source from the provided \`context\`. + - Integrate citations naturally at the end of sentences or clauses as appropriate. For example, "The Eiffel Tower is one of the most visited landmarks in the world[1]." + - Ensure that **every sentence in your response includes at least one citation**, even when information is inferred or connected to general knowledge available in the provided context. + - Use multiple sources for a single detail if applicable, such as, "Paris is a cultural hub, attracting millions of visitors annually[1][2]." + - Always prioritize credibility and accuracy by linking all statements back to their respective context sources. + - Avoid citing unsupported assumptions or personal interpretations; if no source supports a statement, clearly indicate the limitation. + + ### Special Instructions + - If the query involves technical, historical, or complex topics, provide detailed background and explanatory sections to ensure clarity. + - If the user provides vague input or if relevant information is missing, explain what additional details might help refine the search. + - If no relevant information is found, say: "Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?" Be transparent about limitations and suggest alternatives or ways to reframe the query. + - You are set on focus mode 'Youtube', this means you will be searching for videos on the web using Youtube and providing information based on the video's transcrip + + ### Example Output + - Begin with a brief introduction summarizing the event or query topic. + - Follow with detailed sections under clear headings, covering all aspects of the query if possible. + - Provide explanations or historical context as needed to enhance understanding. + - End with a conclusion or overall perspective if relevant. + + + {context} + + + Current date & time in ISO format (UTC timezone) is: {date}. +`; diff --git a/src/routes/chats.ts b/src/routes/chats.ts new file mode 100644 index 0000000..afa74f9 --- /dev/null +++ b/src/routes/chats.ts @@ -0,0 +1,66 @@ +import express from 'express'; +import logger from '../utils/logger'; +import db from '../db/index'; +import { eq } from 'drizzle-orm'; +import { chats, messages } from '../db/schema'; + +const router = express.Router(); + +router.get('/', async (_, res) => { + try { + let chats = await db.query.chats.findMany(); + + chats = chats.reverse(); + + return res.status(200).json({ chats: chats }); + } catch (err) { + res.status(500).json({ message: 'An error has occurred.' }); + logger.error(`Error in getting chats: ${err.message}`); + } +}); + +router.get('/:id', async (req, res) => { + try { + const chatExists = await db.query.chats.findFirst({ + where: eq(chats.id, req.params.id), + }); + + if (!chatExists) { + return res.status(404).json({ message: 'Chat not found' }); + } + + const chatMessages = await db.query.messages.findMany({ + where: eq(messages.chatId, req.params.id), + }); + + return res.status(200).json({ chat: chatExists, messages: chatMessages }); + } catch (err) { + res.status(500).json({ message: 'An error has occurred.' }); + logger.error(`Error in getting chat: ${err.message}`); + } +}); + +router.delete(`/:id`, async (req, res) => { + try { + const chatExists = await db.query.chats.findFirst({ + where: eq(chats.id, req.params.id), + }); + + if (!chatExists) { + return res.status(404).json({ message: 'Chat not found' }); + } + + await db.delete(chats).where(eq(chats.id, req.params.id)).execute(); + await db + .delete(messages) + .where(eq(messages.chatId, req.params.id)) + .execute(); + + return res.status(200).json({ message: 'Chat deleted successfully' }); + } catch (err) { + res.status(500).json({ message: 'An error has occurred.' }); + logger.error(`Error in deleting chat: ${err.message}`); + } +}); + +export default router; diff --git a/src/routes/config.ts b/src/routes/config.ts index bf13b63..6ff80c6 100644 --- a/src/routes/config.ts +++ b/src/routes/config.ts @@ -6,40 +6,60 @@ import { import { getGroqApiKey, getOllamaApiEndpoint, + getAnthropicApiKey, + getGeminiApiKey, getOpenaiApiKey, updateConfig, } from '../config'; +import logger from '../utils/logger'; const router = express.Router(); router.get('/', async (_, res) => { - const config = {}; + try { + const config = {}; - const [chatModelProviders, embeddingModelProviders] = await Promise.all([ - getAvailableChatModelProviders(), - getAvailableEmbeddingModelProviders(), - ]); + const [chatModelProviders, embeddingModelProviders] = await Promise.all([ + getAvailableChatModelProviders(), + getAvailableEmbeddingModelProviders(), + ]); - config['chatModelProviders'] = {}; - config['embeddingModelProviders'] = {}; + config['chatModelProviders'] = {}; + config['embeddingModelProviders'] = {}; - for (const provider in chatModelProviders) { - config['chatModelProviders'][provider] = Object.keys( - chatModelProviders[provider], - ); + 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(); + config['geminiApiKey'] = getGeminiApiKey(); + + res.status(200).json(config); + } catch (err: any) { + res.status(500).json({ message: 'An error has occurred.' }); + logger.error(`Error getting config: ${err.message}`); } - - for (const provider in embeddingModelProviders) { - config['embeddingModelProviders'][provider] = Object.keys( - embeddingModelProviders[provider], - ); - } - - config['openaiApiKey'] = getOpenaiApiKey(); - config['ollamaApiUrl'] = getOllamaApiEndpoint(); - config['groqApiKey'] = getGroqApiKey(); - - res.status(200).json(config); }); router.post('/', async (req, res) => { @@ -49,6 +69,8 @@ router.post('/', async (req, res) => { API_KEYS: { OPENAI: config.openaiApiKey, GROQ: config.groqApiKey, + ANTHROPIC: config.anthropicApiKey, + GEMINI: config.geminiApiKey, }, API_ENDPOINTS: { OLLAMA: config.ollamaApiUrl, diff --git a/src/routes/discover.ts b/src/routes/discover.ts new file mode 100644 index 0000000..b6f8ff9 --- /dev/null +++ b/src/routes/discover.ts @@ -0,0 +1,48 @@ +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; diff --git a/src/routes/images.ts b/src/routes/images.ts index 6bd43d3..efa095a 100644 --- a/src/routes/images.ts +++ b/src/routes/images.ts @@ -1,17 +1,31 @@ import express from 'express'; -import handleImageSearch from '../agents/imageSearchAgent'; +import handleImageSearch from '../chains/imageSearchAgent'; import { BaseChatModel } from '@langchain/core/language_models/chat_models'; import { getAvailableChatModelProviders } from '../lib/providers'; import { HumanMessage, AIMessage } from '@langchain/core/messages'; import logger from '../utils/logger'; +import { ChatOpenAI } from '@langchain/openai'; 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) => { try { - let { query, chat_history, chat_model_provider, chat_model } = req.body; + let body: ImageSearchBody = req.body; - chat_history = chat_history.map((msg: any) => { + const chatHistory = body.chatHistory.map((msg: any) => { if (msg.role === 'user') { return new HumanMessage(msg.content); } else if (msg.role === 'assistant') { @@ -19,22 +33,50 @@ router.post('/', async (req, res) => { } }); - const chatModels = await getAvailableChatModelProviders(); - const provider = chat_model_provider ?? Object.keys(chatModels)[0]; - const chatModel = chat_model ?? Object.keys(chatModels[provider])[0]; + const chatModelProviders = await getAvailableChatModelProviders(); + + const chatModelProvider = + body.chatModel?.provider || Object.keys(chatModelProviders)[0]; + const chatModel = + body.chatModel?.model || + Object.keys(chatModelProviders[chatModelProvider])[0]; let llm: BaseChatModel | undefined; - if (chatModels[provider] && chatModels[provider][chatModel]) { - llm = chatModels[provider][chatModel] as BaseChatModel | undefined; + if (body.chatModel?.provider === 'custom_openai') { + if ( + !body.chatModel?.customOpenAIBaseURL || + !body.chatModel?.customOpenAIKey + ) { + return res + .status(400) + .json({ message: 'Missing custom OpenAI base URL or key' }); + } + + llm = new ChatOpenAI({ + modelName: 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) { - res.status(500).json({ message: 'Invalid LLM model selected' }); - return; + return res.status(400).json({ message: 'Invalid model selected' }); } - const images = await handleImageSearch({ query, chat_history }, llm); + const images = await handleImageSearch( + { query: body.query, chat_history: chatHistory }, + llm, + ); res.status(200).json({ images }); } catch (err) { diff --git a/src/routes/index.ts b/src/routes/index.ts index 257e677..cb2c915 100644 --- a/src/routes/index.ts +++ b/src/routes/index.ts @@ -4,6 +4,10 @@ import videosRouter from './videos'; import configRouter from './config'; import modelsRouter from './models'; import suggestionsRouter from './suggestions'; +import chatsRouter from './chats'; +import searchRouter from './search'; +import discoverRouter from './discover'; +import uploadsRouter from './uploads'; const router = express.Router(); @@ -12,5 +16,9 @@ router.use('/videos', videosRouter); router.use('/config', configRouter); router.use('/models', modelsRouter); router.use('/suggestions', suggestionsRouter); +router.use('/chats', chatsRouter); +router.use('/search', searchRouter); +router.use('/discover', discoverRouter); +router.use('/uploads', uploadsRouter); export default router; diff --git a/src/routes/models.ts b/src/routes/models.ts index 36df25a..b5fbe12 100644 --- a/src/routes/models.ts +++ b/src/routes/models.ts @@ -14,6 +14,18 @@ router.get('/', async (req, res) => { getAvailableEmbeddingModelProviders(), ]); + Object.keys(chatModelProviders).forEach((provider) => { + Object.keys(chatModelProviders[provider]).forEach((model) => { + delete chatModelProviders[provider][model].model; + }); + }); + + Object.keys(embeddingModelProviders).forEach((provider) => { + Object.keys(embeddingModelProviders[provider]).forEach((model) => { + delete embeddingModelProviders[provider][model].model; + }); + }); + res.status(200).json({ chatModelProviders, embeddingModelProviders }); } catch (err) { res.status(500).json({ message: 'An error has occurred.' }); diff --git a/src/routes/search.ts b/src/routes/search.ts new file mode 100644 index 0000000..e24b3f9 --- /dev/null +++ b/src/routes/search.ts @@ -0,0 +1,160 @@ +import express from 'express'; +import logger from '../utils/logger'; +import type { BaseChatModel } from '@langchain/core/language_models/chat_models'; +import type { Embeddings } from '@langchain/core/embeddings'; +import { ChatOpenAI } from '@langchain/openai'; +import { + getAvailableChatModelProviders, + getAvailableEmbeddingModelProviders, +} from '../lib/providers'; +import { searchHandlers } from '../websocket/messageHandler'; +import { AIMessage, BaseMessage, HumanMessage } from '@langchain/core/messages'; +import { MetaSearchAgentType } from '../search/metaSearchAgent'; + +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: MetaSearchAgentType = searchHandlers[body.focusMode]; + + if (!searchHandler) { + return res.status(400).json({ message: 'Invalid focus mode' }); + } + + const emitter = await searchHandler.searchAndAnswer( + body.query, + history, + llm, + embeddings, + body.optimizationMode, + [], + ); + + let message = ''; + let sources = []; + + emitter.on('data', (data) => { + const parsedData = JSON.parse(data); + if (parsedData.type === 'response') { + message += parsedData.data; + } else if (parsedData.type === 'sources') { + sources = parsedData.data; + } + }); + + emitter.on('end', () => { + 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; diff --git a/src/routes/suggestions.ts b/src/routes/suggestions.ts index b15ff5f..1d46e5b 100644 --- a/src/routes/suggestions.ts +++ b/src/routes/suggestions.ts @@ -1,17 +1,30 @@ import express from 'express'; -import generateSuggestions from '../agents/suggestionGeneratorAgent'; +import generateSuggestions from '../chains/suggestionGeneratorAgent'; import { BaseChatModel } from '@langchain/core/language_models/chat_models'; import { getAvailableChatModelProviders } from '../lib/providers'; import { HumanMessage, AIMessage } from '@langchain/core/messages'; import logger from '../utils/logger'; +import { ChatOpenAI } from '@langchain/openai'; 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) => { try { - let { chat_history, chat_model, chat_model_provider } = req.body; + let body: SuggestionsBody = req.body; - chat_history = chat_history.map((msg: any) => { + const chatHistory = body.chatHistory.map((msg: any) => { if (msg.role === 'user') { return new HumanMessage(msg.content); } else if (msg.role === 'assistant') { @@ -19,22 +32,50 @@ router.post('/', async (req, res) => { } }); - const chatModels = await getAvailableChatModelProviders(); - const provider = chat_model_provider ?? Object.keys(chatModels)[0]; - const chatModel = chat_model ?? Object.keys(chatModels[provider])[0]; + const chatModelProviders = await getAvailableChatModelProviders(); + + const chatModelProvider = + body.chatModel?.provider || Object.keys(chatModelProviders)[0]; + const chatModel = + body.chatModel?.model || + Object.keys(chatModelProviders[chatModelProvider])[0]; let llm: BaseChatModel | undefined; - if (chatModels[provider] && chatModels[provider][chatModel]) { - llm = chatModels[provider][chatModel] as BaseChatModel | undefined; + if (body.chatModel?.provider === 'custom_openai') { + if ( + !body.chatModel?.customOpenAIBaseURL || + !body.chatModel?.customOpenAIKey + ) { + return res + .status(400) + .json({ message: 'Missing custom OpenAI base URL or key' }); + } + + llm = new ChatOpenAI({ + modelName: 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) { - res.status(500).json({ message: 'Invalid LLM model selected' }); - return; + return res.status(400).json({ message: 'Invalid model selected' }); } - const suggestions = await generateSuggestions({ chat_history }, llm); + const suggestions = await generateSuggestions( + { chat_history: chatHistory }, + llm, + ); res.status(200).json({ suggestions: suggestions }); } catch (err) { diff --git a/src/routes/uploads.ts b/src/routes/uploads.ts new file mode 100644 index 0000000..7b063fc --- /dev/null +++ b/src/routes/uploads.ts @@ -0,0 +1,151 @@ +import express from 'express'; +import logger from '../utils/logger'; +import multer from 'multer'; +import path from 'path'; +import crypto from 'crypto'; +import fs from 'fs'; +import { Embeddings } from '@langchain/core/embeddings'; +import { getAvailableEmbeddingModelProviders } from '../lib/providers'; +import { PDFLoader } from '@langchain/community/document_loaders/fs/pdf'; +import { DocxLoader } from '@langchain/community/document_loaders/fs/docx'; +import { RecursiveCharacterTextSplitter } from '@langchain/textsplitters'; +import { Document } from 'langchain/document'; + +const router = express.Router(); + +const splitter = new RecursiveCharacterTextSplitter({ + chunkSize: 500, + chunkOverlap: 100, +}); + +const storage = multer.diskStorage({ + destination: (req, file, cb) => { + cb(null, path.join(process.cwd(), './uploads')); + }, + filename: (req, file, cb) => { + const splitedFileName = file.originalname.split('.'); + const fileExtension = splitedFileName[splitedFileName.length - 1]; + if (!['pdf', 'docx', 'txt'].includes(fileExtension)) { + return cb(new Error('File type is not supported'), ''); + } + cb(null, `${crypto.randomBytes(16).toString('hex')}.${fileExtension}`); + }, +}); + +const upload = multer({ storage }); + +router.post( + '/', + upload.fields([ + { name: 'files' }, + { name: 'embedding_model', maxCount: 1 }, + { name: 'embedding_model_provider', maxCount: 1 }, + ]), + async (req, res) => { + try { + const { embedding_model, embedding_model_provider } = req.body; + + if (!embedding_model || !embedding_model_provider) { + res + .status(400) + .json({ message: 'Missing embedding model or provider' }); + return; + } + + const embeddingModels = await getAvailableEmbeddingModelProviders(); + const provider = + embedding_model_provider ?? Object.keys(embeddingModels)[0]; + const embeddingModel: Embeddings = + embedding_model ?? Object.keys(embeddingModels[provider])[0]; + + let embeddingsModel: Embeddings | undefined; + + if ( + embeddingModels[provider] && + embeddingModels[provider][embeddingModel] + ) { + embeddingsModel = embeddingModels[provider][embeddingModel].model as + | Embeddings + | undefined; + } + + if (!embeddingsModel) { + res.status(400).json({ message: 'Invalid LLM model selected' }); + return; + } + + const files = req.files['files'] as Express.Multer.File[]; + if (!files || files.length === 0) { + res.status(400).json({ message: 'No files uploaded' }); + return; + } + + await Promise.all( + files.map(async (file) => { + let docs: Document[] = []; + + if (file.mimetype === 'application/pdf') { + const loader = new PDFLoader(file.path); + docs = await loader.load(); + } else if ( + file.mimetype === + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + ) { + const loader = new DocxLoader(file.path); + docs = await loader.load(); + } else if (file.mimetype === 'text/plain') { + const text = fs.readFileSync(file.path, 'utf-8'); + docs = [ + new Document({ + pageContent: text, + metadata: { + title: file.originalname, + }, + }), + ]; + } + + const splitted = await splitter.splitDocuments(docs); + + const json = JSON.stringify({ + title: file.originalname, + contents: splitted.map((doc) => doc.pageContent), + }); + + const pathToSave = file.path.replace(/\.\w+$/, '-extracted.json'); + fs.writeFileSync(pathToSave, json); + + const embeddings = await embeddingsModel.embedDocuments( + splitted.map((doc) => doc.pageContent), + ); + + const embeddingsJSON = JSON.stringify({ + title: file.originalname, + embeddings: embeddings, + }); + + const pathToSaveEmbeddings = file.path.replace( + /\.\w+$/, + '-embeddings.json', + ); + fs.writeFileSync(pathToSaveEmbeddings, embeddingsJSON); + }), + ); + + res.status(200).json({ + files: files.map((file) => { + return { + fileName: file.originalname, + fileExtension: file.filename.split('.').pop(), + fileId: file.filename.replace(/\.\w+$/, ''), + }; + }), + }); + } catch (err: any) { + logger.error(`Error in uploading file results: ${err.message}`); + res.status(500).json({ message: 'An error has occurred.' }); + } + }, +); + +export default router; diff --git a/src/routes/videos.ts b/src/routes/videos.ts index 0ffdb2c..ad87460 100644 --- a/src/routes/videos.ts +++ b/src/routes/videos.ts @@ -3,15 +3,29 @@ import { BaseChatModel } from '@langchain/core/language_models/chat_models'; import { getAvailableChatModelProviders } from '../lib/providers'; import { HumanMessage, AIMessage } from '@langchain/core/messages'; import logger from '../utils/logger'; -import handleVideoSearch from '../agents/videoSearchAgent'; +import handleVideoSearch from '../chains/videoSearchAgent'; +import { ChatOpenAI } from '@langchain/openai'; 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) => { try { - let { query, chat_history, chat_model_provider, chat_model } = req.body; + let body: VideoSearchBody = req.body; - chat_history = chat_history.map((msg: any) => { + const chatHistory = body.chatHistory.map((msg: any) => { if (msg.role === 'user') { return new HumanMessage(msg.content); } else if (msg.role === 'assistant') { @@ -19,22 +33,50 @@ router.post('/', async (req, res) => { } }); - const chatModels = await getAvailableChatModelProviders(); - const provider = chat_model_provider ?? Object.keys(chatModels)[0]; - const chatModel = chat_model ?? Object.keys(chatModels[provider])[0]; + const chatModelProviders = await getAvailableChatModelProviders(); + + const chatModelProvider = + body.chatModel?.provider || Object.keys(chatModelProviders)[0]; + const chatModel = + body.chatModel?.model || + Object.keys(chatModelProviders[chatModelProvider])[0]; let llm: BaseChatModel | undefined; - if (chatModels[provider] && chatModels[provider][chatModel]) { - llm = chatModels[provider][chatModel] as BaseChatModel | undefined; + if (body.chatModel?.provider === 'custom_openai') { + if ( + !body.chatModel?.customOpenAIBaseURL || + !body.chatModel?.customOpenAIKey + ) { + return res + .status(400) + .json({ message: 'Missing custom OpenAI base URL or key' }); + } + + llm = new ChatOpenAI({ + modelName: 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) { - res.status(500).json({ message: 'Invalid LLM model selected' }); - return; + return res.status(400).json({ message: 'Invalid model selected' }); } - const videos = await handleVideoSearch({ chat_history, query }, llm); + const videos = await handleVideoSearch( + { chat_history: chatHistory, query: body.query }, + llm, + ); res.status(200).json({ videos }); } catch (err) { diff --git a/src/search/metaSearchAgent.ts b/src/search/metaSearchAgent.ts new file mode 100644 index 0000000..ee82c10 --- /dev/null +++ b/src/search/metaSearchAgent.ts @@ -0,0 +1,494 @@ +import { ChatOpenAI } from '@langchain/openai'; +import type { BaseChatModel } from '@langchain/core/language_models/chat_models'; +import type { Embeddings } from '@langchain/core/embeddings'; +import { + ChatPromptTemplate, + MessagesPlaceholder, + PromptTemplate, +} from '@langchain/core/prompts'; +import { + RunnableLambda, + RunnableMap, + RunnableSequence, +} from '@langchain/core/runnables'; +import { BaseMessage } from '@langchain/core/messages'; +import { StringOutputParser } from '@langchain/core/output_parsers'; +import LineListOutputParser from '../lib/outputParsers/listLineOutputParser'; +import LineOutputParser from '../lib/outputParsers/lineOutputParser'; +import { getDocumentsFromLinks } from '../utils/documents'; +import { Document } from 'langchain/document'; +import { searchSearxng } from '../lib/searxng'; +import path from 'path'; +import fs from 'fs'; +import computeSimilarity from '../utils/computeSimilarity'; +import formatChatHistoryAsString from '../utils/formatHistory'; +import eventEmitter from 'events'; +import { StreamEvent } from '@langchain/core/tracers/log_stream'; +import { IterableReadableStream } from '@langchain/core/utils/stream'; + +export interface MetaSearchAgentType { + searchAndAnswer: ( + message: string, + history: BaseMessage[], + llm: BaseChatModel, + embeddings: Embeddings, + optimizationMode: 'speed' | 'balanced' | 'quality', + fileIds: string[], + ) => Promise; +} + +interface Config { + searchWeb: boolean; + rerank: boolean; + summarizer: boolean; + rerankThreshold: number; + queryGeneratorPrompt: string; + responsePrompt: string; + activeEngines: string[]; +} + +type BasicChainInput = { + chat_history: BaseMessage[]; + query: string; +}; + +class MetaSearchAgent implements MetaSearchAgentType { + private config: Config; + private strParser = new StringOutputParser(); + + constructor(config: Config) { + this.config = config; + } + + private async createSearchRetrieverChain(llm: BaseChatModel) { + (llm as unknown as ChatOpenAI).temperature = 0; + + return RunnableSequence.from([ + PromptTemplate.fromTemplate(this.config.queryGeneratorPrompt), + llm, + this.strParser, + RunnableLambda.from(async (input: string) => { + const linksOutputParser = new LineListOutputParser({ + key: 'links', + }); + + const questionOutputParser = new LineOutputParser({ + key: 'question', + }); + + const links = await linksOutputParser.parse(input); + let question = this.config.summarizer + ? await questionOutputParser.parse(input) + : input; + + if (question === 'not_needed') { + return { query: '', docs: [] }; + } + + if (links.length > 0) { + if (question.length === 0) { + question = 'summarize'; + } + + let docs = []; + + const linkDocs = await getDocumentsFromLinks({ links }); + + const docGroups: Document[] = []; + + linkDocs.map((doc) => { + const URLDocExists = docGroups.find( + (d) => + d.metadata.url === doc.metadata.url && + d.metadata.totalDocs < 10, + ); + + if (!URLDocExists) { + docGroups.push({ + ...doc, + metadata: { + ...doc.metadata, + totalDocs: 1, + }, + }); + } + + const docIndex = docGroups.findIndex( + (d) => + d.metadata.url === doc.metadata.url && + d.metadata.totalDocs < 10, + ); + + if (docIndex !== -1) { + docGroups[docIndex].pageContent = + docGroups[docIndex].pageContent + `\n\n` + doc.pageContent; + docGroups[docIndex].metadata.totalDocs += 1; + } + }); + + await Promise.all( + docGroups.map(async (doc) => { + const res = await llm.invoke(` + You are a web search summarizer, tasked with summarizing a piece of text retrieved from a web search. Your job is to summarize the + text into a detailed, 2-4 paragraph explanation that captures the main ideas and provides a comprehensive answer to the query. + If the query is \"summarize\", you should provide a detailed summary of the text. If the query is a specific question, you should answer it in the summary. + + - **Journalistic tone**: The summary should sound professional and journalistic, not too casual or vague. + - **Thorough and detailed**: Ensure that every key point from the text is captured and that the summary directly answers the query. + - **Not too lengthy, but detailed**: The summary should be informative but not excessively long. Focus on providing detailed information in a concise format. + + The text will be shared inside the \`text\` XML tag, and the query inside the \`query\` XML tag. + + + 1. \` + 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. + + + + What is Docker and how does it work? + + + 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. \` + 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. + + + + summarize + + + 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. + \` + + + Everything below is the actual data you will be working with. Good luck! + + + ${question} + + + + ${doc.pageContent} + + + Make sure to answer the query in the summary. + `); + + const document = new Document({ + pageContent: res.content as string, + metadata: { + title: doc.metadata.title, + url: doc.metadata.url, + }, + }); + + docs.push(document); + }), + ); + + return { query: question, docs: docs }; + } else { + const res = await searchSearxng(question, { + language: 'en', + engines: this.config.activeEngines, + }); + + const documents = res.results.map( + (result) => + new Document({ + pageContent: + result.content || + (this.config.activeEngines.includes('youtube') + ? result.title + : '') /* Todo: Implement transcript grabbing using Youtubei (source: https://www.npmjs.com/package/youtubei) */, + metadata: { + title: result.title, + url: result.url, + ...(result.img_src && { img_src: result.img_src }), + }, + }), + ); + + return { query: question, docs: documents }; + } + }), + ]); + } + + private async createAnsweringChain( + llm: BaseChatModel, + fileIds: string[], + embeddings: Embeddings, + optimizationMode: 'speed' | 'balanced' | 'quality', + ) { + return RunnableSequence.from([ + RunnableMap.from({ + query: (input: BasicChainInput) => input.query, + chat_history: (input: BasicChainInput) => input.chat_history, + date: () => new Date().toISOString(), + context: RunnableLambda.from(async (input: BasicChainInput) => { + const processedHistory = formatChatHistoryAsString( + input.chat_history, + ); + + let docs: Document[] | null = null; + let query = input.query; + + if (this.config.searchWeb) { + const searchRetrieverChain = + await this.createSearchRetrieverChain(llm); + + const searchRetrieverResult = await searchRetrieverChain.invoke({ + chat_history: processedHistory, + query, + }); + + query = searchRetrieverResult.query; + docs = searchRetrieverResult.docs; + } + + const sortedDocs = await this.rerankDocs( + query, + docs ?? [], + fileIds, + embeddings, + optimizationMode, + ); + + return sortedDocs; + }) + .withConfig({ + runName: 'FinalSourceRetriever', + }) + .pipe(this.processDocs), + }), + ChatPromptTemplate.fromMessages([ + ['system', this.config.responsePrompt], + new MessagesPlaceholder('chat_history'), + ['user', '{query}'], + ]), + llm, + this.strParser, + ]).withConfig({ + runName: 'FinalResponseGenerator', + }); + } + + private async rerankDocs( + query: string, + docs: Document[], + fileIds: string[], + embeddings: Embeddings, + optimizationMode: 'speed' | 'balanced' | 'quality', + ) { + if (docs.length === 0 && fileIds.length === 0) { + return docs; + } + + const filesData = fileIds + .map((file) => { + const filePath = path.join(process.cwd(), 'uploads', file); + + const contentPath = filePath + '-extracted.json'; + const embeddingsPath = filePath + '-embeddings.json'; + + const content = JSON.parse(fs.readFileSync(contentPath, 'utf8')); + const embeddings = JSON.parse(fs.readFileSync(embeddingsPath, 'utf8')); + + const fileSimilaritySearchObject = content.contents.map( + (c: string, i) => { + return { + fileName: content.title, + content: c, + embeddings: embeddings.embeddings[i], + }; + }, + ); + + return fileSimilaritySearchObject; + }) + .flat(); + + if (query.toLocaleLowerCase() === 'summarize') { + return docs.slice(0, 15); + } + + const docsWithContent = docs.filter( + (doc) => doc.pageContent && doc.pageContent.length > 0, + ); + + if (optimizationMode === 'speed' || this.config.rerank === false) { + if (filesData.length > 0) { + const [queryEmbedding] = await Promise.all([ + embeddings.embedQuery(query), + ]); + + const fileDocs = filesData.map((fileData) => { + return new Document({ + pageContent: fileData.content, + metadata: { + title: fileData.fileName, + url: `File`, + }, + }); + }); + + const similarity = filesData.map((fileData, i) => { + const sim = computeSimilarity(queryEmbedding, fileData.embeddings); + + return { + index: i, + similarity: sim, + }; + }); + + let sortedDocs = similarity + .filter( + (sim) => sim.similarity > (this.config.rerankThreshold ?? 0.3), + ) + .sort((a, b) => b.similarity - a.similarity) + .slice(0, 15) + .map((sim) => fileDocs[sim.index]); + + sortedDocs = + docsWithContent.length > 0 ? sortedDocs.slice(0, 8) : sortedDocs; + + return [ + ...sortedDocs, + ...docsWithContent.slice(0, 15 - sortedDocs.length), + ]; + } else { + return docsWithContent.slice(0, 15); + } + } else if (optimizationMode === 'balanced') { + const [docEmbeddings, queryEmbedding] = await Promise.all([ + embeddings.embedDocuments( + docsWithContent.map((doc) => doc.pageContent), + ), + embeddings.embedQuery(query), + ]); + + docsWithContent.push( + ...filesData.map((fileData) => { + return new Document({ + pageContent: fileData.content, + metadata: { + title: fileData.fileName, + url: `File`, + }, + }); + }), + ); + + docEmbeddings.push(...filesData.map((fileData) => fileData.embeddings)); + + const similarity = docEmbeddings.map((docEmbedding, i) => { + const sim = computeSimilarity(queryEmbedding, docEmbedding); + + return { + index: i, + similarity: sim, + }; + }); + + const sortedDocs = similarity + .filter((sim) => sim.similarity > (this.config.rerankThreshold ?? 0.3)) + .sort((a, b) => b.similarity - a.similarity) + .slice(0, 15) + .map((sim) => docsWithContent[sim.index]); + + return sortedDocs; + } + } + + private processDocs(docs: Document[]) { + return docs + .map( + (_, index) => + `${index + 1}. ${docs[index].metadata.title} ${docs[index].pageContent}`, + ) + .join('\n'); + } + + private async handleStream( + stream: IterableReadableStream, + emitter: eventEmitter, + ) { + for await (const event of stream) { + if ( + event.event === 'on_chain_end' && + event.name === 'FinalSourceRetriever' + ) { + ``; + emitter.emit( + 'data', + JSON.stringify({ type: 'sources', data: event.data.output }), + ); + } + if ( + event.event === 'on_chain_stream' && + event.name === 'FinalResponseGenerator' + ) { + emitter.emit( + 'data', + JSON.stringify({ type: 'response', data: event.data.chunk }), + ); + } + if ( + event.event === 'on_chain_end' && + event.name === 'FinalResponseGenerator' + ) { + emitter.emit('end'); + } + } + } + + async searchAndAnswer( + message: string, + history: BaseMessage[], + llm: BaseChatModel, + embeddings: Embeddings, + optimizationMode: 'speed' | 'balanced' | 'quality', + fileIds: string[], + ) { + const emitter = new eventEmitter(); + + const answeringChain = await this.createAnsweringChain( + llm, + fileIds, + embeddings, + optimizationMode, + ); + + const stream = answeringChain.streamEvents( + { + chat_history: history, + query: message, + }, + { + version: 'v1', + }, + ); + + this.handleStream(stream, emitter); + + return emitter; + } +} + +export default MetaSearchAgent; diff --git a/src/utils/documents.ts b/src/utils/documents.ts new file mode 100644 index 0000000..5cd0366 --- /dev/null +++ b/src/utils/documents.ts @@ -0,0 +1,99 @@ +import axios from 'axios'; +import { htmlToText } from 'html-to-text'; +import { RecursiveCharacterTextSplitter } from 'langchain/text_splitter'; +import { Document } from '@langchain/core/documents'; +import pdfParse from 'pdf-parse'; +import logger from './logger'; + +export const getDocumentsFromLinks = async ({ links }: { links: string[] }) => { + const splitter = new RecursiveCharacterTextSplitter(); + + let docs: Document[] = []; + + await Promise.all( + links.map(async (link) => { + link = + link.startsWith('http://') || link.startsWith('https://') + ? link + : `https://${link}`; + + try { + const res = await axios.get(link, { + responseType: 'arraybuffer', + }); + + const isPdf = res.headers['content-type'] === 'application/pdf'; + + if (isPdf) { + const pdfText = await pdfParse(res.data); + 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(/\s+/g, ' ') + .trim(); + + const splittedText = await splitter.splitText(parsedText); + const title = res.data + .toString('utf8') + .match(/(.*?)<\/title>/)?.[1]; + + const linkDocs = splittedText.map((text) => { + return new Document({ + pageContent: text, + metadata: { + title: title || link, + url: link, + }, + }); + }); + + docs.push(...linkDocs); + } catch (err) { + 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, + }, + }), + ); + } + }), + ); + + return docs; +}; diff --git a/src/utils/files.ts b/src/utils/files.ts new file mode 100644 index 0000000..e6e91df --- /dev/null +++ b/src/utils/files.ts @@ -0,0 +1,17 @@ +import path from 'path'; +import fs from 'fs'; + +export const getFileDetails = (fileId: string) => { + const fileLoc = path.join( + process.cwd(), + './uploads', + fileId + '-extracted.json', + ); + + const parsedFile = JSON.parse(fs.readFileSync(fileLoc, 'utf8')); + + return { + name: parsedFile.title, + fileId: fileId, + }; +}; diff --git a/src/websocket/connectionManager.ts b/src/websocket/connectionManager.ts index 5cb075b..d980500 100644 --- a/src/websocket/connectionManager.ts +++ b/src/websocket/connectionManager.ts @@ -45,9 +45,8 @@ export const handleConnection = async ( chatModelProviders[chatModelProvider][chatModel] && chatModelProvider != 'custom_openai' ) { - llm = chatModelProviders[chatModelProvider][chatModel] as - | BaseChatModel - | undefined; + llm = chatModelProviders[chatModelProvider][chatModel] + .model as unknown as BaseChatModel | undefined; } else if (chatModelProvider == 'custom_openai') { llm = new ChatOpenAI({ modelName: chatModel, @@ -56,7 +55,7 @@ export const handleConnection = async ( configuration: { baseURL: searchParams.get('openAIBaseURL'), }, - }); + }) as unknown as BaseChatModel; } if ( @@ -65,7 +64,7 @@ export const handleConnection = async ( ) { embeddings = embeddingModelProviders[embeddingModelProvider][ embeddingModel - ] as Embeddings | undefined; + ].model as Embeddings | undefined; } if (!llm || !embeddings) { @@ -79,6 +78,18 @@ export const handleConnection = async ( ws.close(); } + const interval = setInterval(() => { + if (ws.readyState === ws.OPEN) { + ws.send( + JSON.stringify({ + type: 'signal', + data: 'open', + }), + ); + clearInterval(interval); + } + }, 5); + ws.on( 'message', async (message) => diff --git a/src/websocket/messageHandler.ts b/src/websocket/messageHandler.ts index 98f67c2..395c0de 100644 --- a/src/websocket/messageHandler.ts +++ b/src/websocket/messageHandler.ts @@ -1,37 +1,99 @@ import { EventEmitter, WebSocket } from 'ws'; import { BaseMessage, AIMessage, HumanMessage } from '@langchain/core/messages'; -import handleWebSearch from '../agents/webSearchAgent'; -import handleAcademicSearch from '../agents/academicSearchAgent'; -import handleWritingAssistant from '../agents/writingAssistant'; -import handleWolframAlphaSearch from '../agents/wolframAlphaSearchAgent'; -import handleYoutubeSearch from '../agents/youtubeSearchAgent'; -import handleRedditSearch from '../agents/redditSearchAgent'; import type { BaseChatModel } from '@langchain/core/language_models/chat_models'; import type { Embeddings } from '@langchain/core/embeddings'; import logger from '../utils/logger'; +import db from '../db'; +import { chats, messages as messagesSchema } from '../db/schema'; +import { eq, asc, gt, and } from 'drizzle-orm'; +import crypto from 'crypto'; +import { getFileDetails } from '../utils/files'; +import MetaSearchAgent, { + MetaSearchAgentType, +} from '../search/metaSearchAgent'; +import prompts from '../prompts'; type Message = { - type: string; + messageId: string; + chatId: string; content: string; - copilot: boolean; - focusMode: string; - history: Array<[string, string]>; }; -const searchHandlers = { - webSearch: handleWebSearch, - academicSearch: handleAcademicSearch, - writingAssistant: handleWritingAssistant, - wolframAlphaSearch: handleWolframAlphaSearch, - youtubeSearch: handleYoutubeSearch, - redditSearch: handleRedditSearch, +type WSMessage = { + message: Message; + optimizationMode: 'speed' | 'balanced' | 'quality'; + type: string; + focusMode: string; + history: Array<[string, string]>; + files: Array<string>; +}; + +export const searchHandlers = { + webSearch: new MetaSearchAgent({ + activeEngines: [], + queryGeneratorPrompt: prompts.webSearchRetrieverPrompt, + responsePrompt: prompts.webSearchResponsePrompt, + rerank: true, + rerankThreshold: 0.3, + searchWeb: true, + summarizer: true, + }), + academicSearch: new MetaSearchAgent({ + activeEngines: ['arxiv', 'google scholar', 'pubmed'], + queryGeneratorPrompt: prompts.academicSearchRetrieverPrompt, + responsePrompt: prompts.academicSearchResponsePrompt, + rerank: true, + rerankThreshold: 0, + searchWeb: true, + summarizer: false, + }), + writingAssistant: new MetaSearchAgent({ + activeEngines: [], + queryGeneratorPrompt: '', + responsePrompt: prompts.writingAssistantPrompt, + rerank: true, + rerankThreshold: 0, + searchWeb: false, + summarizer: false, + }), + wolframAlphaSearch: new MetaSearchAgent({ + activeEngines: ['wolframalpha'], + queryGeneratorPrompt: prompts.wolframAlphaSearchRetrieverPrompt, + responsePrompt: prompts.wolframAlphaSearchResponsePrompt, + rerank: false, + rerankThreshold: 0, + searchWeb: true, + summarizer: false, + }), + youtubeSearch: new MetaSearchAgent({ + activeEngines: ['youtube'], + queryGeneratorPrompt: prompts.youtubeSearchRetrieverPrompt, + responsePrompt: prompts.youtubeSearchResponsePrompt, + rerank: true, + rerankThreshold: 0.3, + searchWeb: true, + summarizer: false, + }), + redditSearch: new MetaSearchAgent({ + activeEngines: ['reddit'], + queryGeneratorPrompt: prompts.redditSearchRetrieverPrompt, + responsePrompt: prompts.redditSearchResponsePrompt, + rerank: true, + rerankThreshold: 0.3, + searchWeb: true, + summarizer: false, + }), }; const handleEmitterEvents = ( emitter: EventEmitter, ws: WebSocket, - id: string, + messageId: string, + chatId: string, ) => { + let recievedMessage = ''; + let sources = []; + emitter.on('data', (data) => { const parsedData = JSON.parse(data); if (parsedData.type === 'response') { @@ -39,21 +101,36 @@ const handleEmitterEvents = ( JSON.stringify({ type: 'message', data: parsedData.data, - messageId: id, + messageId: messageId, }), ); + recievedMessage += parsedData.data; } else if (parsedData.type === 'sources') { ws.send( JSON.stringify({ type: 'sources', data: parsedData.data, - messageId: id, + messageId: messageId, }), ); + sources = parsedData.data; } }); emitter.on('end', () => { - ws.send(JSON.stringify({ type: 'messageEnd', messageId: id })); + ws.send(JSON.stringify({ type: 'messageEnd', messageId: messageId })); + + db.insert(messagesSchema) + .values({ + content: recievedMessage, + chatId: chatId, + messageId: messageId, + role: 'assistant', + metadata: JSON.stringify({ + createdAt: new Date(), + ...(sources && sources.length > 0 && { sources }), + }), + }) + .execute(); }); emitter.on('error', (data) => { const parsedData = JSON.parse(data); @@ -74,8 +151,17 @@ export const handleMessage = async ( embeddings: Embeddings, ) => { try { - const parsedMessage = JSON.parse(message) as Message; - const id = Math.random().toString(36).substring(7); + const parsedWSMessage = JSON.parse(message) as WSMessage; + const parsedMessage = parsedWSMessage.message; + + if (parsedWSMessage.files.length > 0) { + /* TODO: Implement uploads in other classes/single meta class system*/ + parsedWSMessage.focusMode = 'webSearch'; + } + + const humanMessageId = + parsedMessage.messageId ?? crypto.randomBytes(7).toString('hex'); + const aiMessageId = crypto.randomBytes(7).toString('hex'); if (!parsedMessage.content) return ws.send( @@ -86,7 +172,7 @@ export const handleMessage = async ( }), ); - const history: BaseMessage[] = parsedMessage.history.map((msg) => { + const history: BaseMessage[] = parsedWSMessage.history.map((msg) => { if (msg[0] === 'human') { return new HumanMessage({ content: msg[1], @@ -98,16 +184,71 @@ export const handleMessage = async ( } }); - if (parsedMessage.type === 'message') { - const handler = searchHandlers[parsedMessage.focusMode]; + if (parsedWSMessage.type === 'message') { + const handler: MetaSearchAgentType = + searchHandlers[parsedWSMessage.focusMode]; + if (handler) { - const emitter = handler( - parsedMessage.content, - history, - llm, - embeddings, - ); - handleEmitterEvents(emitter, ws, id); + try { + const emitter = await handler.searchAndAnswer( + parsedMessage.content, + history, + llm, + embeddings, + parsedWSMessage.optimizationMode, + parsedWSMessage.files, + ); + + handleEmitterEvents(emitter, ws, aiMessageId, 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, + files: parsedWSMessage.files.map(getFileDetails), + }) + .execute(); + } + + const messageExists = await db.query.messages.findFirst({ + where: eq(messagesSchema.messageId, humanMessageId), + }); + + if (!messageExists) { + await db + .insert(messagesSchema) + .values({ + content: parsedMessage.content, + chatId: parsedMessage.chatId, + messageId: humanMessageId, + role: 'user', + metadata: JSON.stringify({ + createdAt: new Date(), + }), + }) + .execute(); + } else { + await db + .delete(messagesSchema) + .where( + and( + gt(messagesSchema.id, messageExists.id), + eq(messagesSchema.chatId, parsedMessage.chatId), + ), + ) + .execute(); + } + } catch (err) { + console.log(err); + } } else { ws.send( JSON.stringify({ diff --git a/ui/app/c/[chatId]/page.tsx b/ui/app/c/[chatId]/page.tsx new file mode 100644 index 0000000..dc3c92a --- /dev/null +++ b/ui/app/c/[chatId]/page.tsx @@ -0,0 +1,7 @@ +import ChatWindow from '@/components/ChatWindow'; + +const Page = ({ params }: { params: { chatId: string } }) => { + return <ChatWindow id={params.chatId} />; +}; + +export default Page; diff --git a/ui/app/discover/page.tsx b/ui/app/discover/page.tsx index a443a17..eb94040 100644 --- a/ui/app/discover/page.tsx +++ b/ui/app/discover/page.tsx @@ -1,5 +1,113 @@ +'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 = () => { - return <div>page</div>; + 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" + target="_blank" + > + <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; diff --git a/ui/app/layout.tsx b/ui/app/layout.tsx index b3f5005..684a99c 100644 --- a/ui/app/layout.tsx +++ b/ui/app/layout.tsx @@ -4,6 +4,7 @@ import './globals.css'; import { cn } from '@/lib/utils'; import Sidebar from '@/components/Sidebar'; import { Toaster } from 'sonner'; +import ThemeProvider from '@/components/theme/Provider'; const montserrat = Montserrat({ weight: ['300', '400', '500', '700'], @@ -24,18 +25,20 @@ export default function RootLayout({ children: React.ReactNode; }>) { return ( - <html className="h-full" lang="en"> + <html className="h-full" lang="en" suppressHydrationWarning> <body className={cn('h-full', montserrat.className)}> - <Sidebar>{children}</Sidebar> - <Toaster - toastOptions={{ - unstyled: true, - classNames: { - toast: - 'bg-[#111111] text-white rounded-lg p-4 flex flex-row items-center space-x-2', - }, - }} - /> + <ThemeProvider> + <Sidebar>{children}</Sidebar> + <Toaster + toastOptions={{ + unstyled: true, + classNames: { + toast: + 'bg-light-primary dark:bg-dark-secondary dark:text-white/70 text-black-70 rounded-lg p-4 flex flex-row items-center space-x-2', + }, + }} + /> + </ThemeProvider> </body> </html> ); diff --git a/ui/app/library/layout.tsx b/ui/app/library/layout.tsx new file mode 100644 index 0000000..00d4a3b --- /dev/null +++ b/ui/app/library/layout.tsx @@ -0,0 +1,12 @@ +import { Metadata } from 'next'; +import React from 'react'; + +export const metadata: Metadata = { + title: 'Library - Perplexica', +}; + +const Layout = ({ children }: { children: React.ReactNode }) => { + return <div>{children}</div>; +}; + +export default Layout; diff --git a/ui/app/library/page.tsx b/ui/app/library/page.tsx new file mode 100644 index 0000000..379596c --- /dev/null +++ b/ui/app/library/page.tsx @@ -0,0 +1,114 @@ +'use client'; + +import DeleteChat from '@/components/DeleteChat'; +import { cn, formatTimeDifference } from '@/lib/utils'; +import { BookOpenText, ClockIcon, Delete, ScanEye } from 'lucide-react'; +import Link from 'next/link'; +import { useEffect, useState } from 'react'; + +export interface Chat { + id: string; + title: string; + createdAt: string; + focusMode: string; +} + +const Page = () => { + const [chats, setChats] = useState<Chat[]>([]); + const [loading, setLoading] = useState(true); + + useEffect(() => { + const fetchChats = async () => { + setLoading(true); + + const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/chats`, { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + }, + }); + + const data = await res.json(); + + setChats(data.chats); + setLoading(false); + }; + + fetchChats(); + }, []); + + 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"> + <BookOpenText /> + <h1 className="text-3xl font-medium p-2">Library</h1> + </div> + <hr className="border-t border-[#2B2C2C] my-4 w-full" /> + </div> + {chats.length === 0 && ( + <div className="flex flex-row items-center justify-center min-h-screen"> + <p className="text-black/70 dark:text-white/70 text-sm"> + No chats found. + </p> + </div> + )} + {chats.length > 0 && ( + <div className="flex flex-col pb-20 lg:pb-2"> + {chats.map((chat, i) => ( + <div + className={cn( + 'flex flex-col space-y-4 py-6', + i !== chats.length - 1 + ? 'border-b border-white-200 dark:border-dark-200' + : '', + )} + key={i} + > + <Link + href={`/c/${chat.id}`} + className="text-black dark:text-white lg:text-xl font-medium truncate transition duration-200 hover:text-[#24A0ED] dark:hover:text-[#24A0ED] cursor-pointer" + > + {chat.title} + </Link> + <div className="flex flex-row items-center justify-between w-full"> + <div className="flex flex-row items-center space-x-1 lg:space-x-1.5 text-black/70 dark:text-white/70"> + <ClockIcon size={15} /> + <p className="text-xs"> + {formatTimeDifference(new Date(), chat.createdAt)} Ago + </p> + </div> + <DeleteChat + chatId={chat.id} + chats={chats} + setChats={setChats} + /> + </div> + </div> + ))} + </div> + )} + </div> + ); +}; + +export default Page; diff --git a/ui/components/Chat.tsx b/ui/components/Chat.tsx index 7b0c1b3..81aa32f 100644 --- a/ui/components/Chat.tsx +++ b/ui/components/Chat.tsx @@ -2,7 +2,7 @@ import { Fragment, useEffect, useRef, useState } from 'react'; import MessageInput from './MessageInput'; -import { Message } from './ChatWindow'; +import { File, Message } from './ChatWindow'; import MessageBox from './MessageBox'; import MessageBoxLoading from './MessageBoxLoading'; @@ -12,12 +12,20 @@ const Chat = ({ sendMessage, messageAppeared, rewrite, + fileIds, + setFileIds, + files, + setFiles, }: { messages: Message[]; sendMessage: (message: string) => void; loading: boolean; messageAppeared: boolean; rewrite: (messageId: string) => void; + fileIds: string[]; + setFileIds: (fileIds: string[]) => void; + files: File[]; + setFiles: (files: File[]) => void; }) => { const [dividerWidth, setDividerWidth] = useState(0); const dividerRef = useRef<HTMLDivElement | null>(null); @@ -53,7 +61,7 @@ const Chat = ({ const isLast = i === messages.length - 1; return ( - <Fragment key={msg.id}> + <Fragment key={msg.messageId}> <MessageBox key={i} message={msg} @@ -66,7 +74,7 @@ const Chat = ({ sendMessage={sendMessage} /> {!isLast && msg.role === 'assistant' && ( - <div className="h-px w-full bg-[#1C1C1C]" /> + <div className="h-px w-full bg-light-secondary dark:bg-dark-secondary" /> )} </Fragment> ); @@ -78,7 +86,14 @@ const Chat = ({ className="bottom-24 lg:bottom-10 fixed z-40" style={{ width: dividerWidth }} > - <MessageInput loading={loading} sendMessage={sendMessage} /> + <MessageInput + loading={loading} + sendMessage={sendMessage} + fileIds={fileIds} + setFileIds={setFileIds} + files={files} + setFiles={setFiles} + /> </div> )} </div> diff --git a/ui/components/ChatWindow.tsx b/ui/components/ChatWindow.tsx index 5f266b5..b26573f 100644 --- a/ui/components/ChatWindow.tsx +++ b/ui/components/ChatWindow.tsx @@ -5,12 +5,17 @@ import { Document } from '@langchain/core/documents'; import Navbar from './Navbar'; import Chat from './Chat'; import EmptyChat from './EmptyChat'; +import crypto from 'crypto'; import { toast } from 'sonner'; import { useSearchParams } from 'next/navigation'; import { getSuggestions } from '@/lib/actions'; +import { Settings } from 'lucide-react'; +import SettingsDialog from './SettingsDialog'; +import NextError from 'next/error'; export type Message = { - id: string; + messageId: string; + chatId: string; createdAt: Date; content: string; role: 'user' | 'assistant'; @@ -18,18 +23,64 @@ export type Message = { sources?: Document[]; }; -const useSocket = (url: string, setIsReady: (ready: boolean) => void) => { - const [ws, setWs] = useState<WebSocket | null>(null); +export interface File { + fileName: string; + fileExtension: string; + fileId: string; +} + +const useSocket = ( + url: string, + setIsWSReady: (ready: boolean) => void, + setError: (error: boolean) => void, +) => { + const wsRef = useRef<WebSocket | null>(null); + const reconnectTimeoutRef = useRef<NodeJS.Timeout>(); + const retryCountRef = useRef(0); + const isCleaningUpRef = useRef(false); + const MAX_RETRIES = 3; + const INITIAL_BACKOFF = 1000; // 1 second + + const getBackoffDelay = (retryCount: number) => { + return Math.min(INITIAL_BACKOFF * Math.pow(2, retryCount), 10000); // Cap at 10 seconds + }; useEffect(() => { - if (!ws) { - const connectWs = async () => { + const connectWs = async () => { + if (wsRef.current?.readyState === WebSocket.OPEN) { + wsRef.current.close(); + } + + try { let chatModel = localStorage.getItem('chatModel'); let chatModelProvider = localStorage.getItem('chatModelProvider'); let embeddingModel = localStorage.getItem('embeddingModel'); let embeddingModelProvider = localStorage.getItem( 'embeddingModelProvider', ); + let openAIBaseURL = + chatModelProvider === 'custom_openai' + ? localStorage.getItem('openAIBaseURL') + : null; + let openAIPIKey = + chatModelProvider === 'custom_openai' + ? localStorage.getItem('openAIApiKey') + : null; + + const providers = await fetch( + `${process.env.NEXT_PUBLIC_API_URL}/models`, + { + headers: { + 'Content-Type': 'application/json', + }, + }, + ).then(async (res) => { + if (!res.ok) + throw new Error( + `Failed to fetch models: ${res.status} ${res.statusText}`, + ); + return res.json(); + }); if ( !chatModel || @@ -37,37 +88,43 @@ const useSocket = (url: string, setIsReady: (ready: boolean) => void) => { !embeddingModel || !embeddingModelProvider ) { - const providers = await fetch( - `${process.env.NEXT_PUBLIC_API_URL}/models`, - { - headers: { - 'Content-Type': 'application/json', - }, - }, - ).then(async (res) => await res.json()); + if (!chatModel || !chatModelProvider) { + const chatModelProviders = providers.chatModelProviders; - const chatModelProviders = providers.chatModelProviders; - const embeddingModelProviders = providers.embeddingModelProviders; + chatModelProvider = + chatModelProvider || Object.keys(chatModelProviders)[0]; - if ( - !chatModelProviders || - Object.keys(chatModelProviders).length === 0 - ) - return toast.error('No chat models available'); + if (chatModelProvider === 'custom_openai') { + toast.error( + 'Seems like you are using the custom OpenAI provider, please open the settings and enter a model name to use.', + ); + setError(true); + return; + } else { + chatModel = Object.keys(chatModelProviders[chatModelProvider])[0]; - if ( - !embeddingModelProviders || - Object.keys(embeddingModelProviders).length === 0 - ) - return toast.error('No embedding models available'); + if ( + !chatModelProviders || + Object.keys(chatModelProviders).length === 0 + ) + return toast.error('No chat models available'); + } + } - chatModelProvider = Object.keys(chatModelProviders)[0]; - chatModel = Object.keys(chatModelProviders[chatModelProvider])[0]; + if (!embeddingModel || !embeddingModelProvider) { + const embeddingModelProviders = providers.embeddingModelProviders; - embeddingModelProvider = Object.keys(embeddingModelProviders)[0]; - embeddingModel = Object.keys( - embeddingModelProviders[embeddingModelProvider], - )[0]; + if ( + !embeddingModelProviders || + Object.keys(embeddingModelProviders).length === 0 + ) + return toast.error('No embedding models available'); + + embeddingModelProvider = Object.keys(embeddingModelProviders)[0]; + embeddingModel = Object.keys( + embeddingModelProviders[embeddingModelProvider], + )[0]; + } localStorage.setItem('chatModel', chatModel!); localStorage.setItem('chatModelProvider', chatModelProvider); @@ -76,6 +133,71 @@ const useSocket = (url: string, setIsReady: (ready: boolean) => void) => { 'embeddingModelProvider', embeddingModelProvider, ); + } else { + const chatModelProviders = providers.chatModelProviders; + const embeddingModelProviders = providers.embeddingModelProviders; + + if ( + Object.keys(chatModelProviders).length > 0 && + (((!openAIBaseURL || !openAIPIKey) && + chatModelProvider === 'custom_openai') || + !chatModelProviders[chatModelProvider]) + ) { + const chatModelProvidersKeys = Object.keys(chatModelProviders); + chatModelProvider = + chatModelProvidersKeys.find( + (key) => Object.keys(chatModelProviders[key]).length > 0, + ) || chatModelProvidersKeys[0]; + + if ( + chatModelProvider === 'custom_openai' && + (!openAIBaseURL || !openAIPIKey) + ) { + toast.error( + 'Seems like you are using the custom OpenAI provider, please open the settings and configure the API key and base URL', + ); + setError(true); + return; + } + + localStorage.setItem('chatModelProvider', chatModelProvider); + } + + if ( + chatModelProvider && + (!openAIBaseURL || !openAIPIKey) && + !chatModelProviders[chatModelProvider][chatModel] + ) { + chatModel = Object.keys( + chatModelProviders[ + Object.keys(chatModelProviders[chatModelProvider]).length > 0 + ? chatModelProvider + : Object.keys(chatModelProviders)[0] + ], + )[0]; + localStorage.setItem('chatModel', chatModel); + } + + if ( + Object.keys(embeddingModelProviders).length > 0 && + !embeddingModelProviders[embeddingModelProvider] + ) { + embeddingModelProvider = Object.keys(embeddingModelProviders)[0]; + localStorage.setItem( + 'embeddingModelProvider', + embeddingModelProvider, + ); + } + + if ( + embeddingModelProvider && + !embeddingModelProviders[embeddingModelProvider][embeddingModel] + ) { + embeddingModel = Object.keys( + embeddingModelProviders[embeddingModelProvider], + )[0]; + localStorage.setItem('embeddingModel', embeddingModel); + } } const wsURL = new URL(url); @@ -101,63 +223,257 @@ const useSocket = (url: string, setIsReady: (ready: boolean) => void) => { wsURL.search = searchParams.toString(); const ws = new WebSocket(wsURL.toString()); + wsRef.current = ws; - ws.onopen = () => { - console.log('[DEBUG] open'); + const timeoutId = setTimeout(() => { + if (ws.readyState !== 1) { + toast.error( + 'Failed to connect to the server. Please try again later.', + ); + } + }, 10000); + + ws.addEventListener('message', (e) => { + const data = JSON.parse(e.data); + if (data.type === 'signal' && data.data === 'open') { + const interval = setInterval(() => { + if (ws.readyState === 1) { + setIsWSReady(true); + setError(false); + if (retryCountRef.current > 0) { + toast.success('Connection restored.'); + } + retryCountRef.current = 0; + clearInterval(interval); + } + }, 5); + clearTimeout(timeoutId); + console.debug(new Date(), 'ws:connected'); + } + if (data.type === 'error') { + toast.error(data.data); + } + }); + + ws.onerror = () => { + clearTimeout(timeoutId); + setIsWSReady(false); + toast.error('WebSocket connection error.'); }; - const stateCheckInterval = setInterval(() => { - if (ws.readyState === 1) { - setIsReady(true); - clearInterval(stateCheckInterval); - } - }, 100); - - setWs(ws); - - ws.onmessage = (e) => { - const parsedData = JSON.parse(e.data); - if (parsedData.type === 'error') { - toast.error(parsedData.data); - if (parsedData.key === 'INVALID_MODEL_SELECTED') { - localStorage.clear(); - } + ws.onclose = () => { + clearTimeout(timeoutId); + setIsWSReady(false); + console.debug(new Date(), 'ws:disconnected'); + if (!isCleaningUpRef.current) { + toast.error('Connection lost. Attempting to reconnect...'); + attemptReconnect(); } }; - }; + } catch (error) { + console.debug(new Date(), 'ws:error', error); + setIsWSReady(false); + attemptReconnect(); + } + }; - connectWs(); - } + const attemptReconnect = () => { + retryCountRef.current += 1; + + if (retryCountRef.current > MAX_RETRIES) { + console.debug(new Date(), 'ws:max_retries'); + setError(true); + toast.error( + 'Unable to connect to server after multiple attempts. Please refresh the page to try again.', + ); + return; + } + + const backoffDelay = getBackoffDelay(retryCountRef.current); + console.debug( + new Date(), + `ws:retry attempt=${retryCountRef.current}/${MAX_RETRIES} delay=${backoffDelay}ms`, + ); + + if (reconnectTimeoutRef.current) { + clearTimeout(reconnectTimeoutRef.current); + } + + reconnectTimeoutRef.current = setTimeout(() => { + connectWs(); + }, backoffDelay); + }; + + connectWs(); return () => { - ws?.close(); - console.log('[DEBUG] closed'); + if (reconnectTimeoutRef.current) { + clearTimeout(reconnectTimeoutRef.current); + } + if (wsRef.current?.readyState === WebSocket.OPEN) { + wsRef.current.close(); + isCleaningUpRef.current = true; + console.debug(new Date(), 'ws:cleanup'); + } }; - }, [ws, url, setIsReady]); + }, [url, setIsWSReady, setError]); - return ws; + return wsRef.current; }; -const ChatWindow = () => { +const loadMessages = async ( + chatId: string, + setMessages: (messages: Message[]) => void, + setIsMessagesLoaded: (loaded: boolean) => void, + setChatHistory: (history: [string, string][]) => void, + setFocusMode: (mode: string) => void, + setNotFound: (notFound: boolean) => void, + setFiles: (files: File[]) => void, + setFileIds: (fileIds: string[]) => void, +) => { + const res = await fetch( + `${process.env.NEXT_PUBLIC_API_URL}/chats/${chatId}`, + { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + }, + }, + ); + + if (res.status === 404) { + setNotFound(true); + setIsMessagesLoaded(true); + return; + } + + const data = await res.json(); + + const messages = data.messages.map((msg: any) => { + return { + ...msg, + ...JSON.parse(msg.metadata), + }; + }) as Message[]; + + setMessages(messages); + + const history = messages.map((msg) => { + return [msg.role, msg.content]; + }) as [string, string][]; + + console.debug(new Date(), 'app:messages_loaded'); + + document.title = messages[0].content; + + const files = data.chat.files.map((file: any) => { + return { + fileName: file.name, + fileExtension: file.name.split('.').pop(), + fileId: file.fileId, + }; + }); + + setFiles(files); + setFileIds(files.map((file: File) => file.fileId)); + + setChatHistory(history); + setFocusMode(data.chat.focusMode); + setIsMessagesLoaded(true); +}; + +const ChatWindow = ({ id }: { id?: string }) => { const searchParams = useSearchParams(); const initialMessage = searchParams.get('q'); + const [chatId, setChatId] = useState<string | undefined>(id); + const [newChatCreated, setNewChatCreated] = useState(false); + + const [hasError, setHasError] = useState(false); const [isReady, setIsReady] = useState(false); - const ws = useSocket(process.env.NEXT_PUBLIC_WS_URL!, setIsReady); + + const [isWSReady, setIsWSReady] = useState(false); + const ws = useSocket( + process.env.NEXT_PUBLIC_WS_URL!, + setIsWSReady, + setHasError, + ); + + const [loading, setLoading] = useState(false); + const [messageAppeared, setMessageAppeared] = useState(false); const [chatHistory, setChatHistory] = useState<[string, string][]>([]); const [messages, setMessages] = useState<Message[]>([]); - const messagesRef = useRef<Message[]>([]); - const [loading, setLoading] = useState(false); - const [messageAppeared, setMessageAppeared] = useState(false); + + const [files, setFiles] = useState<File[]>([]); + const [fileIds, setFileIds] = useState<string[]>([]); + const [focusMode, setFocusMode] = useState('webSearch'); + const [optimizationMode, setOptimizationMode] = useState('speed'); + + const [isMessagesLoaded, setIsMessagesLoaded] = useState(false); + + const [notFound, setNotFound] = useState(false); + + const [isSettingsOpen, setIsSettingsOpen] = useState(false); + + useEffect(() => { + if ( + chatId && + !newChatCreated && + !isMessagesLoaded && + messages.length === 0 + ) { + loadMessages( + chatId, + setMessages, + setIsMessagesLoaded, + setChatHistory, + setFocusMode, + setNotFound, + setFiles, + setFileIds, + ); + } else if (!chatId) { + setNewChatCreated(true); + setIsMessagesLoaded(true); + setChatId(crypto.randomBytes(20).toString('hex')); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + useEffect(() => { + return () => { + if (ws?.readyState === 1) { + ws.close(); + console.debug(new Date(), 'ws:cleanup'); + } + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + const messagesRef = useRef<Message[]>([]); useEffect(() => { messagesRef.current = messages; }, [messages]); - const sendMessage = async (message: string) => { + useEffect(() => { + if (isMessagesLoaded && isWSReady) { + setIsReady(true); + console.debug(new Date(), 'app:ready'); + } else { + setIsReady(false); + } + }, [isMessagesLoaded, isWSReady]); + + const sendMessage = async (message: string, messageId?: string) => { if (loading) return; + if (!ws || ws.readyState !== WebSocket.OPEN) { + toast.error('Cannot send message while disconnected'); + return; + } + setLoading(true); setMessageAppeared(false); @@ -165,11 +481,19 @@ const ChatWindow = () => { let recievedMessage = ''; let added = false; - ws?.send( + messageId = messageId ?? crypto.randomBytes(7).toString('hex'); + + ws.send( JSON.stringify({ type: 'message', - content: message, + message: { + messageId: messageId, + chatId: chatId!, + content: message, + }, + files: fileIds, focusMode: focusMode, + optimizationMode: optimizationMode, history: [...chatHistory, ['human', message]], }), ); @@ -178,7 +502,8 @@ const ChatWindow = () => { ...prevMessages, { content: message, - id: Math.random().toString(36).substring(7), + messageId: messageId, + chatId: chatId!, role: 'user', createdAt: new Date(), }, @@ -200,7 +525,8 @@ const ChatWindow = () => { ...prevMessages, { content: '', - id: data.messageId, + messageId: data.messageId, + chatId: chatId!, role: 'assistant', sources: sources, createdAt: new Date(), @@ -217,7 +543,8 @@ const ChatWindow = () => { ...prevMessages, { content: data.data, - id: data.messageId, + messageId: data.messageId, + chatId: chatId!, role: 'assistant', sources: sources, createdAt: new Date(), @@ -228,7 +555,7 @@ const ChatWindow = () => { setMessages((prev) => prev.map((message) => { - if (message.id === data.messageId) { + if (message.messageId === data.messageId) { return { ...message, content: message.content + data.data }; } @@ -261,7 +588,7 @@ const ChatWindow = () => { const suggestions = await getSuggestions(messagesRef.current); setMessages((prev) => prev.map((msg) => { - if (msg.id === lastMsg.id) { + if (msg.messageId === lastMsg.messageId) { return { ...msg, suggestions: suggestions }; } return msg; @@ -275,7 +602,7 @@ const ChatWindow = () => { }; const rewrite = (messageId: string) => { - const index = messages.findIndex((msg) => msg.id === messageId); + const index = messages.findIndex((msg) => msg.messageId === messageId); if (index === -1) return; @@ -288,52 +615,85 @@ const ChatWindow = () => { return [...prev.slice(0, messages.length > 2 ? index - 1 : 0)]; }); - sendMessage(message.content); + sendMessage(message.content, message.messageId); }; useEffect(() => { - if (isReady && initialMessage) { + if (isReady && initialMessage && ws?.readyState === 1) { sendMessage(initialMessage); } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [isReady, initialMessage]); + }, [ws?.readyState, isReady, initialMessage, isWSReady]); + + if (hasError) { + return ( + <div className="relative"> + <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"> + <p className="dark:text-white/70 text-black/70 text-sm"> + Failed to connect to the server. Please try again later. + </p> + </div> + <SettingsDialog isOpen={isSettingsOpen} setIsOpen={setIsSettingsOpen} /> + </div> + ); + } return isReady ? ( - <div> - {messages.length > 0 ? ( - <> - <Navbar messages={messages} /> - <Chat - loading={loading} - messages={messages} + notFound ? ( + <NextError statusCode={404} /> + ) : ( + <div> + {messages.length > 0 ? ( + <> + <Navbar chatId={chatId!} messages={messages} /> + <Chat + loading={loading} + messages={messages} + sendMessage={sendMessage} + messageAppeared={messageAppeared} + rewrite={rewrite} + fileIds={fileIds} + setFileIds={setFileIds} + files={files} + setFiles={setFiles} + /> + </> + ) : ( + <EmptyChat sendMessage={sendMessage} - messageAppeared={messageAppeared} - rewrite={rewrite} + focusMode={focusMode} + setFocusMode={setFocusMode} + optimizationMode={optimizationMode} + setOptimizationMode={setOptimizationMode} + fileIds={fileIds} + setFileIds={setFileIds} + files={files} + setFiles={setFiles} /> - </> - ) : ( - <EmptyChat - sendMessage={sendMessage} - focusMode={focusMode} - setFocusMode={setFocusMode} - /> - )} - </div> + )} + </div> + ) ) : ( <div className="flex flex-row items-center justify-center min-h-screen"> <svg aria-hidden="true" - className="w-8 h-8 text-[#202020] animate-spin fill-[#ffffff3b]" + 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 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" + 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.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" + 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> diff --git a/ui/components/DeleteChat.tsx b/ui/components/DeleteChat.tsx new file mode 100644 index 0000000..2857fc8 --- /dev/null +++ b/ui/components/DeleteChat.tsx @@ -0,0 +1,128 @@ +import { Trash } from 'lucide-react'; +import { + Description, + Dialog, + DialogBackdrop, + DialogPanel, + DialogTitle, + Transition, + TransitionChild, +} from '@headlessui/react'; +import { Fragment, useState } from 'react'; +import { toast } from 'sonner'; +import { Chat } from '@/app/library/page'; + +const DeleteChat = ({ + chatId, + chats, + setChats, + redirect = false, +}: { + chatId: string; + chats: Chat[]; + setChats: (chats: Chat[]) => void; + redirect?: boolean; +}) => { + const [confirmationDialogOpen, setConfirmationDialogOpen] = useState(false); + const [loading, setLoading] = useState(false); + + const handleDelete = async () => { + setLoading(true); + try { + const res = await fetch( + `${process.env.NEXT_PUBLIC_API_URL}/chats/${chatId}`, + { + method: 'DELETE', + headers: { + 'Content-Type': 'application/json', + }, + }, + ); + + if (res.status != 200) { + throw new Error('Failed to delete chat'); + } + + const newChats = chats.filter((chat) => chat.id !== chatId); + + setChats(newChats); + + if (redirect) { + window.location.href = '/'; + } + } catch (err: any) { + toast.error(err.message); + } finally { + setConfirmationDialogOpen(false); + setLoading(false); + } + }; + + return ( + <> + <button + onClick={() => { + setConfirmationDialogOpen(true); + }} + className="bg-transparent text-red-400 hover:scale-105 transition duration-200" + > + <Trash size={17} /> + </button> + <Transition appear show={confirmationDialogOpen} as={Fragment}> + <Dialog + as="div" + className="relative z-50" + onClose={() => { + if (!loading) { + setConfirmationDialogOpen(false); + } + }} + > + <DialogBackdrop className="fixed inset-0 bg-black/30" /> + <div className="fixed inset-0 overflow-y-auto"> + <div className="flex min-h-full items-center justify-center p-4 text-center"> + <TransitionChild + as={Fragment} + enter="ease-out duration-200" + enterFrom="opacity-0 scale-95" + enterTo="opacity-100 scale-100" + leave="ease-in duration-100" + leaveFrom="opacity-100 scale-200" + leaveTo="opacity-0 scale-95" + > + <DialogPanel className="w-full max-w-md transform rounded-2xl bg-light-secondary dark:bg-dark-secondary border border-light-200 dark:border-dark-200 p-6 text-left align-middle shadow-xl transition-all"> + <DialogTitle className="text-lg font-medium leading-6 dark:text-white"> + Delete Confirmation + </DialogTitle> + <Description className="text-sm dark:text-white/70 text-black/70"> + Are you sure you want to delete this chat? + </Description> + <div className="flex flex-row items-end justify-end space-x-4 mt-6"> + <button + onClick={() => { + if (!loading) { + setConfirmationDialogOpen(false); + } + }} + className="text-black/50 dark:text-white/50 text-sm hover:text-black/70 hover:dark:text-white/70 transition duration-200" + > + Cancel + </button> + <button + onClick={handleDelete} + className="text-red-400 text-sm hover:text-red-500 transition duration200" + > + Delete + </button> + </div> + </DialogPanel> + </TransitionChild> + </div> + </div> + </Dialog> + </Transition> + </> + ); +}; + +export default DeleteChat; diff --git a/ui/components/EmptyChat.tsx b/ui/components/EmptyChat.tsx index 30bb883..c47c301 100644 --- a/ui/components/EmptyChat.tsx +++ b/ui/components/EmptyChat.tsx @@ -1,24 +1,57 @@ +import { Settings } from 'lucide-react'; import EmptyChatMessageInput from './EmptyChatMessageInput'; +import SettingsDialog from './SettingsDialog'; +import { useState } from 'react'; +import { File } from './ChatWindow'; const EmptyChat = ({ sendMessage, focusMode, setFocusMode, + optimizationMode, + setOptimizationMode, + fileIds, + setFileIds, + files, + setFiles, }: { sendMessage: (message: string) => void; focusMode: string; setFocusMode: (mode: string) => void; + optimizationMode: string; + setOptimizationMode: (mode: string) => void; + fileIds: string[]; + setFileIds: (fileIds: string[]) => void; + files: File[]; + setFiles: (files: File[]) => void; }) => { + const [isSettingsOpen, setIsSettingsOpen] = useState(false); + return ( - <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-white/70 text-3xl font-medium -mt-8"> - Research begins here. - </h2> - <EmptyChatMessageInput - sendMessage={sendMessage} - focusMode={focusMode} - setFocusMode={setFocusMode} - /> + <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"> + <h2 className="text-black/70 dark:text-white/70 text-3xl font-medium -mt-8"> + Research begins here. + </h2> + <EmptyChatMessageInput + sendMessage={sendMessage} + focusMode={focusMode} + setFocusMode={setFocusMode} + optimizationMode={optimizationMode} + setOptimizationMode={setOptimizationMode} + fileIds={fileIds} + setFileIds={setFileIds} + files={files} + setFiles={setFiles} + /> + </div> </div> ); }; diff --git a/ui/components/EmptyChatMessageInput.tsx b/ui/components/EmptyChatMessageInput.tsx index 4932803..43d1e28 100644 --- a/ui/components/EmptyChatMessageInput.tsx +++ b/ui/components/EmptyChatMessageInput.tsx @@ -1,20 +1,62 @@ import { ArrowRight } from 'lucide-react'; -import { useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import TextareaAutosize from 'react-textarea-autosize'; -import { CopilotToggle, Focus } from './MessageInputActions'; +import CopilotToggle from './MessageInputActions/Copilot'; +import Focus from './MessageInputActions/Focus'; +import Optimization from './MessageInputActions/Optimization'; +import Attach from './MessageInputActions/Attach'; +import { File } from './ChatWindow'; const EmptyChatMessageInput = ({ sendMessage, focusMode, setFocusMode, + optimizationMode, + setOptimizationMode, + fileIds, + setFileIds, + files, + setFiles, }: { sendMessage: (message: string) => void; focusMode: string; setFocusMode: (mode: string) => void; + optimizationMode: string; + setOptimizationMode: (mode: string) => void; + fileIds: string[]; + setFileIds: (fileIds: string[]) => void; + files: File[]; + setFiles: (files: File[]) => void; }) => { const [copilotEnabled, setCopilotEnabled] = useState(false); const [message, setMessage] = useState(''); + const inputRef = useRef<HTMLTextAreaElement | null>(null); + + 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); + + inputRef.current?.focus(); + + return () => { + document.removeEventListener('keydown', handleKeyDown); + }; + }, []); + return ( <form onSubmit={(e) => { @@ -31,27 +73,34 @@ const EmptyChatMessageInput = ({ }} className="w-full" > - <div className="flex flex-col bg-[#111111] px-5 pt-5 pb-2 rounded-lg w-full border border-[#1C1C1C]"> + <div className="flex flex-col bg-light-secondary dark:bg-dark-secondary px-5 pt-5 pb-2 rounded-lg w-full border border-light-200 dark:border-dark-200"> <TextareaAutosize + ref={inputRef} value={message} onChange={(e) => setMessage(e.target.value)} minRows={2} - className="bg-transparent placeholder:text-white/50 text-sm text-white resize-none focus:outline-none w-full max-h-24 lg:max-h-36 xl:max-h-48" + className="bg-transparent placeholder:text-black/50 dark:placeholder:text-white/50 text-sm text-black dark:text-white resize-none focus:outline-none w-full max-h-24 lg:max-h-36 xl:max-h-48" placeholder="Ask anything..." /> <div className="flex flex-row items-center justify-between mt-4"> - <div className="flex flex-row items-center space-x-1 -mx-2"> + <div className="flex flex-row items-center space-x-2 lg:space-x-4"> <Focus focusMode={focusMode} setFocusMode={setFocusMode} /> - {/* <Attach /> */} + <Attach + fileIds={fileIds} + setFileIds={setFileIds} + files={files} + setFiles={setFiles} + showText + /> </div> - <div className="flex flex-row items-center space-x-4 -mx-2"> - <CopilotToggle - copilotEnabled={copilotEnabled} - setCopilotEnabled={setCopilotEnabled} + <div className="flex flex-row items-center space-x-1 sm:space-x-4"> + <Optimization + optimizationMode={optimizationMode} + setOptimizationMode={setOptimizationMode} /> <button disabled={message.trim().length === 0} - className="bg-[#24A0ED] text-white disabled:text-white/50 hover:bg-opacity-85 transition duration-100 disabled:bg-[#ececec21] rounded-full p-2" + className="bg-[#24A0ED] text-white disabled:text-black/50 dark:disabled:text-white/50 disabled:bg-[#e0e0dc] dark:disabled:bg-[#ececec21] hover:bg-opacity-85 transition duration-100 rounded-full p-2" > <ArrowRight className="bg-background" size={17} /> </button> diff --git a/ui/components/Layout.tsx b/ui/components/Layout.tsx index e517e00..00f0fff 100644 --- a/ui/components/Layout.tsx +++ b/ui/components/Layout.tsx @@ -1,6 +1,6 @@ const Layout = ({ children }: { children: React.ReactNode }) => { return ( - <main className="lg:pl-20 bg-[#0A0A0A] min-h-screen"> + <main className="lg:pl-20 bg-light-primary dark:bg-dark-primary min-h-screen"> <div className="max-w-screen-lg lg:mx-auto mx-4">{children}</div> </main> ); diff --git a/ui/components/MessageActions/Copy.tsx b/ui/components/MessageActions/Copy.tsx index b19d8d4..cb07b3e 100644 --- a/ui/components/MessageActions/Copy.tsx +++ b/ui/components/MessageActions/Copy.tsx @@ -19,7 +19,7 @@ const Copy = ({ setCopied(true); setTimeout(() => setCopied(false), 1000); }} - className="p-2 text-white/70 rounded-xl hover:bg-[#1c1c1c] transition duration-200 hover:text-white" + className="p-2 text-black/70 dark:text-white/70 rounded-xl hover:bg-light-secondary dark:hover:bg-dark-secondary transition duration-200 hover:text-black dark:hover:text-white" > {copied ? <Check size={18} /> : <ClipboardList size={18} />} </button> diff --git a/ui/components/MessageActions/Rewrite.tsx b/ui/components/MessageActions/Rewrite.tsx index 3282e7d..80fadb3 100644 --- a/ui/components/MessageActions/Rewrite.tsx +++ b/ui/components/MessageActions/Rewrite.tsx @@ -10,7 +10,7 @@ const Rewrite = ({ return ( <button onClick={() => rewrite(messageId)} - className="py-2 px-3 text-white/70 rounded-xl hover:bg-[#1c1c1c] transition duration-200 hover:text-white flex flex-row items-center space-x-1" + className="py-2 px-3 text-black/70 dark:text-white/70 rounded-xl hover:bg-light-secondary dark:hover:bg-dark-secondary transition duration-200 hover:text-black dark:hover:text-white flex flex-row items-center space-x-1" > <ArrowLeftRight size={18} /> <p className="text-xs font-medium">Rewrite</p> diff --git a/ui/components/MessageBox.tsx b/ui/components/MessageBox.tsx index 8084d5f..f23127c 100644 --- a/ui/components/MessageBox.tsx +++ b/ui/components/MessageBox.tsx @@ -7,7 +7,6 @@ import { cn } from '@/lib/utils'; import { BookCopy, Disc3, - Share, Volume2, StopCircle, Layers3, @@ -55,7 +54,7 @@ const MessageBox = ({ message.content.replace( regex, (_, number) => - `<a href="${message.sources?.[number - 1]?.metadata?.url}" target="_blank" className="bg-[#1C1C1C] px-1 rounded ml-1 no-underline text-xs text-white/70 relative">${number}</a>`, + `<a href="${message.sources?.[number - 1]?.metadata?.url}" target="_blank" className="bg-light-secondary dark:bg-dark-secondary px-1 rounded ml-1 no-underline text-xs text-black/70 dark:text-white/70 relative">${number}</a>`, ), ); } @@ -70,7 +69,7 @@ const MessageBox = ({ <div> {message.role === 'user' && ( <div className={cn('w-full', messageIndex === 0 ? 'pt-16' : 'pt-8')}> - <h2 className="text-white font-medium text-3xl lg:w-9/12"> + <h2 className="text-black dark:text-white font-medium text-3xl lg:w-9/12"> {message.content} </h2> </div> @@ -85,8 +84,10 @@ const MessageBox = ({ {message.sources && message.sources.length > 0 && ( <div className="flex flex-col space-y-2"> <div className="flex flex-row items-center space-x-2"> - <BookCopy className="text-white" size={20} /> - <h3 className="text-white font-medium text-xl">Sources</h3> + <BookCopy className="text-black dark:text-white" size={20} /> + <h3 className="text-black dark:text-white font-medium text-xl"> + Sources + </h3> </div> <MessageSources sources={message.sources} /> </div> @@ -95,23 +96,30 @@ const MessageBox = ({ <div className="flex flex-row items-center space-x-2"> <Disc3 className={cn( - 'text-white', + 'text-black dark:text-white', isLast && loading ? 'animate-spin' : 'animate-none', )} size={20} /> - <h3 className="text-white font-medium text-xl">Answer</h3> + <h3 className="text-black dark:text-white font-medium text-xl"> + Answer + </h3> </div> - <Markdown className="prose max-w-none break-words prose-invert prose-p:leading-relaxed prose-pre:p-0 text-white text-sm md:text-base font-medium"> + <Markdown + className={cn( + 'prose prose-h1:mb-3 prose-h2:mb-2 prose-h2:mt-6 prose-h2:font-[800] prose-h3:mt-4 prose-h3:mb-1.5 prose-h3:font-[600] dark:prose-invert prose-p:leading-relaxed prose-pre:p-0 font-[400]', + 'max-w-none break-words text-black dark:text-white', + )} + > {parsedMessage} </Markdown> {loading && isLast ? null : ( - <div className="flex flex-row items-center justify-between w-full text-white py-4 -mx-2"> + <div className="flex flex-row items-center justify-between w-full text-black dark:text-white py-4 -mx-2"> <div className="flex flex-row items-center space-x-1"> - {/* <button className="p-2 text-white/70 rounded-xl hover:bg-[#1c1c1c] transition duration-200 hover:text-white"> + {/* <button className="p-2 text-black/70 dark:text-white/70 rounded-xl hover:bg-light-secondary dark:hover:bg-dark-secondary transition duration-200 hover:text-black text-black dark:hover:text-white"> <Share size={18} /> </button> */} - <Rewrite rewrite={rewrite} messageId={message.id} /> + <Rewrite rewrite={rewrite} messageId={message.messageId} /> </div> <div className="flex flex-row items-center space-x-1"> <Copy initialMessage={message.content} message={message} /> @@ -123,7 +131,7 @@ const MessageBox = ({ start(); } }} - className="p-2 text-white/70 rounded-xl hover:bg-[#1c1c1c] transition duration-200 hover:text-white" + className="p-2 text-black/70 dark:text-white/70 rounded-xl hover:bg-light-secondary dark:hover:bg-dark-secondary transition duration-200 hover:text-black dark:hover:text-white" > {speechStatus === 'started' ? ( <StopCircle size={18} /> @@ -140,8 +148,8 @@ const MessageBox = ({ message.role === 'assistant' && !loading && ( <> - <div className="h-px w-full bg-[#1C1C1C]" /> - <div className="flex flex-col space-y-3 text-white"> + <div className="h-px w-full bg-light-secondary dark:bg-dark-secondary" /> + <div className="flex flex-col space-y-3 text-black dark:text-white"> <div className="flex flex-row items-center space-x-2 mt-4"> <Layers3 /> <h3 className="text-xl font-medium">Related</h3> @@ -152,7 +160,7 @@ const MessageBox = ({ className="flex flex-col space-y-3 text-sm" key={i} > - <div className="h-px w-full bg-[#1C1C1C]" /> + <div className="h-px w-full bg-light-secondary dark:bg-dark-secondary" /> <div onClick={() => { sendMessage(suggestion); @@ -162,7 +170,10 @@ const MessageBox = ({ <p className="transition duration-200 hover:text-[#24A0ED]"> {suggestion} </p> - <Plus size={20} className="text-[#24A0ED]" /> + <Plus + size={20} + className="text-[#24A0ED] flex-shrink-0" + /> </div> </div> ))} @@ -175,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"> <SearchImages query={history[messageIndex - 1].content} - chat_history={history.slice(0, messageIndex - 1)} + chatHistory={history.slice(0, messageIndex - 1)} /> <SearchVideos - chat_history={history.slice(0, messageIndex - 1)} + chatHistory={history.slice(0, messageIndex - 1)} query={history[messageIndex - 1].content} /> </div> diff --git a/ui/components/MessageBoxLoading.tsx b/ui/components/MessageBoxLoading.tsx index e070a27..3c53d9e 100644 --- a/ui/components/MessageBoxLoading.tsx +++ b/ui/components/MessageBoxLoading.tsx @@ -1,9 +1,9 @@ const MessageBoxLoading = () => { return ( - <div className="flex flex-col space-y-2 w-full lg:w-9/12 bg-[#111111] animate-pulse rounded-lg p-3"> - <div className="h-2 rounded-full w-full bg-[#1c1c1c]" /> - <div className="h-2 rounded-full w-9/12 bg-[#1c1c1c]" /> - <div className="h-2 rounded-full w-10/12 bg-[#1c1c1c]" /> + <div className="flex flex-col space-y-2 w-full lg:w-9/12 bg-light-primary dark:bg-dark-primary animate-pulse rounded-lg py-3"> + <div className="h-2 rounded-full w-full bg-light-secondary dark:bg-dark-secondary" /> + <div className="h-2 rounded-full w-9/12 bg-light-secondary dark:bg-dark-secondary" /> + <div className="h-2 rounded-full w-10/12 bg-light-secondary dark:bg-dark-secondary" /> </div> ); }; diff --git a/ui/components/MessageInput.tsx b/ui/components/MessageInput.tsx index baf6095..b6b1d96 100644 --- a/ui/components/MessageInput.tsx +++ b/ui/components/MessageInput.tsx @@ -1,15 +1,26 @@ import { cn } from '@/lib/utils'; import { ArrowUp } from 'lucide-react'; -import { useEffect, useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import TextareaAutosize from 'react-textarea-autosize'; -import { Attach, CopilotToggle } from './MessageInputActions'; +import Attach from './MessageInputActions/Attach'; +import CopilotToggle from './MessageInputActions/Copilot'; +import { File } from './ChatWindow'; +import AttachSmall from './MessageInputActions/AttachSmall'; const MessageInput = ({ sendMessage, loading, + fileIds, + setFileIds, + files, + setFiles, }: { sendMessage: (message: string) => void; loading: boolean; + fileIds: string[]; + setFileIds: (fileIds: string[]) => void; + files: File[]; + setFiles: (files: File[]) => void; }) => { const [copilotEnabled, setCopilotEnabled] = useState(false); const [message, setMessage] = useState(''); @@ -24,6 +35,30 @@ const MessageInput = ({ } }, [textareaRows, mode, message]); + const inputRef = useRef<HTMLTextAreaElement | null>(null); + + 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); + + return () => { + document.removeEventListener('keydown', handleKeyDown); + }; + }, []); + return ( <form onSubmit={(e) => { @@ -40,18 +75,26 @@ const MessageInput = ({ } }} className={cn( - 'bg-[#111111] p-4 flex items-center overflow-hidden border border-[#1C1C1C]', + 'bg-light-secondary dark:bg-dark-secondary p-4 flex items-center overflow-hidden border border-light-200 dark:border-dark-200', mode === 'multi' ? 'flex-col rounded-lg' : 'flex-row rounded-full', )} > - {mode === 'single' && <Attach />} + {mode === 'single' && ( + <AttachSmall + fileIds={fileIds} + setFileIds={setFileIds} + files={files} + setFiles={setFiles} + /> + )} <TextareaAutosize + ref={inputRef} value={message} onChange={(e) => setMessage(e.target.value)} onHeightChange={(height, props) => { setTextareaRows(Math.ceil(height / props.rowHeight)); }} - className="transition bg-transparent placeholder:text-white/50 placeholder:text-sm text-sm text-white resize-none focus:outline-none w-full px-2 max-h-24 lg:max-h-36 xl:max-h-48 flex-grow flex-shrink" + className="transition bg-transparent dark:placeholder:text-white/50 placeholder:text-sm text-sm dark:text-white resize-none focus:outline-none w-full px-2 max-h-24 lg:max-h-36 xl:max-h-48 flex-grow flex-shrink" placeholder="Ask a follow-up" /> {mode === 'single' && ( @@ -62,7 +105,7 @@ const MessageInput = ({ /> <button disabled={message.trim().length === 0 || loading} - className="bg-[#24A0ED] text-white disabled:text-white/50 hover:bg-opacity-85 transition duration-100 disabled:bg-[#ececec21] rounded-full p-2" + className="bg-[#24A0ED] text-white disabled:text-black/50 dark:disabled:text-white/50 hover:bg-opacity-85 transition duration-100 disabled:bg-[#e0e0dc79] dark:disabled:bg-[#ececec21] rounded-full p-2" > <ArrowUp className="bg-background" size={17} /> </button> @@ -70,7 +113,12 @@ const MessageInput = ({ )} {mode === 'multi' && ( <div className="flex flex-row items-center justify-between w-full pt-2"> - <Attach /> + <AttachSmall + fileIds={fileIds} + setFileIds={setFileIds} + files={files} + setFiles={setFiles} + /> <div className="flex flex-row items-center space-x-4"> <CopilotToggle copilotEnabled={copilotEnabled} @@ -78,7 +126,7 @@ const MessageInput = ({ /> <button disabled={message.trim().length === 0 || loading} - className="bg-[#24A0ED] text-white disabled:text-white/50 hover:bg-opacity-85 transition duration-100 disabled:bg-[#ececec21] rounded-full p-2" + className="bg-[#24A0ED] text-white text-black/50 dark:disabled:text-white/50 hover:bg-opacity-85 transition duration-100 disabled:bg-[#e0e0dc79] dark:disabled:bg-[#ececec21] rounded-full p-2" > <ArrowUp className="bg-background" size={17} /> </button> diff --git a/ui/components/MessageInputActions/Attach.tsx b/ui/components/MessageInputActions/Attach.tsx new file mode 100644 index 0000000..61cc86a --- /dev/null +++ b/ui/components/MessageInputActions/Attach.tsx @@ -0,0 +1,185 @@ +import { cn } from '@/lib/utils'; +import { + Popover, + PopoverButton, + PopoverPanel, + Transition, +} from '@headlessui/react'; +import { CopyPlus, File, LoaderCircle, Plus, Trash } from 'lucide-react'; +import { Fragment, useRef, useState } from 'react'; +import { File as FileType } from '../ChatWindow'; + +const Attach = ({ + fileIds, + setFileIds, + showText, + files, + setFiles, +}: { + fileIds: string[]; + setFileIds: (fileIds: string[]) => void; + showText?: boolean; + files: FileType[]; + setFiles: (files: FileType[]) => void; +}) => { + const [loading, setLoading] = useState(false); + const fileInputRef = useRef<any>(); + + const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => { + setLoading(true); + const data = new FormData(); + + for (let i = 0; i < e.target.files!.length; i++) { + data.append('files', e.target.files![i]); + } + + const embeddingModelProvider = localStorage.getItem( + 'embeddingModelProvider', + ); + const embeddingModel = localStorage.getItem('embeddingModel'); + + data.append('embedding_model_provider', embeddingModelProvider!); + data.append('embedding_model', embeddingModel!); + + const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/uploads`, { + method: 'POST', + body: data, + }); + + const resData = await res.json(); + + setFiles([...files, ...resData.files]); + setFileIds([...fileIds, ...resData.files.map((file: any) => file.fileId)]); + setLoading(false); + }; + + return loading ? ( + <div className="flex flex-row items-center justify-between space-x-1"> + <LoaderCircle size={18} className="text-sky-400 animate-spin" /> + <p className="text-sky-400 inline whitespace-nowrap text-xs font-medium"> + Uploading.. + </p> + </div> + ) : files.length > 0 ? ( + <Popover className="relative w-full max-w-[15rem] md:max-w-md lg:max-w-lg"> + <PopoverButton + type="button" + className={cn( + 'flex flex-row items-center justify-between space-x-1 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', + files.length > 0 ? '-ml-2 lg:-ml-3' : '', + )} + > + {files.length > 1 && ( + <> + <File size={19} className="text-sky-400" /> + <p className="text-sky-400 inline whitespace-nowrap text-xs font-medium"> + {files.length} files + </p> + </> + )} + + {files.length === 1 && ( + <> + <File size={18} className="text-sky-400" /> + <p className="text-sky-400 text-xs font-medium"> + {files[0].fileName.length > 10 + ? files[0].fileName.replace(/\.\w+$/, '').substring(0, 3) + + '...' + + files[0].fileExtension + : files[0].fileName} + </p> + </> + )} + </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-[350px] right-0"> + <div className="bg-light-primary dark:bg-dark-primary border rounded-md border-light-200 dark:border-dark-200 w-full max-h-[200px] md:max-h-none overflow-y-auto flex flex-col"> + <div className="flex flex-row items-center justify-between px-3 py-2"> + <h4 className="text-black dark:text-white font-medium text-sm"> + Attached files + </h4> + <div className="flex flex-row items-center space-x-4"> + <button + type="button" + onClick={() => fileInputRef.current.click()} + className="flex flex-row items-center space-x-1 text-white/70 hover:text-white transition duration-200" + > + <input + type="file" + onChange={handleChange} + ref={fileInputRef} + accept=".pdf,.docx,.txt" + multiple + hidden + /> + <Plus size={18} /> + <p className="text-xs">Add</p> + </button> + <button + onClick={() => { + setFiles([]); + setFileIds([]); + }} + className="flex flex-row items-center space-x-1 text-white/70 hover:text-white transition duration-200" + > + <Trash size={14} /> + <p className="text-xs">Clear</p> + </button> + </div> + </div> + <div className="h-[0.5px] mx-2 bg-white/10" /> + <div className="flex flex-col items-center"> + {files.map((file, i) => ( + <div + key={i} + className="flex flex-row items-center justify-start w-full space-x-3 p-3" + > + <div className="bg-dark-100 flex items-center justify-center w-10 h-10 rounded-md"> + <File size={16} className="text-white/70" /> + </div> + <p className="text-white/70 text-sm"> + {file.fileName.length > 25 + ? file.fileName.replace(/\.\w+$/, '').substring(0, 25) + + '...' + + file.fileExtension + : file.fileName} + </p> + </div> + ))} + </div> + </div> + </PopoverPanel> + </Transition> + </Popover> + ) : ( + <button + type="button" + onClick={() => fileInputRef.current.click()} + className={cn( + 'flex flex-row items-center space-x-1 text-black/50 dark:text-white/50 rounded-xl hover:bg-light-secondary dark:hover:bg-dark-secondary transition duration-200 hover:text-black dark:hover:text-white', + showText ? '' : 'p-2', + )} + > + <input + type="file" + onChange={handleChange} + ref={fileInputRef} + accept=".pdf,.docx,.txt" + multiple + hidden + /> + <CopyPlus size={showText ? 18 : undefined} /> + {showText && <p className="text-xs font-medium pl-[1px]">Attach</p>} + </button> + ); +}; + +export default Attach; diff --git a/ui/components/MessageInputActions/AttachSmall.tsx b/ui/components/MessageInputActions/AttachSmall.tsx new file mode 100644 index 0000000..3514a58 --- /dev/null +++ b/ui/components/MessageInputActions/AttachSmall.tsx @@ -0,0 +1,153 @@ +import { cn } from '@/lib/utils'; +import { + Popover, + PopoverButton, + PopoverPanel, + Transition, +} from '@headlessui/react'; +import { CopyPlus, File, LoaderCircle, Plus, Trash } from 'lucide-react'; +import { Fragment, useRef, useState } from 'react'; +import { File as FileType } from '../ChatWindow'; + +const AttachSmall = ({ + fileIds, + setFileIds, + files, + setFiles, +}: { + fileIds: string[]; + setFileIds: (fileIds: string[]) => void; + files: FileType[]; + setFiles: (files: FileType[]) => void; +}) => { + const [loading, setLoading] = useState(false); + const fileInputRef = useRef<any>(); + + const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => { + setLoading(true); + const data = new FormData(); + + for (let i = 0; i < e.target.files!.length; i++) { + data.append('files', e.target.files![i]); + } + + const embeddingModelProvider = localStorage.getItem( + 'embeddingModelProvider', + ); + const embeddingModel = localStorage.getItem('embeddingModel'); + + data.append('embedding_model_provider', embeddingModelProvider!); + data.append('embedding_model', embeddingModel!); + + const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/uploads`, { + method: 'POST', + body: data, + }); + + const resData = await res.json(); + + setFiles([...files, ...resData.files]); + setFileIds([...fileIds, ...resData.files.map((file: any) => file.fileId)]); + setLoading(false); + }; + + return loading ? ( + <div className="flex flex-row items-center justify-between space-x-1 p-1"> + <LoaderCircle size={20} className="text-sky-400 animate-spin" /> + </div> + ) : files.length > 0 ? ( + <Popover className="max-w-[15rem] md:max-w-md lg:max-w-lg"> + <PopoverButton + type="button" + className="flex flex-row items-center justify-between space-x-1 p-1 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" + > + <File size={20} className="text-sky-400" /> + </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-[350px] bottom-14 -ml-3"> + <div className="bg-light-primary dark:bg-dark-primary border rounded-md border-light-200 dark:border-dark-200 w-full max-h-[200px] md:max-h-none overflow-y-auto flex flex-col"> + <div className="flex flex-row items-center justify-between px-3 py-2"> + <h4 className="text-black dark:text-white font-medium text-sm"> + Attached files + </h4> + <div className="flex flex-row items-center space-x-4"> + <button + type="button" + onClick={() => fileInputRef.current.click()} + className="flex flex-row items-center space-x-1 text-white/70 hover:text-white transition duration-200" + > + <input + type="file" + onChange={handleChange} + ref={fileInputRef} + accept=".pdf,.docx,.txt" + multiple + hidden + /> + <Plus size={18} /> + <p className="text-xs">Add</p> + </button> + <button + onClick={() => { + setFiles([]); + setFileIds([]); + }} + className="flex flex-row items-center space-x-1 text-white/70 hover:text-white transition duration-200" + > + <Trash size={14} /> + <p className="text-xs">Clear</p> + </button> + </div> + </div> + <div className="h-[0.5px] mx-2 bg-white/10" /> + <div className="flex flex-col items-center"> + {files.map((file, i) => ( + <div + key={i} + className="flex flex-row items-center justify-start w-full space-x-3 p-3" + > + <div className="bg-dark-100 flex items-center justify-center w-10 h-10 rounded-md"> + <File size={16} className="text-white/70" /> + </div> + <p className="text-white/70 text-sm"> + {file.fileName.length > 25 + ? file.fileName.replace(/\.\w+$/, '').substring(0, 25) + + '...' + + file.fileExtension + : file.fileName} + </p> + </div> + ))} + </div> + </div> + </PopoverPanel> + </Transition> + </Popover> + ) : ( + <button + type="button" + onClick={() => fileInputRef.current.click()} + className="flex flex-row items-center space-x-1 text-black/50 dark:text-white/50 rounded-xl hover:bg-light-secondary dark:hover:bg-dark-secondary transition duration-200 hover:text-black dark:hover:text-white p-1" + > + <input + type="file" + onChange={handleChange} + ref={fileInputRef} + accept=".pdf,.docx,.txt" + multiple + hidden + /> + <CopyPlus size={20} /> + </button> + ); +}; + +export default AttachSmall; diff --git a/ui/components/MessageInputActions/Copilot.tsx b/ui/components/MessageInputActions/Copilot.tsx new file mode 100644 index 0000000..5a3e476 --- /dev/null +++ b/ui/components/MessageInputActions/Copilot.tsx @@ -0,0 +1,43 @@ +import { cn } from '@/lib/utils'; +import { Switch } from '@headlessui/react'; + +const CopilotToggle = ({ + copilotEnabled, + setCopilotEnabled, +}: { + copilotEnabled: boolean; + setCopilotEnabled: (enabled: boolean) => void; +}) => { + return ( + <div className="group flex flex-row items-center space-x-1 active:scale-95 duration-200 transition cursor-pointer"> + <Switch + checked={copilotEnabled} + onChange={setCopilotEnabled} + 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={cn( + copilotEnabled + ? '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> + <p + onClick={() => setCopilotEnabled(!copilotEnabled)} + className={cn( + 'text-xs font-medium transition-colors duration-150 ease-in-out', + copilotEnabled + ? 'text-[#24A0ED]' + : 'text-black/50 dark:text-white/50 group-hover:text-black dark:group-hover:text-white', + )} + > + Copilot + </p> + </div> + ); +}; + +export default CopilotToggle; diff --git a/ui/components/MessageInputActions.tsx b/ui/components/MessageInputActions/Focus.tsx similarity index 55% rename from ui/components/MessageInputActions.tsx rename to ui/components/MessageInputActions/Focus.tsx index 9c00c4d..613078b 100644 --- a/ui/components/MessageInputActions.tsx +++ b/ui/components/MessageInputActions/Focus.tsx @@ -1,28 +1,21 @@ import { BadgePercent, ChevronDown, - CopyPlus, Globe, Pencil, ScanEye, SwatchBook, } from 'lucide-react'; import { cn } from '@/lib/utils'; -import { Popover, Switch, Transition } from '@headlessui/react'; +import { + Popover, + PopoverButton, + PopoverPanel, + Transition, +} from '@headlessui/react'; import { SiReddit, SiYoutube } from '@icons-pack/react-simple-icons'; import { Fragment } from 'react'; -export const Attach = () => { - return ( - <button - type="button" - className="p-2 text-white/50 rounded-xl hover:bg-[#1c1c1c] transition duration-200 hover:text-white" - > - <CopyPlus /> - </button> - ); -}; - const focusModes = [ { key: 'webSearch', @@ -74,7 +67,7 @@ const focusModes = [ }, ]; -export const Focus = ({ +const Focus = ({ focusMode, setFocusMode, }: { @@ -82,23 +75,26 @@ export const Focus = ({ setFocusMode: (mode: string) => void; }) => { return ( - <Popover className="fixed w-full max-w-[15rem] md:max-w-md lg:max-w-lg"> - <Popover.Button + <Popover className="relative w-full max-w-[15rem] md:max-w-md lg:max-w-lg mt-[6.5px]"> + <PopoverButton type="button" - className="p-2 text-white/50 rounded-xl hover:bg-[#1c1c1c] active:scale-95 transition duration-200 hover:text-white" + 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" > {focusMode !== 'webSearch' ? ( <div className="flex flex-row items-center space-x-1"> {focusModes.find((mode) => mode.key === focusMode)?.icon} - <p className="text-xs font-medium"> + <p className="text-xs font-medium hidden lg:block"> {focusModes.find((mode) => mode.key === focusMode)?.title} </p> - <ChevronDown size={20} /> + <ChevronDown size={20} className="-translate-x-1" /> </div> ) : ( - <ScanEye /> + <div className="flex flex-row items-center space-x-1"> + <ScanEye size={20} /> + <p className="text-xs font-medium hidden lg:block">Focus</p> + </div> )} - </Popover.Button> + </PopoverButton> <Transition as={Fragment} enter="transition ease-out duration-150" @@ -108,73 +104,40 @@ export const Focus = ({ leaveFrom="opacity-100 translate-y-0" leaveTo="opacity-0 translate-y-1" > - <Popover.Panel className="absolute z-10 w-full"> - <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-1 bg-[#0A0A0A] border rounded-lg border-[#1c1c1c] w-full p-2 max-h-[200px] md:max-h-none overflow-y-auto"> + <PopoverPanel className="absolute z-10 w-64 md:w-[500px] left-0"> + <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"> {focusModes.map((mode, i) => ( - <Popover.Button + <PopoverButton onClick={() => setFocusMode(mode.key)} key={i} className={cn( 'p-2 rounded-lg flex flex-col items-start justify-start text-start space-y-2 duration-200 cursor-pointer transition', focusMode === mode.key - ? 'bg-[#111111]' - : 'hover:bg-[#111111]', + ? 'bg-light-secondary dark:bg-dark-secondary' + : 'hover:bg-light-secondary dark:hover:bg-dark-secondary', )} > <div className={cn( 'flex flex-row items-center space-x-1', - focusMode === mode.key ? 'text-[#24A0ED]' : 'text-white', + focusMode === mode.key + ? 'text-[#24A0ED]' + : 'text-black dark:text-white', )} > {mode.icon} <p className="text-sm font-medium">{mode.title}</p> </div> - <p className="text-white/70 text-xs">{mode.description}</p> - </Popover.Button> + <p className="text-black/70 dark:text-white/70 text-xs"> + {mode.description} + </p> + </PopoverButton> ))} </div> - </Popover.Panel> + </PopoverPanel> </Transition> </Popover> ); }; -export const CopilotToggle = ({ - copilotEnabled, - setCopilotEnabled, -}: { - copilotEnabled: boolean; - setCopilotEnabled: (enabled: boolean) => void; -}) => { - return ( - <div className="group flex flex-row items-center space-x-1 active:scale-95 duration-200 transition cursor-pointer"> - <Switch - checked={copilotEnabled} - onChange={setCopilotEnabled} - className="bg-[#111111] border border-[#1C1C1C] 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={cn( - copilotEnabled - ? 'translate-x-6 bg-[#24A0ED]' - : 'translate-x-1 bg-white/50', - 'inline-block h-3 w-3 sm:h-4 sm:w-4 transform rounded-full transition-all duration-200', - )} - /> - </Switch> - <p - onClick={() => setCopilotEnabled(!copilotEnabled)} - className={cn( - 'text-xs font-medium transition-colors duration-150 ease-in-out', - copilotEnabled - ? 'text-[#24A0ED]' - : 'text-white/50 group-hover:text-white', - )} - > - Copilot - </p> - </div> - ); -}; +export default Focus; diff --git a/ui/components/MessageInputActions/Optimization.tsx b/ui/components/MessageInputActions/Optimization.tsx new file mode 100644 index 0000000..ac8a7b0 --- /dev/null +++ b/ui/components/MessageInputActions/Optimization.tsx @@ -0,0 +1,104 @@ +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; diff --git a/ui/components/MessageSources.tsx b/ui/components/MessageSources.tsx index 5816f8d..c7ee945 100644 --- a/ui/components/MessageSources.tsx +++ b/ui/components/MessageSources.tsx @@ -1,6 +1,13 @@ /* eslint-disable @next/next/no-img-element */ -import { Dialog, Transition } from '@headlessui/react'; +import { + Dialog, + DialogPanel, + DialogTitle, + Transition, + TransitionChild, +} from '@headlessui/react'; import { Document } from '@langchain/core/documents'; +import { File } from 'lucide-react'; import { Fragment, useState } from 'react'; const MessageSources = ({ sources }: { sources: Document[] }) => { @@ -20,29 +27,35 @@ const MessageSources = ({ sources }: { sources: Document[] }) => { <div className="grid grid-cols-2 lg:grid-cols-4 gap-2"> {sources.slice(0, 3).map((source, i) => ( <a - className="bg-[#111111] hover:bg-[#1c1c1c] transition duration-200 rounded-lg p-3 flex flex-col space-y-2 font-medium" + className="bg-light-100 hover:bg-light-200 dark:bg-dark-100 dark:hover:bg-dark-200 transition duration-200 rounded-lg p-3 flex flex-col space-y-2 font-medium" key={i} href={source.metadata.url} target="_blank" > - <p className="text-white text-xs overflow-hidden whitespace-nowrap text-ellipsis"> + <p className="dark:text-white text-xs overflow-hidden whitespace-nowrap text-ellipsis"> {source.metadata.title} </p> <div className="flex flex-row items-center justify-between"> <div className="flex flex-row items-center space-x-1"> - <img - src={`https://s2.googleusercontent.com/s2/favicons?domain_url=${source.metadata.url}`} - width={16} - height={16} - alt="favicon" - className="rounded-lg h-4 w-4" - /> - <p className="text-xs text-white/50 overflow-hidden whitespace-nowrap text-ellipsis"> + {source.metadata.url === 'File' ? ( + <div className="bg-dark-200 hover:bg-dark-100 transition duration-200 flex items-center justify-center w-6 h-6 rounded-full"> + <File size={12} className="text-white/70" /> + </div> + ) : ( + <img + src={`https://s2.googleusercontent.com/s2/favicons?domain_url=${source.metadata.url}`} + width={16} + height={16} + alt="favicon" + className="rounded-lg h-4 w-4" + /> + )} + <p className="text-xs text-black/50 dark:text-white/50 overflow-hidden whitespace-nowrap text-ellipsis"> {source.metadata.url.replace(/.+\/\/|www.|\..+/g, '')} </p> </div> - <div className="flex flex-row items-center space-x-1 text-white/50 text-xs"> - <div className="bg-white/50 h-[4px] w-[4px] rounded-full" /> + <div className="flex flex-row items-center space-x-1 text-black/50 dark:text-white/50 text-xs"> + <div className="bg-black/50 dark:bg-white/50 h-[4px] w-[4px] rounded-full" /> <span>{i + 1}</span> </div> </div> @@ -51,21 +64,26 @@ const MessageSources = ({ sources }: { sources: Document[] }) => { {sources.length > 3 && ( <button onClick={openModal} - className="bg-[#111111] hover:bg-[#1c1c1c] transition duration-200 rounded-lg px-4 py-2 flex flex-col justify-between space-y-2" + className="bg-light-100 hover:bg-light-200 dark:bg-dark-100 dark:hover:bg-dark-200 transition duration-200 rounded-lg p-3 flex flex-col space-y-2 font-medium" > <div className="flex flex-row items-center space-x-1"> - {sources.slice(3, 6).map((source, i) => ( - <img - src={`https://s2.googleusercontent.com/s2/favicons?domain_url=${source.metadata.url}`} - width={16} - height={16} - alt="favicon" - className="rounded-lg h-4 w-4" - key={i} - /> - ))} + {sources.slice(3, 6).map((source, i) => { + return source.metadata.url === 'File' ? ( + <div className="bg-dark-200 hover:bg-dark-100 transition duration-200 flex items-center justify-center w-6 h-6 rounded-full"> + <File size={12} className="text-white/70" /> + </div> + ) : ( + <img + src={`https://s2.googleusercontent.com/s2/favicons?domain_url=${source.metadata.url}`} + width={16} + height={16} + alt="favicon" + className="rounded-lg h-4 w-4" + /> + ); + })} </div> - <p className="text-xs text-white/50"> + <p className="text-xs text-black/50 dark:text-white/50"> View {sources.length - 3} more </p> </button> @@ -74,7 +92,7 @@ const MessageSources = ({ sources }: { sources: Document[] }) => { <Dialog as="div" className="relative z-50" onClose={closeModal}> <div className="fixed inset-0 overflow-y-auto"> <div className="flex min-h-full items-center justify-center p-4 text-center"> - <Transition.Child + <TransitionChild as={Fragment} enter="ease-out duration-200" enterFrom="opacity-0 scale-95" @@ -83,47 +101,53 @@ const MessageSources = ({ sources }: { sources: Document[] }) => { leaveFrom="opacity-100 scale-200" leaveTo="opacity-0 scale-95" > - <Dialog.Panel className="w-full max-w-md transform rounded-2xl bg-[#111111] border border-[#1c1c1c] p-6 text-left align-middle shadow-xl transition-all"> - <Dialog.Title className="text-lg font-medium leading-6 text-white"> + <DialogPanel className="w-full max-w-md transform rounded-2xl bg-light-secondary dark:bg-dark-secondary border border-light-200 dark:border-dark-200 p-6 text-left align-middle shadow-xl transition-all"> + <DialogTitle className="text-lg font-medium leading-6 dark:text-white"> Sources - </Dialog.Title> + </DialogTitle> <div className="grid grid-cols-2 gap-2 overflow-auto max-h-[300px] mt-2 pr-2"> {sources.map((source, i) => ( <a - className="bg-[#111111] hover:bg-[#1c1c1c] border border-[#1c1c1c] transition duration-200 rounded-lg p-3 flex flex-col space-y-2 font-medium" + className="bg-light-secondary hover:bg-light-200 dark:bg-dark-secondary dark:hover:bg-dark-200 border border-light-200 dark:border-dark-200 transition duration-200 rounded-lg p-3 flex flex-col space-y-2 font-medium" key={i} href={source.metadata.url} target="_blank" > - <p className="text-white text-xs overflow-hidden whitespace-nowrap text-ellipsis"> + <p className="dark:text-white text-xs overflow-hidden whitespace-nowrap text-ellipsis"> {source.metadata.title} </p> <div className="flex flex-row items-center justify-between"> <div className="flex flex-row items-center space-x-1"> - <img - src={`https://s2.googleusercontent.com/s2/favicons?domain_url=${source.metadata.url}`} - width={16} - height={16} - alt="favicon" - className="rounded-lg h-4 w-4" - /> - <p className="text-xs text-white/50 overflow-hidden whitespace-nowrap text-ellipsis"> + {source.metadata.url === 'File' ? ( + <div className="bg-dark-200 hover:bg-dark-100 transition duration-200 flex items-center justify-center w-6 h-6 rounded-full"> + <File size={12} className="text-white/70" /> + </div> + ) : ( + <img + src={`https://s2.googleusercontent.com/s2/favicons?domain_url=${source.metadata.url}`} + width={16} + height={16} + alt="favicon" + className="rounded-lg h-4 w-4" + /> + )} + <p className="text-xs text-black/50 dark:text-white/50 overflow-hidden whitespace-nowrap text-ellipsis"> {source.metadata.url.replace( /.+\/\/|www.|\..+/g, '', )} </p> </div> - <div className="flex flex-row items-center space-x-1 text-white/50 text-xs"> - <div className="bg-white/50 h-[4px] w-[4px] rounded-full" /> + <div className="flex flex-row items-center space-x-1 text-black/50 dark:text-white/50 text-xs"> + <div className="bg-black/50 dark:bg-white/50 h-[4px] w-[4px] rounded-full" /> <span>{i + 1}</span> </div> </div> </a> ))} </div> - </Dialog.Panel> - </Transition.Child> + </DialogPanel> + </TransitionChild> </div> </div> </Dialog> diff --git a/ui/components/Navbar.tsx b/ui/components/Navbar.tsx index 75c34a6..13f2da3 100644 --- a/ui/components/Navbar.tsx +++ b/ui/components/Navbar.tsx @@ -2,8 +2,15 @@ import { Clock, Edit, Share, Trash } from 'lucide-react'; import { Message } from './ChatWindow'; import { useEffect, useState } from 'react'; import { formatTimeDifference } from '@/lib/utils'; +import DeleteChat from './DeleteChat'; -const Navbar = ({ messages }: { messages: Message[] }) => { +const Navbar = ({ + chatId, + messages, +}: { + messages: Message[]; + chatId: string; +}) => { const [title, setTitle] = useState<string>(''); const [timeAgo, setTimeAgo] = useState<string>(''); @@ -38,25 +45,25 @@ const Navbar = ({ messages }: { messages: Message[] }) => { }, []); 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-white/70 border-b bg-[#0A0A0A] border-[#1C1C1C]"> - <Edit - size={17} + <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 + href="/" 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"> <Clock size={17} /> <p className="text-xs">{timeAgo} ago</p> </div> <p className="hidden lg:flex">{title}</p> + <div className="flex flex-row items-center space-x-4"> <Share size={17} className="active:scale-95 transition duration-100 cursor-pointer" /> - <Trash - size={17} - className="text-red-400 active:scale-95 transition duration-100 cursor-pointer" - /> + <DeleteChat redirect chatId={chatId} chats={[]} setChats={() => {}} /> </div> </div> ); diff --git a/ui/components/SearchImages.tsx b/ui/components/SearchImages.tsx index aa70c96..b083af7 100644 --- a/ui/components/SearchImages.tsx +++ b/ui/components/SearchImages.tsx @@ -13,10 +13,10 @@ type Image = { const SearchImages = ({ query, - chat_history, + chatHistory, }: { query: string; - chat_history: Message[]; + chatHistory: Message[]; }) => { const [images, setImages] = useState<Image[] | null>(null); const [loading, setLoading] = useState(false); @@ -33,6 +33,9 @@ const SearchImages = ({ const chatModelProvider = localStorage.getItem('chatModelProvider'); const chatModel = localStorage.getItem('chatModel'); + const customOpenAIBaseURL = localStorage.getItem('openAIBaseURL'); + const customOpenAIKey = localStorage.getItem('openAIApiKey'); + const res = await fetch( `${process.env.NEXT_PUBLIC_API_URL}/images`, { @@ -42,16 +45,22 @@ const SearchImages = ({ }, body: JSON.stringify({ query: query, - chat_history: chat_history, - chat_model_provider: chatModelProvider, - chat_model: chatModel, + chatHistory: chatHistory, + chatModel: { + provider: chatModelProvider, + model: chatModel, + ...(chatModelProvider === 'custom_openai' && { + customOpenAIBaseURL: customOpenAIBaseURL, + customOpenAIKey: customOpenAIKey, + }), + }, }), }, ); const data = await res.json(); - const images = data.images; + const images = data.images ?? []; setImages(images); setSlides( images.map((image: Image) => { @@ -62,7 +71,7 @@ const SearchImages = ({ ); setLoading(false); }} - className="border border-dashed border-[#1C1C1C] hover:bg-[#1c1c1c] active:scale-95 duration-200 transition px-4 py-2 flex flex-row items-center justify-between rounded-lg text-white text-sm w-full" + className="border border-dashed border-light-200 dark:border-dark-200 hover:bg-light-200 dark:hover:bg-dark-200 active:scale-95 duration-200 transition px-4 py-2 flex flex-row items-center justify-between rounded-lg dark:text-white text-sm w-full" > <div className="flex flex-row items-center space-x-2"> <ImagesIcon size={17} /> @@ -76,7 +85,7 @@ const SearchImages = ({ {[...Array(4)].map((_, i) => ( <div key={i} - className="bg-[#1C1C1C] h-32 w-full rounded-lg animate-pulse aspect-video object-cover" + className="bg-light-secondary dark:bg-dark-secondary h-32 w-full rounded-lg animate-pulse aspect-video object-cover" /> ))} </div> @@ -120,7 +129,7 @@ const SearchImages = ({ {images.length > 4 && ( <button onClick={() => setOpen(true)} - className="bg-[#111111] hover:bg-[#1c1c1c] transition duration-200 active:scale-95 hover:scale-[1.02] h-auto w-full rounded-lg flex flex-col justify-between text-white p-2" + className="bg-light-100 hover:bg-light-200 dark:bg-dark-100 dark:hover:bg-dark-200 transition duration-200 active:scale-95 hover:scale-[1.02] h-auto w-full rounded-lg flex flex-col justify-between text-white p-2" > <div className="flex flex-row items-center space-x-1"> {images.slice(3, 6).map((image, i) => ( @@ -132,7 +141,7 @@ const SearchImages = ({ /> ))} </div> - <p className="text-white/70 text-xs"> + <p className="text-black/70 dark:text-white/70 text-xs"> View {images.length - 3} more </p> </button> diff --git a/ui/components/SearchVideos.tsx b/ui/components/SearchVideos.tsx index b5ff6c5..170df61 100644 --- a/ui/components/SearchVideos.tsx +++ b/ui/components/SearchVideos.tsx @@ -1,6 +1,6 @@ /* eslint-disable @next/next/no-img-element */ import { PlayCircle, PlayIcon, PlusIcon, VideoIcon } from 'lucide-react'; -import { useState } from 'react'; +import { useRef, useState } from 'react'; import Lightbox, { GenericSlide, VideoSlide } from 'yet-another-react-lightbox'; import 'yet-another-react-lightbox/styles.css'; import { Message } from './ChatWindow'; @@ -26,15 +26,17 @@ declare module 'yet-another-react-lightbox' { const Searchvideos = ({ query, - chat_history, + chatHistory, }: { query: string; - chat_history: Message[]; + chatHistory: Message[]; }) => { const [videos, setVideos] = useState<Video[] | null>(null); const [loading, setLoading] = useState(false); const [open, setOpen] = useState(false); const [slides, setSlides] = useState<VideoSlide[]>([]); + const [currentIndex, setCurrentIndex] = useState(0); + const videoRefs = useRef<(HTMLIFrameElement | null)[]>([]); return ( <> @@ -46,6 +48,9 @@ const Searchvideos = ({ const chatModelProvider = localStorage.getItem('chatModelProvider'); const chatModel = localStorage.getItem('chatModel'); + const customOpenAIBaseURL = localStorage.getItem('openAIBaseURL'); + const customOpenAIKey = localStorage.getItem('openAIApiKey'); + const res = await fetch( `${process.env.NEXT_PUBLIC_API_URL}/videos`, { @@ -55,16 +60,22 @@ const Searchvideos = ({ }, body: JSON.stringify({ query: query, - chat_history: chat_history, - chat_model_provider: chatModelProvider, - chat_model: chatModel, + chatHistory: chatHistory, + chatModel: { + provider: chatModelProvider, + model: chatModel, + ...(chatModelProvider === 'custom_openai' && { + customOpenAIBaseURL: customOpenAIBaseURL, + customOpenAIKey: customOpenAIKey, + }), + }, }), }, ); const data = await res.json(); - const videos = data.videos; + const videos = data.videos ?? []; setVideos(videos); setSlides( videos.map((video: Video) => { @@ -77,7 +88,7 @@ const Searchvideos = ({ ); setLoading(false); }} - className="border border-dashed border-[#1C1C1C] hover:bg-[#1c1c1c] active:scale-95 duration-200 transition px-4 py-2 flex flex-row items-center justify-between rounded-lg text-white text-sm w-full" + className="border border-dashed border-light-200 dark:border-dark-200 hover:bg-light-200 dark:hover:bg-dark-200 active:scale-95 duration-200 transition px-4 py-2 flex flex-row items-center justify-between rounded-lg dark:text-white text-sm w-full" > <div className="flex flex-row items-center space-x-2"> <VideoIcon size={17} /> @@ -91,7 +102,7 @@ const Searchvideos = ({ {[...Array(4)].map((_, i) => ( <div key={i} - className="bg-[#1C1C1C] h-32 w-full rounded-lg animate-pulse aspect-video object-cover" + className="bg-light-secondary dark:bg-dark-secondary h-32 w-full rounded-lg animate-pulse aspect-video object-cover" /> ))} </div> @@ -118,7 +129,7 @@ const Searchvideos = ({ alt={video.title} className="relative h-full w-full aspect-video object-cover rounded-lg" /> - <div className="absolute bg-black/70 text-white/70 px-2 py-1 flex flex-row items-center space-x-1 bottom-1 right-1 rounded-md"> + <div className="absolute bg-white/70 dark:bg-black/70 text-black/70 dark:text-white/70 px-2 py-1 flex flex-row items-center space-x-1 bottom-1 right-1 rounded-md"> <PlayCircle size={15} /> <p className="text-xs">Video</p> </div> @@ -142,7 +153,7 @@ const Searchvideos = ({ alt={video.title} className="relative h-full w-full aspect-video object-cover rounded-lg" /> - <div className="absolute bg-black/70 text-white/70 px-2 py-1 flex flex-row items-center space-x-1 bottom-1 right-1 rounded-md"> + <div className="absolute bg-white/70 dark:bg-black/70 text-black/70 dark:text-white/70 px-2 py-1 flex flex-row items-center space-x-1 bottom-1 right-1 rounded-md"> <PlayCircle size={15} /> <p className="text-xs">Video</p> </div> @@ -151,7 +162,7 @@ const Searchvideos = ({ {videos.length > 4 && ( <button onClick={() => setOpen(true)} - className="bg-[#111111] hover:bg-[#1c1c1c] transition duration-200 active:scale-95 hover:scale-[1.02] h-auto w-full rounded-lg flex flex-col justify-between text-white p-2" + className="bg-light-100 hover:bg-light-200 dark:bg-dark-100 dark:hover:bg-dark-200 transition duration-200 active:scale-95 hover:scale-[1.02] h-auto w-full rounded-lg flex flex-col justify-between text-white p-2" > <div className="flex flex-row items-center space-x-1"> {videos.slice(3, 6).map((video, i) => ( @@ -163,7 +174,7 @@ const Searchvideos = ({ /> ))} </div> - <p className="text-white/70 text-xs"> + <p className="text-black/70 dark:text-white/70 text-xs"> View {videos.length - 3} more </p> </button> @@ -173,18 +184,39 @@ const Searchvideos = ({ open={open} close={() => setOpen(false)} slides={slides} + index={currentIndex} + on={{ + view: ({ index }) => { + const previousIframe = videoRefs.current[currentIndex]; + if (previousIframe?.contentWindow) { + previousIframe.contentWindow.postMessage( + '{"event":"command","func":"pauseVideo","args":""}', + '*', + ); + } + + setCurrentIndex(index); + }, + }} render={{ - slide: ({ slide }) => - slide.type === 'video-slide' ? ( + slide: ({ slide }) => { + const index = slides.findIndex((s) => s === slide); + return slide.type === 'video-slide' ? ( <div className="h-full w-full flex flex-row items-center justify-center"> <iframe - src={slide.iframe_src} + src={`${slide.iframe_src}${slide.iframe_src.includes('?') ? '&' : '?'}enablejsapi=1`} + ref={(el) => { + if (el) { + videoRefs.current[index] = el; + } + }} className="aspect-video max-h-[95vh] w-[95vw] rounded-2xl md:w-[80vw]" allowFullScreen allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" /> </div> - ) : null, + ) : null; + }, }} /> </> diff --git a/ui/components/SettingsDialog.tsx b/ui/components/SettingsDialog.tsx index 57f79f6..163857b 100644 --- a/ui/components/SettingsDialog.tsx +++ b/ui/components/SettingsDialog.tsx @@ -1,16 +1,69 @@ -import { Dialog, Transition } from '@headlessui/react'; +import { cn } from '@/lib/utils'; +import { + Dialog, + DialogPanel, + DialogTitle, + Transition, + TransitionChild, +} from '@headlessui/react'; import { CloudUpload, RefreshCcw, RefreshCw } from 'lucide-react'; -import React, { Fragment, useEffect, useState } from 'react'; +import React, { + Fragment, + useEffect, + useState, + type SelectHTMLAttributes, +} from 'react'; +import ThemeSwitcher from './theme/Switcher'; + +interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {} + +const Input = ({ className, ...restProps }: InputProps) => { + return ( + <input + {...restProps} + className={cn( + 'bg-light-secondary dark:bg-dark-secondary px-3 py-2 flex items-center overflow-hidden border border-light-200 dark:border-dark-200 dark:text-white rounded-lg text-sm', + className, + )} + /> + ); +}; + +interface SelectProps extends SelectHTMLAttributes<HTMLSelectElement> { + options: { value: string; label: string; disabled?: boolean }[]; +} + +export const Select = ({ className, options, ...restProps }: SelectProps) => { + return ( + <select + {...restProps} + className={cn( + 'bg-light-secondary dark:bg-dark-secondary px-3 py-2 flex items-center overflow-hidden border border-light-200 dark:border-dark-200 dark:text-white rounded-lg text-sm', + className, + )} + > + {options.map(({ label, value, disabled }) => { + return ( + <option key={value} value={value} disabled={disabled}> + {label} + </option> + ); + })} + </select> + ); +}; interface SettingsType { chatModelProviders: { - [key: string]: string[]; + [key: string]: [Record<string, any>]; }; embeddingModelProviders: { - [key: string]: string[]; + [key: string]: [Record<string, any>]; }; openaiApiKey: string; groqApiKey: string; + anthropicApiKey: string; + geminiApiKey: string; ollamaApiUrl: string; } @@ -22,6 +75,10 @@ const SettingsDialog = ({ setIsOpen: (isOpen: boolean) => void; }) => { const [config, setConfig] = useState<SettingsType | null>(null); + const [chatModels, setChatModels] = useState<Record<string, any>>({}); + const [embeddingModels, setEmbeddingModels] = useState<Record<string, any>>( + {}, + ); const [selectedChatModelProvider, setSelectedChatModelProvider] = useState< string | null >(null); @@ -72,7 +129,9 @@ const SettingsDialog = ({ const chatModel = localStorage.getItem('chatModel') || (data.chatModelProviders && - data.chatModelProviders[chatModelProvider]?.[0]) || + data.chatModelProviders[chatModelProvider]?.length > 0 + ? data.chatModelProviders[chatModelProvider][0].name + : undefined) || ''; const embeddingModelProvider = localStorage.getItem('embeddingModelProvider') || @@ -81,7 +140,7 @@ const SettingsDialog = ({ const embeddingModel = localStorage.getItem('embeddingModel') || (data.embeddingModelProviders && - data.embeddingModelProviders[embeddingModelProvider]?.[0]) || + data.embeddingModelProviders[embeddingModelProvider]?.[0].name) || ''; setSelectedChatModelProvider(chatModelProvider); @@ -90,6 +149,8 @@ const SettingsDialog = ({ setSelectedEmbeddingModel(embeddingModel); setCustomOpenAIApiKey(localStorage.getItem('openAIApiKey') || ''); setCustomOpenAIBaseURL(localStorage.getItem('openAIBaseURL') || ''); + setChatModels(data.chatModelProviders || {}); + setEmbeddingModels(data.embeddingModelProviders || {}); setIsLoading(false); }; @@ -136,7 +197,7 @@ const SettingsDialog = ({ className="relative z-50" onClose={() => setIsOpen(false)} > - <Transition.Child + <TransitionChild as={Fragment} enter="ease-out duration-300" enterFrom="opacity-0" @@ -145,11 +206,11 @@ const SettingsDialog = ({ leaveFrom="opacity-100" leaveTo="opacity-0" > - <div className="fixed inset-0 bg-black/50" /> - </Transition.Child> + <div className="fixed inset-0 bg-white/50 dark:bg-black/50" /> + </TransitionChild> <div className="fixed inset-0 overflow-y-auto"> <div className="flex min-h-full items-center justify-center p-4 text-center"> - <Transition.Child + <TransitionChild as={Fragment} enter="ease-out duration-200" enterFrom="opacity-0 scale-95" @@ -158,116 +219,129 @@ const SettingsDialog = ({ leaveFrom="opacity-100 scale-200" leaveTo="opacity-0 scale-95" > - <Dialog.Panel className="w-full max-w-md transform rounded-2xl bg-[#111111] border border-[#1c1c1c] p-6 text-left align-middle shadow-xl transition-all"> - <Dialog.Title className="text-xl font-medium leading-6 text-white"> + <DialogPanel className="w-full max-w-md transform rounded-2xl bg-light-secondary dark:bg-dark-secondary border border-light-200 dark:border-dark-200 p-6 text-left align-middle shadow-xl transition-all"> + <DialogTitle className="text-xl font-medium leading-6 dark:text-white"> Settings - </Dialog.Title> + </DialogTitle> {config && !isLoading && ( <div className="flex flex-col space-y-4 mt-6"> + <div className="flex flex-col space-y-1"> + <p className="text-black/70 dark:text-white/70 text-sm"> + Theme + </p> + <ThemeSwitcher /> + </div> {config.chatModelProviders && ( <div className="flex flex-col space-y-1"> - <p className="text-white/70 text-sm"> + <p className="text-black/70 dark:text-white/70 text-sm"> Chat model Provider </p> - <select + <Select value={selectedChatModelProvider ?? undefined} onChange={(e) => { setSelectedChatModelProvider(e.target.value); - setSelectedChatModel( - config.chatModelProviders[e.target.value][0], - ); + if (e.target.value === 'custom_openai') { + setSelectedChatModel(''); + } else { + setSelectedChatModel( + config.chatModelProviders[e.target.value][0] + .name, + ); + } }} - className="bg-[#111111] px-3 py-2 flex items-center overflow-hidden border border-[#1C1C1C] text-white rounded-lg text-sm" - > - {Object.keys(config.chatModelProviders).map( - (provider) => ( - <option key={provider} value={provider}> - {provider.charAt(0).toUpperCase() + - provider.slice(1)} - </option> - ), + options={Object.keys(config.chatModelProviders).map( + (provider) => ({ + value: provider, + label: + provider.charAt(0).toUpperCase() + + provider.slice(1), + }), )} - </select> + /> </div> )} {selectedChatModelProvider && selectedChatModelProvider != 'custom_openai' && ( <div className="flex flex-col space-y-1"> - <p className="text-white/70 text-sm">Chat Model</p> - <select + <p className="text-black/70 dark:text-white/70 text-sm"> + Chat Model + </p> + <Select value={selectedChatModel ?? undefined} onChange={(e) => setSelectedChatModel(e.target.value) } - className="bg-[#111111] px-3 py-2 flex items-center overflow-hidden border border-[#1C1C1C] text-white rounded-lg text-sm" - > - {config.chatModelProviders[ - selectedChatModelProvider - ] ? ( - config.chatModelProviders[ - selectedChatModelProvider - ].length > 0 ? ( + options={(() => { + const chatModelProvider = config.chatModelProviders[ selectedChatModelProvider - ].map((model) => ( - <option key={model} value={model}> - {model} - </option> - )) - ) : ( - <option value="" disabled> - No models available - </option> - ) - ) : ( - <option value="" disabled> - Invalid provider, please check backend logs - </option> - )} - </select> + ]; + + return chatModelProvider + ? chatModelProvider.length > 0 + ? chatModelProvider.map((model) => ({ + value: model.name, + label: model.displayName, + })) + : [ + { + value: '', + label: 'No models available', + disabled: true, + }, + ] + : [ + { + value: '', + label: + 'Invalid provider, please check backend logs', + disabled: true, + }, + ]; + })()} + /> </div> )} {selectedChatModelProvider && selectedChatModelProvider === 'custom_openai' && ( <> <div className="flex flex-col space-y-1"> - <p className="text-white/70 text-sm">Model name</p> - <input + <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) } - className="bg-[#111111] px-3 py-2 flex items-center overflow-hidden border border-[#1C1C1C] text-white rounded-lg text-sm" /> </div> <div className="flex flex-col space-y-1"> - <p className="text-white/70 text-sm"> + <p className="text-black/70 dark:text-white/70 text-sm"> Custom OpenAI API Key </p> - <input + <Input type="text" placeholder="Custom OpenAI API Key" defaultValue={customOpenAIApiKey!} onChange={(e) => setCustomOpenAIApiKey(e.target.value) } - className="bg-[#111111] px-3 py-2 flex items-center overflow-hidden border border-[#1C1C1C] text-white rounded-lg text-sm" /> </div> <div className="flex flex-col space-y-1"> - <p className="text-white/70 text-sm"> + <p className="text-black/70 dark:text-white/70 text-sm"> Custom OpenAI Base URL </p> - <input + <Input type="text" placeholder="Custom OpenAI Base URL" defaultValue={customOpenAIBaseURL!} onChange={(e) => setCustomOpenAIBaseURL(e.target.value) } - className="bg-[#111111] px-3 py-2 flex items-center overflow-hidden border border-[#1C1C1C] text-white rounded-lg text-sm" /> </div> </> @@ -275,69 +349,75 @@ const SettingsDialog = ({ {/* Embedding models */} {config.embeddingModelProviders && ( <div className="flex flex-col space-y-1"> - <p className="text-white/70 text-sm"> + <p className="text-black/70 dark:text-white/70 text-sm"> Embedding model Provider </p> - <select + <Select value={selectedEmbeddingModelProvider ?? undefined} onChange={(e) => { setSelectedEmbeddingModelProvider(e.target.value); setSelectedEmbeddingModel( - config.embeddingModelProviders[e.target.value][0], + config.embeddingModelProviders[e.target.value][0] + .name, ); }} - className="bg-[#111111] px-3 py-2 flex items-center overflow-hidden border border-[#1C1C1C] text-white rounded-lg text-sm" - > - {Object.keys(config.embeddingModelProviders).map( - (provider) => ( - <option key={provider} value={provider}> - {provider.charAt(0).toUpperCase() + - provider.slice(1)} - </option> - ), - )} - </select> + 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-white/70 text-sm">Embedding Model</p> - <select + <p className="text-black/70 dark:text-white/70 text-sm"> + Embedding Model + </p> + <Select value={selectedEmbeddingModel ?? undefined} onChange={(e) => setSelectedEmbeddingModel(e.target.value) } - className="bg-[#111111] px-3 py-2 flex items-center overflow-hidden border border-[#1C1C1C] text-white rounded-lg text-sm" - > - {config.embeddingModelProviders[ - selectedEmbeddingModelProvider - ] ? ( - config.embeddingModelProviders[ - selectedEmbeddingModelProvider - ].length > 0 ? ( + options={(() => { + const embeddingModelProvider = config.embeddingModelProviders[ selectedEmbeddingModelProvider - ].map((model) => ( - <option key={model} value={model}> - {model} - </option> - )) - ) : ( - <option value="" disabled selected> - No embedding models available - </option> - ) - ) : ( - <option value="" disabled selected> - Invalid provider, please check backend logs - </option> - )} - </select> + ]; + + return embeddingModelProvider + ? embeddingModelProvider.length > 0 + ? embeddingModelProvider.map((model) => ({ + label: model.displayName, + value: model.name, + })) + : [ + { + label: 'No embedding models available', + value: '', + disabled: true, + }, + ] + : [ + { + label: + 'Invalid provider, please check backend logs', + value: '', + disabled: true, + }, + ]; + })()} + /> </div> )} <div className="flex flex-col space-y-1"> - <p className="text-white/70 text-sm">OpenAI API Key</p> - <input + <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} @@ -347,12 +427,13 @@ const SettingsDialog = ({ openaiApiKey: e.target.value, }) } - className="bg-[#111111] px-3 py-2 flex items-center overflow-hidden border border-[#1C1C1C] text-white rounded-lg text-sm" /> </div> <div className="flex flex-col space-y-1"> - <p className="text-white/70 text-sm">Ollama API URL</p> - <input + <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} @@ -362,12 +443,13 @@ const SettingsDialog = ({ ollamaApiUrl: e.target.value, }) } - className="bg-[#111111] px-3 py-2 flex items-center overflow-hidden border border-[#1C1C1C] text-white rounded-lg text-sm" /> </div> <div className="flex flex-col space-y-1"> - <p className="text-white/70 text-sm">GROQ API Key</p> - <input + <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} @@ -377,18 +459,49 @@ const SettingsDialog = ({ groqApiKey: e.target.value, }) } - className="bg-[#111111] px-3 py-2 flex items-center overflow-hidden border border-[#1C1C1C] text-white rounded-lg text-sm" + /> + </div> + <div className="flex flex-col space-y-1"> + <p className="text-black/70 dark:text-white/70 text-sm"> + Anthropic API Key + </p> + <Input + type="text" + placeholder="Anthropic API key" + defaultValue={config.anthropicApiKey} + onChange={(e) => + setConfig({ + ...config, + anthropicApiKey: e.target.value, + }) + } + /> + </div> + <div className="flex flex-col space-y-1"> + <p className="text-black/70 dark:text-white/70 text-sm"> + Gemini API Key + </p> + <Input + type="text" + placeholder="Gemini API key" + defaultValue={config.geminiApiKey} + onChange={(e) => + setConfig({ + ...config, + geminiApiKey: e.target.value, + }) + } /> </div> </div> )} {isLoading && ( - <div className="w-full flex items-center justify-center mt-6 text-white/70 py-6"> + <div className="w-full flex items-center justify-center mt-6 text-black/70 dark:text-white/70 py-6"> <RefreshCcw className="animate-spin" /> </div> )} <div className="w-full mt-6 space-y-2"> - <p className="text-xs text-white/50"> + <p className="text-xs text-black/50 dark:text-white/50"> We'll refresh the page after updating the settings. </p> <button @@ -403,8 +516,8 @@ const SettingsDialog = ({ )} </button> </div> - </Dialog.Panel> - </Transition.Child> + </DialogPanel> + </TransitionChild> </div> </div> </Dialog> diff --git a/ui/components/Sidebar.tsx b/ui/components/Sidebar.tsx index aef1153..cc2097d 100644 --- a/ui/components/Sidebar.tsx +++ b/ui/components/Sidebar.tsx @@ -4,11 +4,16 @@ import { cn } from '@/lib/utils'; import { BookOpenText, Home, Search, SquarePen, Settings } from 'lucide-react'; import Link from 'next/link'; import { useSelectedLayoutSegments } from 'next/navigation'; -import React, { Fragment, useState } from 'react'; +import React, { useState, type ReactNode } from 'react'; import Layout from './Layout'; -import { Dialog, Transition } from '@headlessui/react'; import SettingsDialog from './SettingsDialog'; +const VerticalIconContainer = ({ children }: { children: ReactNode }) => { + return ( + <div className="flex flex-col items-center gap-y-3 w-full">{children}</div> + ); +}; + const Sidebar = ({ children }: { children: React.ReactNode }) => { const segments = useSelectedLayoutSegments(); @@ -18,7 +23,7 @@ const Sidebar = ({ children }: { children: React.ReactNode }) => { { icon: Home, href: '/', - active: segments.length === 0, + active: segments.length === 0 || segments.includes('c'), label: 'Home', }, { @@ -38,31 +43,35 @@ const Sidebar = ({ children }: { children: React.ReactNode }) => { return ( <div> <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-[#111111] 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"> <a href="/"> - <SquarePen className="text-white cursor-pointer" /> + <SquarePen className="cursor-pointer" /> </a> - <div className="flex flex-col items-center gap-y-3 w-full"> + <VerticalIconContainer> {navLinks.map((link, i) => ( <Link key={i} href={link.href} className={cn( - 'relative flex flex-row items-center justify-center cursor-pointer hover:bg-white/10 hover:text-white duration-150 transition w-full py-2 rounded-lg', - link.active ? 'text-white' : 'text-white/70', + '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', + 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-white" /> + <div className="absolute right-0 -mr-2 h-full w-1 rounded-l-lg bg-black dark:bg-white" /> )} </Link> ))} - </div> + </VerticalIconContainer> + <Settings onClick={() => setIsSettingsOpen(!isSettingsOpen)} - className="text-white cursor-pointer" + className="cursor-pointer" /> + <SettingsDialog isOpen={isSettingsOpen} setIsOpen={setIsSettingsOpen} @@ -70,18 +79,20 @@ const Sidebar = ({ children }: { children: React.ReactNode }) => { </div> </div> - <div className="fixed bottom-0 w-full z-50 flex flex-row items-center gap-x-6 bg-[#111111] px-4 py-4 shadow-sm lg:hidden"> + <div className="fixed bottom-0 w-full z-50 flex flex-row items-center gap-x-6 bg-light-primary dark:bg-dark-primary px-4 py-4 shadow-sm lg:hidden"> {navLinks.map((link, i) => ( <Link href={link.href} key={i} className={cn( 'relative flex flex-col items-center space-y-1 text-center w-full', - link.active ? 'text-white' : 'text-white/70', + link.active + ? 'text-black dark:text-white' + : 'text-black dark:text-white/70', )} > {link.active && ( - <div className="absolute top-0 -mt-4 h-1 w-full rounded-b-lg bg-white" /> + <div className="absolute top-0 -mt-4 h-1 w-full rounded-b-lg bg-black dark:bg-white" /> )} <link.icon /> <p className="text-xs">{link.label}</p> diff --git a/ui/components/theme/Provider.tsx b/ui/components/theme/Provider.tsx new file mode 100644 index 0000000..43e2714 --- /dev/null +++ b/ui/components/theme/Provider.tsx @@ -0,0 +1,16 @@ +'use client'; +import { ThemeProvider } from 'next-themes'; + +const ThemeProviderComponent = ({ + children, +}: { + children: React.ReactNode; +}) => { + return ( + <ThemeProvider attribute="class" enableSystem={false} defaultTheme="dark"> + {children} + </ThemeProvider> + ); +}; + +export default ThemeProviderComponent; diff --git a/ui/components/theme/Switcher.tsx b/ui/components/theme/Switcher.tsx new file mode 100644 index 0000000..43bbdc8 --- /dev/null +++ b/ui/components/theme/Switcher.tsx @@ -0,0 +1,61 @@ +'use client'; +import { useTheme } from 'next-themes'; +import { SunIcon, MoonIcon, MonitorIcon } from 'lucide-react'; +import { useCallback, useEffect, useState } from 'react'; +import { Select } from '../SettingsDialog'; + +type Theme = 'dark' | 'light' | 'system'; + +const ThemeSwitcher = ({ className }: { className?: string }) => { + const [mounted, setMounted] = useState(false); + + const { theme, setTheme } = useTheme(); + + const isTheme = useCallback((t: Theme) => t === theme, [theme]); + + const handleThemeSwitch = (theme: Theme) => { + setTheme(theme); + }; + + useEffect(() => { + setMounted(true); + }, []); + + useEffect(() => { + if (isTheme('system')) { + const preferDarkScheme = window.matchMedia( + '(prefers-color-scheme: dark)', + ); + + const detectThemeChange = (event: MediaQueryListEvent) => { + const theme: Theme = event.matches ? 'dark' : 'light'; + setTheme(theme); + }; + + preferDarkScheme.addEventListener('change', detectThemeChange); + + return () => { + preferDarkScheme.removeEventListener('change', detectThemeChange); + }; + } + }, [isTheme, setTheme, theme]); + + // Avoid Hydration Mismatch + if (!mounted) { + return null; + } + + return ( + <Select + className={className} + value={theme} + onChange={(e) => handleThemeSwitch(e.target.value as Theme)} + options={[ + { value: 'light', label: 'Light' }, + { value: 'dark', label: 'Dark' }, + ]} + /> + ); +}; + +export default ThemeSwitcher; diff --git a/ui/lib/actions.ts b/ui/lib/actions.ts index d7eb71f..a4409b0 100644 --- a/ui/lib/actions.ts +++ b/ui/lib/actions.ts @@ -4,15 +4,24 @@ export const getSuggestions = async (chatHisory: Message[]) => { const chatModel = localStorage.getItem('chatModel'); 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`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ - chat_history: chatHisory, - chat_model: chatModel, - chat_model_provider: chatModelProvider, + chatHistory: chatHisory, + chatModel: { + provider: chatModelProvider, + model: chatModel, + ...(chatModelProvider === 'custom_openai' && { + customOpenAIKey, + customOpenAIBaseURL, + }), + }, }), }); diff --git a/ui/lib/utils.ts b/ui/lib/utils.ts index 6b35b90..30d6da5 100644 --- a/ui/lib/utils.ts +++ b/ui/lib/utils.ts @@ -3,7 +3,13 @@ import { twMerge } from 'tailwind-merge'; export const cn = (...classes: ClassValue[]) => twMerge(clsx(...classes)); -export const formatTimeDifference = (date1: Date, date2: Date): string => { +export const formatTimeDifference = ( + date1: Date | string, + date2: Date | string, +): string => { + date1 = new Date(date1); + date2 = new Date(date2); + const diffInSeconds = Math.floor( Math.abs(date2.getTime() - date1.getTime()) / 1000, ); diff --git a/ui/package.json b/ui/package.json index ff61082..a8826dc 100644 --- a/ui/package.json +++ b/ui/package.json @@ -1,6 +1,6 @@ { "name": "perplexica-frontend", - "version": "1.5.0", + "version": "1.10.0-rc2", "license": "MIT", "author": "ItzCrazyKns", "scripts": { @@ -11,15 +11,16 @@ "format:write": "prettier . --write" }, "dependencies": { - "@headlessui/react": "^1.7.18", + "@headlessui/react": "^2.2.0", "@icons-pack/react-simple-icons": "^9.4.0", "@langchain/openai": "^0.0.25", "@tailwindcss/typography": "^0.5.12", "clsx": "^2.1.0", "langchain": "^0.1.30", "lucide-react": "^0.363.0", - "markdown-to-jsx": "^7.4.5", + "markdown-to-jsx": "^7.7.2", "next": "14.1.4", + "next-themes": "^0.3.0", "react": "^18", "react-dom": "^18", "react-text-to-speech": "^0.14.5", diff --git a/ui/tailwind.config.ts b/ui/tailwind.config.ts index 05f107d..00ae10a 100644 --- a/ui/tailwind.config.ts +++ b/ui/tailwind.config.ts @@ -1,4 +1,17 @@ import type { Config } from 'tailwindcss'; +import type { DefaultColors } from 'tailwindcss/types/generated/colors'; + +const themeDark = (colors: DefaultColors) => ({ + 50: '#0a0a0a', + 100: '#111111', + 200: '#1c1c1c', +}); + +const themeLight = (colors: DefaultColors) => ({ + 50: '#fcfcf9', + 100: '#f3f3ee', + 200: '#e8e8e3', +}); const config: Config = { content: [ @@ -6,8 +19,33 @@ const config: Config = { './components/**/*.{js,ts,jsx,tsx,mdx}', './app/**/*.{js,ts,jsx,tsx,mdx}', ], + darkMode: 'class', theme: { - extend: {}, + extend: { + borderColor: ({ colors }) => { + return { + light: themeLight(colors), + dark: themeDark(colors), + }; + }, + colors: ({ colors }) => { + const colorsDark = themeDark(colors); + const colorsLight = themeLight(colors); + + return { + dark: { + primary: colorsDark[50], + secondary: colorsDark[100], + ...colorsDark, + }, + light: { + primary: colorsLight[50], + secondary: colorsLight[100], + ...colorsLight, + }, + }; + }, + }, }, plugins: [require('@tailwindcss/typography')], }; diff --git a/ui/yarn.lock b/ui/yarn.lock index ec8b3d7..7eb109f 100644 --- a/ui/yarn.lock +++ b/ui/yarn.lock @@ -66,13 +66,51 @@ resolved "https://registry.yarnpkg.com/@eslint/js/-/js-8.57.0.tgz#a5417ae8427873f1dd08b70b3574b453e67b5f7f" integrity sha512-Ys+3g2TaW7gADOJzPt83SJtCDhMjndcDMFVQ/Tj9iA1BfJzFKD9mAUXT3OenpuPHbI6P/myECxRJrofUsDx/5g== -"@headlessui/react@^1.7.18": - version "1.7.18" - resolved "https://registry.yarnpkg.com/@headlessui/react/-/react-1.7.18.tgz#30af4634d2215b2ca1aa29d07f33d02bea82d9d7" - integrity sha512-4i5DOrzwN4qSgNsL4Si61VMkUcWbcSKueUV7sFhpHzQcSShdlHENE5+QBntMSRvHt8NyoFO2AGG8si9lq+w4zQ== +"@floating-ui/core@^1.6.0": + version "1.6.8" + resolved "https://registry.yarnpkg.com/@floating-ui/core/-/core-1.6.8.tgz#aa43561be075815879305965020f492cdb43da12" + integrity sha512-7XJ9cPU+yI2QeLS+FCSlqNFZJq8arvswefkZrYI1yQBbftw6FyrZOxYSh+9S7z7TpeWlRt9zJ5IhM1WIL334jA== dependencies: - "@tanstack/react-virtual" "^3.0.0-beta.60" - client-only "^0.0.1" + "@floating-ui/utils" "^0.2.8" + +"@floating-ui/dom@^1.0.0": + version "1.6.12" + resolved "https://registry.yarnpkg.com/@floating-ui/dom/-/dom-1.6.12.tgz#6333dcb5a8ead3b2bf82f33d6bc410e95f54e556" + integrity sha512-NP83c0HjokcGVEMeoStg317VD9W7eDlGK7457dMBANbKA6GJZdc7rjujdgqzTaz93jkGgc5P/jeWbaCHnMNc+w== + 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.28" + resolved "https://registry.yarnpkg.com/@floating-ui/react/-/react-0.26.28.tgz#93f44ebaeb02409312e9df9507e83aab4a8c0dc7" + integrity sha512-yORQuuAtVpiRjpMhdc0wJj06b9JFjrYF4qp96j++v2NBpbi6SEGF7donUJ3TMieerQ6qVkAv1tgr7L4r5roTqw== + 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.2.0": + version "2.2.0" + resolved "https://registry.yarnpkg.com/@headlessui/react/-/react-2.2.0.tgz#a8e32f0899862849a1ce1615fa280e7891431ab7" + integrity sha512-RzCEg+LXsuI7mHiSomsu/gBJSjpupm6A1qIZ5sWjd7JhARNlMiSA4kKfJpCKwU9tE+zMRterhhrP74PvfJrpXQ== + 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": version "0.11.14" @@ -278,6 +316,57 @@ resolved "https://registry.yarnpkg.com/@pkgjs/parseargs/-/parseargs-0.11.0.tgz#a77ea742fab25775145434eb1d2328cf5013ac33" integrity sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg== +"@react-aria/focus@^3.17.1": + version "3.18.4" + resolved "https://registry.yarnpkg.com/@react-aria/focus/-/focus-3.18.4.tgz#a6e95896bc8680d1b5bcd855e983fc2c195a1a55" + integrity sha512-91J35077w9UNaMK1cpMUEFRkNNz0uZjnSwiyBCFuRdaVuivO53wNC9XtWSDNDdcO5cGy87vfJRVAiyoCn/mjqA== + dependencies: + "@react-aria/interactions" "^3.22.4" + "@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.4": + version "3.22.4" + resolved "https://registry.yarnpkg.com/@react-aria/interactions/-/interactions-3.22.4.tgz#88ed61ab6a485f869bc1f65ae6688d48ca96064b" + integrity sha512-E0vsgtpItmknq/MJELqYJwib+YN18Qag8nroqwjk1qOnBa9ROIkUhWJerLi1qs5diXq9LHKehZDXRlwPvdEFww== + 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": version "1.10.1" resolved "https://registry.yarnpkg.com/@rushstack/eslint-patch/-/eslint-patch-1.10.1.tgz#7ca168b6937818e9a74b47ac4e2112b2e1a024cf" @@ -290,6 +379,13 @@ dependencies: tslib "^2.4.0" +"@swc/helpers@^0.5.0": + version "0.5.15" + resolved "https://registry.yarnpkg.com/@swc/helpers/-/helpers-0.5.15.tgz#79efab344c5819ecf83a43f3f9f811fc84b516d7" + integrity sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g== + dependencies: + tslib "^2.8.0" + "@tailwindcss/typography@^0.5.12": version "0.5.12" resolved "https://registry.yarnpkg.com/@tailwindcss/typography/-/typography-0.5.12.tgz#c0532fd594427b7f4e8e38eff7bf272c63a1dca4" @@ -300,17 +396,17 @@ lodash.merge "^4.6.2" postcss-selector-parser "6.0.10" -"@tanstack/react-virtual@^3.0.0-beta.60": - version "3.2.0" - resolved "https://registry.yarnpkg.com/@tanstack/react-virtual/-/react-virtual-3.2.0.tgz#fb70f9c6baee753a5a0f7618ac886205d5a02af9" - integrity sha512-OEdMByf2hEfDa6XDbGlZN8qO6bTjlNKqjM3im9JG+u3mCL8jALy0T/67oDI001raUUPh1Bdmfn4ZvPOV5knpcg== +"@tanstack/react-virtual@^3.8.1": + version "3.10.9" + resolved "https://registry.yarnpkg.com/@tanstack/react-virtual/-/react-virtual-3.10.9.tgz#40606b6dd8aba8e977f576d8f7df07f69ca63eea" + integrity sha512-OXO2uBjFqA4Ibr2O3y0YMnkrRWGVNqcvHQXmGvMu6IK8chZl3PrDxFXdGZ2iZkSrKh3/qUYoFqYe+Rx23RoU0g== dependencies: - "@tanstack/virtual-core" "3.2.0" + "@tanstack/virtual-core" "3.10.9" -"@tanstack/virtual-core@3.2.0": - version "3.2.0" - resolved "https://registry.yarnpkg.com/@tanstack/virtual-core/-/virtual-core-3.2.0.tgz#874d36135e4badce2719e7bdc556ce240cbaff14" - integrity sha512-P5XgYoAw/vfW65byBbJQCw+cagdXDT/qH6wmABiLt4v4YBT2q2vqCOhihe+D1Nt325F/S/0Tkv6C5z0Lv+VBQQ== +"@tanstack/virtual-core@3.10.9": + version "3.10.9" + resolved "https://registry.yarnpkg.com/@tanstack/virtual-core/-/virtual-core-3.10.9.tgz#55710c92b311fdaa8d8c66682a0dbdd684bc77c4" + integrity sha512-kBknKOKzmeR7lN+vSadaKWXaLS0SZZG+oqpQ/k80Q6g9REn6zRHS/ZYdrIzHnpHgy/eWs00SujveUN/GJT2qTw== "@types/json5@^0.0.29": version "0.0.29" @@ -779,11 +875,16 @@ chokidar@^3.5.3: optionalDependencies: fsevents "~2.3.2" -client-only@0.0.1, client-only@^0.0.1: +client-only@0.0.1: version "0.0.1" resolved "https://registry.yarnpkg.com/client-only/-/client-only-0.0.1.tgz#38bba5d403c41ab150bff64a95c85013cf73bca1" 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: version "2.1.0" resolved "https://registry.yarnpkg.com/clsx/-/clsx-2.1.0.tgz#e851283bcb5c80ee7608db18487433f7b23f77cb" @@ -2109,10 +2210,10 @@ lucide-react@^0.363.0: resolved "https://registry.yarnpkg.com/lucide-react/-/lucide-react-0.363.0.tgz#2bb1f9d09b830dda86f5118fcd097f87247fe0e3" integrity sha512-AlsfPCsXQyQx7wwsIgzcKOL9LwC498LIMAo+c0Es5PkHJa33xwmYAkkSoKoJWWWSYQEStqu58/jT4tL2gi32uQ== -markdown-to-jsx@^7.4.5: - version "7.4.6" - resolved "https://registry.yarnpkg.com/markdown-to-jsx/-/markdown-to-jsx-7.4.6.tgz#1ea0018c549bf00c9ce35e8f4ea57e48028d9cf7" - integrity sha512-3cyNxI/PwotvYkjg6KmFaN1uyN/7NqETteD2DobBB8ro/FR9jsHIh4Fi7ywAz0s9QHRKCmGlOUggs5GxSWACKA== +markdown-to-jsx@^7.7.2: + version "7.7.2" + resolved "https://registry.yarnpkg.com/markdown-to-jsx/-/markdown-to-jsx-7.7.2.tgz#59c1dd64f48b53719311ab140be3cd51cdabccd3" + integrity sha512-N3AKfYRvxNscvcIH6HDnDKILp4S8UWbebp+s92Y8SwIq0CuSbLW4Jgmrbjku3CWKjTQO0OyIMS6AhzqrwjEa3g== md5@^2.3.0: version "2.3.0" @@ -2244,6 +2345,11 @@ natural-compare@^1.4.0: resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7" integrity sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw== +next-themes@^0.3.0: + version "0.3.0" + resolved "https://registry.yarnpkg.com/next-themes/-/next-themes-0.3.0.tgz#b4d2a866137a67d42564b07f3a3e720e2ff3871a" + integrity sha512-/QHIrsYpd6Kfk7xakK4svpDI5mmXP0gfvCoJdGpZQ2TOrQZmsW0QxjaiLn8wbIKjtm4BTSqLoix4lxYYOnLJ/w== + next@14.1.4: version "14.1.4" resolved "https://registry.yarnpkg.com/next/-/next-14.1.4.tgz#203310f7310578563fd5c961f0db4729ce7a502d" @@ -2854,8 +2960,16 @@ streamsearch@^1.1.0: resolved "https://registry.yarnpkg.com/streamsearch/-/streamsearch-1.1.0.tgz#404dd1e2247ca94af554e841a8ef0eaa238da764" integrity sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg== -"string-width-cjs@npm:string-width@^4.2.0", string-width@^4.1.0: - name string-width-cjs +"string-width-cjs@npm:string-width@^4.2.0": + version "4.2.3" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" + integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== + dependencies: + emoji-regex "^8.0.0" + is-fullwidth-code-point "^3.0.0" + strip-ansi "^6.0.1" + +string-width@^4.1.0: version "4.2.3" resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== @@ -2919,7 +3033,14 @@ string.prototype.trimstart@^1.0.8: define-properties "^1.2.1" es-object-atoms "^1.0.0" -"strip-ansi-cjs@npm:strip-ansi@^6.0.1", strip-ansi@^6.0.0, strip-ansi@^6.0.1: +"strip-ansi-cjs@npm:strip-ansi@^6.0.1": + version "6.0.1" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" + integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== + dependencies: + ansi-regex "^5.0.1" + +strip-ansi@^6.0.0, strip-ansi@^6.0.1: version "6.0.1" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== @@ -2975,6 +3096,11 @@ 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" 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: version "2.2.2" resolved "https://registry.yarnpkg.com/tailwind-merge/-/tailwind-merge-2.2.2.tgz#87341e7604f0e20499939e152cd2841f41f7a3df" @@ -3066,10 +3192,10 @@ tsconfig-paths@^3.15.0: minimist "^1.2.6" strip-bom "^3.0.0" -tslib@^2.4.0: - version "2.6.2" - resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.6.2.tgz#703ac29425e7b37cd6fd456e92404d46d1f3e4ae" - integrity sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q== +tslib@^2.4.0, tslib@^2.8.0: + version "2.8.1" + resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.8.1.tgz#612efe4ed235d567e8aba5f2a5fab70280ade83f" + integrity sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w== type-check@^0.4.0, type-check@~0.4.0: version "0.4.0" diff --git a/uploads/.gitignore b/uploads/.gitignore new file mode 100644 index 0000000..d6b7ef3 --- /dev/null +++ b/uploads/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/yarn.lock b/yarn.lock index 6ec0ff2..5764b3c 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2,6 +2,20 @@ # yarn lockfile v1 +"@anthropic-ai/sdk@^0.22.0": + version "0.22.0" + resolved "https://registry.yarnpkg.com/@anthropic-ai/sdk/-/sdk-0.22.0.tgz#548e4218d9810fd494e595d4e57cb2d46d301a1a" + integrity sha512-dv4BCC6FZJw3w66WNLsHlUFjhu19fS1L/5jMPApwhZLa/Oy1j0A2i3RypmDtHEPp4Wwg3aZkSHksp7VzYWjzmw== + dependencies: + "@types/node" "^18.11.18" + "@types/node-fetch" "^2.6.4" + abort-controller "^3.0.0" + agentkeepalive "^4.2.1" + form-data-encoder "1.7.2" + formdata-node "^4.3.2" + node-fetch "^2.6.7" + web-streams-polyfill "^3.2.1" + "@anthropic-ai/sdk@^0.9.1": version "0.9.1" resolved "https://registry.yarnpkg.com/@anthropic-ai/sdk/-/sdk-0.9.1.tgz#b2d2b7bf05c90dce502c9a2e869066870f69ba88" @@ -38,6 +52,252 @@ enabled "2.0.x" kuler "^2.0.0" +"@esbuild-kit/core-utils@^3.3.2": + version "3.3.2" + resolved "https://registry.yarnpkg.com/@esbuild-kit/core-utils/-/core-utils-3.3.2.tgz#186b6598a5066f0413471d7c4d45828e399ba96c" + integrity sha512-sPRAnw9CdSsRmEtnsl2WXWdyquogVpB3yZ3dgwJfe8zrOzTsV7cJvmwrKVa+0ma5BoiGJ+BoqkMvawbayKUsqQ== + dependencies: + esbuild "~0.18.20" + source-map-support "^0.5.21" + +"@esbuild-kit/esm-loader@^2.5.5": + version "2.6.5" + resolved "https://registry.yarnpkg.com/@esbuild-kit/esm-loader/-/esm-loader-2.6.5.tgz#6eedee46095d7d13b1efc381e2211ed1c60e64ea" + integrity sha512-FxEMIkJKnodyA1OaCUoEvbYRkoZlLZ4d/eXFu9Fh8CbBBgP5EmZxrfTRyN0qpXZ4vOvqnE5YdRdcrmUUXuU+dA== + dependencies: + "@esbuild-kit/core-utils" "^3.3.2" + get-tsconfig "^4.7.0" + +"@esbuild/aix-ppc64@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/aix-ppc64/-/aix-ppc64-0.19.12.tgz#d1bc06aedb6936b3b6d313bf809a5a40387d2b7f" + integrity sha512-bmoCYyWdEL3wDQIVbcyzRyeKLgk2WtWLTWz1ZIAZF/EGbNOwSA6ew3PftJ1PqMiOOGu0OyFMzG53L0zqIpPeNA== + +"@esbuild/android-arm64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/android-arm64/-/android-arm64-0.18.20.tgz#984b4f9c8d0377443cc2dfcef266d02244593622" + integrity sha512-Nz4rJcchGDtENV0eMKUNa6L12zz2zBDXuhj/Vjh18zGqB44Bi7MBMSXjgunJgjRhCmKOjnPuZp4Mb6OKqtMHLQ== + +"@esbuild/android-arm64@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/android-arm64/-/android-arm64-0.19.12.tgz#7ad65a36cfdb7e0d429c353e00f680d737c2aed4" + integrity sha512-P0UVNGIienjZv3f5zq0DP3Nt2IE/3plFzuaS96vihvD0Hd6H/q4WXUGpCxD/E8YrSXfNyRPbpTq+T8ZQioSuPA== + +"@esbuild/android-arm@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/android-arm/-/android-arm-0.18.20.tgz#fedb265bc3a589c84cc11f810804f234947c3682" + integrity sha512-fyi7TDI/ijKKNZTUJAQqiG5T7YjJXgnzkURqmGj13C6dCqckZBLdl4h7bkhHt/t0WP+zO9/zwroDvANaOqO5Sw== + +"@esbuild/android-arm@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/android-arm/-/android-arm-0.19.12.tgz#b0c26536f37776162ca8bde25e42040c203f2824" + integrity sha512-qg/Lj1mu3CdQlDEEiWrlC4eaPZ1KztwGJ9B6J+/6G+/4ewxJg7gqj8eVYWvao1bXrqGiW2rsBZFSX3q2lcW05w== + +"@esbuild/android-x64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/android-x64/-/android-x64-0.18.20.tgz#35cf419c4cfc8babe8893d296cd990e9e9f756f2" + integrity sha512-8GDdlePJA8D6zlZYJV/jnrRAi6rOiNaCC/JclcXpB+KIuvfBN4owLtgzY2bsxnx666XjJx2kDPUmnTtR8qKQUg== + +"@esbuild/android-x64@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/android-x64/-/android-x64-0.19.12.tgz#cb13e2211282012194d89bf3bfe7721273473b3d" + integrity sha512-3k7ZoUW6Q6YqhdhIaq/WZ7HwBpnFBlW905Fa4s4qWJyiNOgT1dOqDiVAQFwBH7gBRZr17gLrlFCRzF6jFh7Kew== + +"@esbuild/darwin-arm64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/darwin-arm64/-/darwin-arm64-0.18.20.tgz#08172cbeccf95fbc383399a7f39cfbddaeb0d7c1" + integrity sha512-bxRHW5kHU38zS2lPTPOyuyTm+S+eobPUnTNkdJEfAddYgEcll4xkT8DB9d2008DtTbl7uJag2HuE5NZAZgnNEA== + +"@esbuild/darwin-arm64@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/darwin-arm64/-/darwin-arm64-0.19.12.tgz#cbee41e988020d4b516e9d9e44dd29200996275e" + integrity sha512-B6IeSgZgtEzGC42jsI+YYu9Z3HKRxp8ZT3cqhvliEHovq8HSX2YX8lNocDn79gCKJXOSaEot9MVYky7AKjCs8g== + +"@esbuild/darwin-x64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/darwin-x64/-/darwin-x64-0.18.20.tgz#d70d5790d8bf475556b67d0f8b7c5bdff053d85d" + integrity sha512-pc5gxlMDxzm513qPGbCbDukOdsGtKhfxD1zJKXjCCcU7ju50O7MeAZ8c4krSJcOIJGFR+qx21yMMVYwiQvyTyQ== + +"@esbuild/darwin-x64@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/darwin-x64/-/darwin-x64-0.19.12.tgz#e37d9633246d52aecf491ee916ece709f9d5f4cd" + integrity sha512-hKoVkKzFiToTgn+41qGhsUJXFlIjxI/jSYeZf3ugemDYZldIXIxhvwN6erJGlX4t5h417iFuheZ7l+YVn05N3A== + +"@esbuild/freebsd-arm64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/freebsd-arm64/-/freebsd-arm64-0.18.20.tgz#98755cd12707f93f210e2494d6a4b51b96977f54" + integrity sha512-yqDQHy4QHevpMAaxhhIwYPMv1NECwOvIpGCZkECn8w2WFHXjEwrBn3CeNIYsibZ/iZEUemj++M26W3cNR5h+Tw== + +"@esbuild/freebsd-arm64@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/freebsd-arm64/-/freebsd-arm64-0.19.12.tgz#1ee4d8b682ed363b08af74d1ea2b2b4dbba76487" + integrity sha512-4aRvFIXmwAcDBw9AueDQ2YnGmz5L6obe5kmPT8Vd+/+x/JMVKCgdcRwH6APrbpNXsPz+K653Qg8HB/oXvXVukA== + +"@esbuild/freebsd-x64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/freebsd-x64/-/freebsd-x64-0.18.20.tgz#c1eb2bff03915f87c29cece4c1a7fa1f423b066e" + integrity sha512-tgWRPPuQsd3RmBZwarGVHZQvtzfEBOreNuxEMKFcd5DaDn2PbBxfwLcj4+aenoh7ctXcbXmOQIn8HI6mCSw5MQ== + +"@esbuild/freebsd-x64@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/freebsd-x64/-/freebsd-x64-0.19.12.tgz#37a693553d42ff77cd7126764b535fb6cc28a11c" + integrity sha512-EYoXZ4d8xtBoVN7CEwWY2IN4ho76xjYXqSXMNccFSx2lgqOG/1TBPW0yPx1bJZk94qu3tX0fycJeeQsKovA8gg== + +"@esbuild/linux-arm64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/linux-arm64/-/linux-arm64-0.18.20.tgz#bad4238bd8f4fc25b5a021280c770ab5fc3a02a0" + integrity sha512-2YbscF+UL7SQAVIpnWvYwM+3LskyDmPhe31pE7/aoTMFKKzIc9lLbyGUpmmb8a8AixOL61sQ/mFh3jEjHYFvdA== + +"@esbuild/linux-arm64@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/linux-arm64/-/linux-arm64-0.19.12.tgz#be9b145985ec6c57470e0e051d887b09dddb2d4b" + integrity sha512-EoTjyYyLuVPfdPLsGVVVC8a0p1BFFvtpQDB/YLEhaXyf/5bczaGeN15QkR+O4S5LeJ92Tqotve7i1jn35qwvdA== + +"@esbuild/linux-arm@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/linux-arm/-/linux-arm-0.18.20.tgz#3e617c61f33508a27150ee417543c8ab5acc73b0" + integrity sha512-/5bHkMWnq1EgKr1V+Ybz3s1hWXok7mDFUMQ4cG10AfW3wL02PSZi5kFpYKrptDsgb2WAJIvRcDm+qIvXf/apvg== + +"@esbuild/linux-arm@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/linux-arm/-/linux-arm-0.19.12.tgz#207ecd982a8db95f7b5279207d0ff2331acf5eef" + integrity sha512-J5jPms//KhSNv+LO1S1TX1UWp1ucM6N6XuL6ITdKWElCu8wXP72l9MM0zDTzzeikVyqFE6U8YAV9/tFyj0ti+w== + +"@esbuild/linux-ia32@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/linux-ia32/-/linux-ia32-0.18.20.tgz#699391cccba9aee6019b7f9892eb99219f1570a7" + integrity sha512-P4etWwq6IsReT0E1KHU40bOnzMHoH73aXp96Fs8TIT6z9Hu8G6+0SHSw9i2isWrD2nbx2qo5yUqACgdfVGx7TA== + +"@esbuild/linux-ia32@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/linux-ia32/-/linux-ia32-0.19.12.tgz#d0d86b5ca1562523dc284a6723293a52d5860601" + integrity sha512-Thsa42rrP1+UIGaWz47uydHSBOgTUnwBwNq59khgIwktK6x60Hivfbux9iNR0eHCHzOLjLMLfUMLCypBkZXMHA== + +"@esbuild/linux-loong64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/linux-loong64/-/linux-loong64-0.18.20.tgz#e6fccb7aac178dd2ffb9860465ac89d7f23b977d" + integrity sha512-nXW8nqBTrOpDLPgPY9uV+/1DjxoQ7DoB2N8eocyq8I9XuqJ7BiAMDMf9n1xZM9TgW0J8zrquIb/A7s3BJv7rjg== + +"@esbuild/linux-loong64@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/linux-loong64/-/linux-loong64-0.19.12.tgz#9a37f87fec4b8408e682b528391fa22afd952299" + integrity sha512-LiXdXA0s3IqRRjm6rV6XaWATScKAXjI4R4LoDlvO7+yQqFdlr1Bax62sRwkVvRIrwXxvtYEHHI4dm50jAXkuAA== + +"@esbuild/linux-mips64el@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/linux-mips64el/-/linux-mips64el-0.18.20.tgz#eeff3a937de9c2310de30622a957ad1bd9183231" + integrity sha512-d5NeaXZcHp8PzYy5VnXV3VSd2D328Zb+9dEq5HE6bw6+N86JVPExrA6O68OPwobntbNJ0pzCpUFZTo3w0GyetQ== + +"@esbuild/linux-mips64el@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/linux-mips64el/-/linux-mips64el-0.19.12.tgz#4ddebd4e6eeba20b509d8e74c8e30d8ace0b89ec" + integrity sha512-fEnAuj5VGTanfJ07ff0gOA6IPsvrVHLVb6Lyd1g2/ed67oU1eFzL0r9WL7ZzscD+/N6i3dWumGE1Un4f7Amf+w== + +"@esbuild/linux-ppc64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/linux-ppc64/-/linux-ppc64-0.18.20.tgz#2f7156bde20b01527993e6881435ad79ba9599fb" + integrity sha512-WHPyeScRNcmANnLQkq6AfyXRFr5D6N2sKgkFo2FqguP44Nw2eyDlbTdZwd9GYk98DZG9QItIiTlFLHJHjxP3FA== + +"@esbuild/linux-ppc64@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/linux-ppc64/-/linux-ppc64-0.19.12.tgz#adb67dadb73656849f63cd522f5ecb351dd8dee8" + integrity sha512-nYJA2/QPimDQOh1rKWedNOe3Gfc8PabU7HT3iXWtNUbRzXS9+vgB0Fjaqr//XNbd82mCxHzik2qotuI89cfixg== + +"@esbuild/linux-riscv64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/linux-riscv64/-/linux-riscv64-0.18.20.tgz#6628389f210123d8b4743045af8caa7d4ddfc7a6" + integrity sha512-WSxo6h5ecI5XH34KC7w5veNnKkju3zBRLEQNY7mv5mtBmrP/MjNBCAlsM2u5hDBlS3NGcTQpoBvRzqBcRtpq1A== + +"@esbuild/linux-riscv64@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/linux-riscv64/-/linux-riscv64-0.19.12.tgz#11bc0698bf0a2abf8727f1c7ace2112612c15adf" + integrity sha512-2MueBrlPQCw5dVJJpQdUYgeqIzDQgw3QtiAHUC4RBz9FXPrskyyU3VI1hw7C0BSKB9OduwSJ79FTCqtGMWqJHg== + +"@esbuild/linux-s390x@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/linux-s390x/-/linux-s390x-0.18.20.tgz#255e81fb289b101026131858ab99fba63dcf0071" + integrity sha512-+8231GMs3mAEth6Ja1iK0a1sQ3ohfcpzpRLH8uuc5/KVDFneH6jtAJLFGafpzpMRO6DzJ6AvXKze9LfFMrIHVQ== + +"@esbuild/linux-s390x@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/linux-s390x/-/linux-s390x-0.19.12.tgz#e86fb8ffba7c5c92ba91fc3b27ed5a70196c3cc8" + integrity sha512-+Pil1Nv3Umes4m3AZKqA2anfhJiVmNCYkPchwFJNEJN5QxmTs1uzyy4TvmDrCRNT2ApwSari7ZIgrPeUx4UZDg== + +"@esbuild/linux-x64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/linux-x64/-/linux-x64-0.18.20.tgz#c7690b3417af318a9b6f96df3031a8865176d338" + integrity sha512-UYqiqemphJcNsFEskc73jQ7B9jgwjWrSayxawS6UVFZGWrAAtkzjxSqnoclCXxWtfwLdzU+vTpcNYhpn43uP1w== + +"@esbuild/linux-x64@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/linux-x64/-/linux-x64-0.19.12.tgz#5f37cfdc705aea687dfe5dfbec086a05acfe9c78" + integrity sha512-B71g1QpxfwBvNrfyJdVDexenDIt1CiDN1TIXLbhOw0KhJzE78KIFGX6OJ9MrtC0oOqMWf+0xop4qEU8JrJTwCg== + +"@esbuild/netbsd-x64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/netbsd-x64/-/netbsd-x64-0.18.20.tgz#30e8cd8a3dded63975e2df2438ca109601ebe0d1" + integrity sha512-iO1c++VP6xUBUmltHZoMtCUdPlnPGdBom6IrO4gyKPFFVBKioIImVooR5I83nTew5UOYrk3gIJhbZh8X44y06A== + +"@esbuild/netbsd-x64@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/netbsd-x64/-/netbsd-x64-0.19.12.tgz#29da566a75324e0d0dd7e47519ba2f7ef168657b" + integrity sha512-3ltjQ7n1owJgFbuC61Oj++XhtzmymoCihNFgT84UAmJnxJfm4sYCiSLTXZtE00VWYpPMYc+ZQmB6xbSdVh0JWA== + +"@esbuild/openbsd-x64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/openbsd-x64/-/openbsd-x64-0.18.20.tgz#7812af31b205055874c8082ea9cf9ab0da6217ae" + integrity sha512-e5e4YSsuQfX4cxcygw/UCPIEP6wbIL+se3sxPdCiMbFLBWu0eiZOJ7WoD+ptCLrmjZBK1Wk7I6D/I3NglUGOxg== + +"@esbuild/openbsd-x64@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/openbsd-x64/-/openbsd-x64-0.19.12.tgz#306c0acbdb5a99c95be98bdd1d47c916e7dc3ff0" + integrity sha512-RbrfTB9SWsr0kWmb9srfF+L933uMDdu9BIzdA7os2t0TXhCRjrQyCeOt6wVxr79CKD4c+p+YhCj31HBkYcXebw== + +"@esbuild/sunos-x64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/sunos-x64/-/sunos-x64-0.18.20.tgz#d5c275c3b4e73c9b0ecd38d1ca62c020f887ab9d" + integrity sha512-kDbFRFp0YpTQVVrqUd5FTYmWo45zGaXe0X8E1G/LKFC0v8x0vWrhOWSLITcCn63lmZIxfOMXtCfti/RxN/0wnQ== + +"@esbuild/sunos-x64@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/sunos-x64/-/sunos-x64-0.19.12.tgz#0933eaab9af8b9b2c930236f62aae3fc593faf30" + integrity sha512-HKjJwRrW8uWtCQnQOz9qcU3mUZhTUQvi56Q8DPTLLB+DawoiQdjsYq+j+D3s9I8VFtDr+F9CjgXKKC4ss89IeA== + +"@esbuild/win32-arm64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/win32-arm64/-/win32-arm64-0.18.20.tgz#73bc7f5a9f8a77805f357fab97f290d0e4820ac9" + integrity sha512-ddYFR6ItYgoaq4v4JmQQaAI5s7npztfV4Ag6NrhiaW0RrnOXqBkgwZLofVTlq1daVTQNhtI5oieTvkRPfZrePg== + +"@esbuild/win32-arm64@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/win32-arm64/-/win32-arm64-0.19.12.tgz#773bdbaa1971b36db2f6560088639ccd1e6773ae" + integrity sha512-URgtR1dJnmGvX864pn1B2YUYNzjmXkuJOIqG2HdU62MVS4EHpU2946OZoTMnRUHklGtJdJZ33QfzdjGACXhn1A== + +"@esbuild/win32-ia32@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/win32-ia32/-/win32-ia32-0.18.20.tgz#ec93cbf0ef1085cc12e71e0d661d20569ff42102" + integrity sha512-Wv7QBi3ID/rROT08SABTS7eV4hX26sVduqDOTe1MvGMjNd3EjOz4b7zeexIR62GTIEKrfJXKL9LFxTYgkyeu7g== + +"@esbuild/win32-ia32@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/win32-ia32/-/win32-ia32-0.19.12.tgz#000516cad06354cc84a73f0943a4aa690ef6fd67" + integrity sha512-+ZOE6pUkMOJfmxmBZElNOx72NKpIa/HFOMGzu8fqzQJ5kgf6aTGrcJaFsNiVMH4JKpMipyK+7k0n2UXN7a8YKQ== + +"@esbuild/win32-x64@0.18.20": + version "0.18.20" + resolved "https://registry.yarnpkg.com/@esbuild/win32-x64/-/win32-x64-0.18.20.tgz#786c5f41f043b07afb1af37683d7c33668858f6d" + integrity sha512-kTdfRcSiDfQca/y9QIkng02avJ+NCaQvrMejlsB3RRv5sE9rRoeBPISaZpKxHELzRxZyLvNts1P27W3wV+8geQ== + +"@esbuild/win32-x64@0.19.12": + version "0.19.12" + resolved "https://registry.yarnpkg.com/@esbuild/win32-x64/-/win32-x64-0.19.12.tgz#c57c8afbb4054a3ab8317591a0b7320360b444ae" + integrity sha512-T1QyPSDCyMXaO3pzBkF96E8xMkiRYbUEZADd29SyPGabqxMViNoii+NcK7eWJAEoU6RZyEm5lVSIjTmcdoB9HA== + +"@google/generative-ai@^0.7.0": + version "0.7.1" + resolved "https://registry.yarnpkg.com/@google/generative-ai/-/generative-ai-0.7.1.tgz#eb187c75080c0706245699dbc06816c830d8c6a7" + integrity sha512-WTjMLLYL/xfA5BW6xAycRPiAX7FNHKAxrid/ayqC1QMam0KAK0NbMeS9Lubw80gVg5xFMLE+H7pw4wdNzTOlxw== + "@huggingface/jinja@^0.2.2": version "0.2.2" resolved "https://registry.yarnpkg.com/@huggingface/jinja/-/jinja-0.2.2.tgz#faeb205a9d6995089bef52655ddd8245d3190627" @@ -66,6 +326,34 @@ "@jridgewell/resolve-uri" "^3.0.3" "@jridgewell/sourcemap-codec" "^1.4.10" +"@langchain/anthropic@^0.2.3": + version "0.2.3" + resolved "https://registry.yarnpkg.com/@langchain/anthropic/-/anthropic-0.2.3.tgz#1505da939f47c90e53dfede0407c497b8177bdf0" + integrity sha512-f2fqzLGcvsXXUyZ1vl8cgwkKDGLshOGrPuR9hkhGuBG5m91eq755OqPBxWJuS1TFtNU813cXft3xh0MQbxavwg== + dependencies: + "@anthropic-ai/sdk" "^0.22.0" + "@langchain/core" ">=0.2.9 <0.3.0" + fast-xml-parser "^4.3.5" + zod "^3.22.4" + zod-to-json-schema "^3.22.4" + +"@langchain/community@^0.2.16": + version "0.2.16" + resolved "https://registry.yarnpkg.com/@langchain/community/-/community-0.2.16.tgz#5888baf7fc7ea272c5f91aaa0e71bc444167262d" + integrity sha512-dFDcMabKACvuRd0w6EIRLWf1ubPGZEeEwFt9v1jiEr4HCFxH0OF+iM1QUCcVRbB2fK5lqmKeTD1XAeZV8+AyXA== + dependencies: + "@langchain/core" "~0.2.11" + "@langchain/openai" "~0.1.0" + binary-extensions "^2.2.0" + expr-eval "^2.0.2" + flat "^5.0.2" + js-yaml "^4.1.0" + langchain "0.2.3" + langsmith "~0.1.30" + uuid "^9.0.0" + zod "^3.22.3" + zod-to-json-schema "^3.22.5" + "@langchain/community@~0.0.41": version "0.0.43" resolved "https://registry.yarnpkg.com/@langchain/community/-/community-0.0.43.tgz#017e2f9b3209b3999482f10df5aec2520731a63c" @@ -79,6 +367,59 @@ uuid "^9.0.0" zod "^3.22.3" +"@langchain/core@>0.1.56 <0.3.0", "@langchain/core@>0.2.0 <0.3.0", "@langchain/core@>=0.2.5 <0.3.0", "@langchain/core@~0.2.0", "@langchain/core@~0.2.11": + version "0.2.11" + resolved "https://registry.yarnpkg.com/@langchain/core/-/core-0.2.11.tgz#5f47467e20e56b250831baef20083657c6facb4c" + integrity sha512-d4SNL7WI0c3oHrV4WxCRH1/TNqdePXEzYjYwIb4aEH6lW1aM0utGhLbNthX+aYkOL4Ynx2FoG4h91ECIipiKWQ== + dependencies: + ansi-styles "^5.0.0" + camelcase "6" + decamelize "1.2.0" + js-tiktoken "^1.0.12" + langsmith "~0.1.30" + ml-distance "^4.0.0" + mustache "^4.2.0" + p-queue "^6.6.2" + p-retry "4" + uuid "^9.0.0" + zod "^3.22.4" + zod-to-json-schema "^3.22.3" + +"@langchain/core@>=0.2.16 <0.3.0": + version "0.2.36" + resolved "https://registry.yarnpkg.com/@langchain/core/-/core-0.2.36.tgz#75754c33aa5b9310dcf117047374a1ae011005a4" + integrity sha512-qHLvScqERDeH7y2cLuJaSAlMwg3f/3Oc9nayRSXRU2UuaK/SOhI42cxiPLj1FnuHJSmN0rBQFkrLx02gI4mcVg== + dependencies: + ansi-styles "^5.0.0" + camelcase "6" + decamelize "1.2.0" + js-tiktoken "^1.0.12" + langsmith "^0.1.56-rc.1" + mustache "^4.2.0" + p-queue "^6.6.2" + p-retry "4" + uuid "^10.0.0" + zod "^3.22.4" + zod-to-json-schema "^3.22.3" + +"@langchain/core@>=0.2.9 <0.3.0": + version "0.2.15" + resolved "https://registry.yarnpkg.com/@langchain/core/-/core-0.2.15.tgz#1bb99ac4fffe935c7ba37edcaa91abfba3c82219" + integrity sha512-L096itIBQ5XNsy5BCCPqIQEk/x4rzI+U4BhYT+fDBYtljESshIi/WzXdmiGfY/6MpVjB76jNuaRgMDmo1m9NeQ== + dependencies: + ansi-styles "^5.0.0" + camelcase "6" + decamelize "1.2.0" + js-tiktoken "^1.0.12" + langsmith "~0.1.30" + ml-distance "^4.0.0" + mustache "^4.2.0" + p-queue "^6.6.2" + p-retry "4" + uuid "^10.0.0" + zod "^3.22.4" + zod-to-json-schema "^3.22.3" + "@langchain/core@~0.1.44", "@langchain/core@~0.1.45": version "0.1.52" resolved "https://registry.yarnpkg.com/@langchain/core/-/core-0.1.52.tgz#7619310b83ffa841628efe2e1eda873ca714d068" @@ -96,6 +437,15 @@ zod "^3.22.4" zod-to-json-schema "^3.22.3" +"@langchain/google-genai@^0.0.23": + version "0.0.23" + resolved "https://registry.yarnpkg.com/@langchain/google-genai/-/google-genai-0.0.23.tgz#e73af501bc1df4c7642b531759b82dc3eb7ae459" + integrity sha512-MTSCJEoKsfU1inz0PWvAjITdNFM4s41uvBCwLpcgx3jWJIEisczFD82x86ahYqJlb2fD6tohYSaCH/4tKAdkXA== + dependencies: + "@google/generative-ai" "^0.7.0" + "@langchain/core" ">=0.2.16 <0.3.0" + zod-to-json-schema "^3.22.4" + "@langchain/openai@^0.0.25", "@langchain/openai@~0.0.19": version "0.0.25" resolved "https://registry.yarnpkg.com/@langchain/openai/-/openai-0.0.25.tgz#8332abea1e3acb9b1169f90636e518c0ee90622e" @@ -107,6 +457,36 @@ zod "^3.22.4" zod-to-json-schema "^3.22.3" +"@langchain/openai@~0.0.28": + version "0.0.34" + resolved "https://registry.yarnpkg.com/@langchain/openai/-/openai-0.0.34.tgz#36c9bca0721ab9f7e5d40927e7c0429cacbd5b56" + integrity sha512-M+CW4oXle5fdoz2T2SwdOef8pl3/1XmUx1vjn2mXUVM/128aO0l23FMF0SNBsAbRV6P+p/TuzjodchJbi0Ht/A== + dependencies: + "@langchain/core" ">0.1.56 <0.3.0" + js-tiktoken "^1.0.12" + openai "^4.41.1" + zod "^3.22.4" + zod-to-json-schema "^3.22.3" + +"@langchain/openai@~0.1.0": + version "0.1.3" + resolved "https://registry.yarnpkg.com/@langchain/openai/-/openai-0.1.3.tgz#6eb0994e970d85ffa9aaeafb94449024ccf6ca63" + integrity sha512-riv/JC9x2A8b7GcHu8sx+mlZJ8KAwSSi231IPTlcciYnKozmrQ5H0vrtiD31fxiDbaRsk7tyCpkSBIOQEo7CyQ== + dependencies: + "@langchain/core" ">=0.2.5 <0.3.0" + js-tiktoken "^1.0.12" + openai "^4.49.1" + zod "^3.22.4" + zod-to-json-schema "^3.22.3" + +"@langchain/textsplitters@~0.0.0": + version "0.0.3" + resolved "https://registry.yarnpkg.com/@langchain/textsplitters/-/textsplitters-0.0.3.tgz#1a3cc93dd2ab330edb225400ded190a22fea14e3" + integrity sha512-cXWgKE3sdWLSqAa8ykbCcUsUF1Kyr5J3HOWYGuobhPEycXW4WI++d5DhzdpL238mzoEXTi90VqfSCra37l5YqA== + dependencies: + "@langchain/core" ">0.2.0 <0.3.0" + js-tiktoken "^1.0.12" + "@protobufjs/aspromise@^1.1.1", "@protobufjs/aspromise@^1.1.2": version "1.1.2" resolved "https://registry.yarnpkg.com/@protobufjs/aspromise/-/aspromise-1.1.2.tgz#9b8b0cc663d669a7d8f6f5d0893a14d348f30fbf" @@ -160,6 +540,14 @@ resolved "https://registry.yarnpkg.com/@protobufjs/utf8/-/utf8-1.1.0.tgz#a777360b5b39a1a2e5106f8e858f2fd2d060c570" integrity sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw== +"@selderee/plugin-htmlparser2@^0.11.0": + version "0.11.0" + resolved "https://registry.yarnpkg.com/@selderee/plugin-htmlparser2/-/plugin-htmlparser2-0.11.0.tgz#d5b5e29a7ba6d3958a1972c7be16f4b2c188c517" + integrity sha512-P33hHGdldxGabLFjPPpaTxVolMrzrcegejx+0GxjrIb9Zv48D8yAIA/QTDR2dFl7Uz7urX8aX6+5bCZslr+gWQ== + dependencies: + domhandler "^5.0.3" + selderee "^0.11.0" + "@tsconfig/node10@^1.0.7": version "1.0.11" resolved "https://registry.yarnpkg.com/@tsconfig/node10/-/node10-1.0.11.tgz#6ee46400685f130e278128c7b38b7e031ff5b2f2" @@ -180,6 +568,13 @@ resolved "https://registry.yarnpkg.com/@tsconfig/node16/-/node16-1.0.4.tgz#0b92dcc0cc1c81f6f306a381f28e31b1a56536e9" integrity sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA== +"@types/better-sqlite3@^7.6.10": + version "7.6.10" + resolved "https://registry.yarnpkg.com/@types/better-sqlite3/-/better-sqlite3-7.6.10.tgz#1818e56490953404acfd44cdde0464f201be6105" + integrity sha512-TZBjD+yOsyrUJGmcUj6OS3JADk3+UZcNv3NOBqGkM09bZdi28fNZw8ODqbMOLfKCu7RYCO62/ldq1iHbzxqoPw== + dependencies: + "@types/node" "*" + "@types/body-parser@*": version "1.19.5" resolved "https://registry.yarnpkg.com/@types/body-parser/-/body-parser-1.19.5.tgz#04ce9a3b677dc8bd681a17da1ab9835dc9d3ede4" @@ -212,6 +607,26 @@ "@types/range-parser" "*" "@types/send" "*" +"@types/express-serve-static-core@^5.0.0": + version "5.0.1" + resolved "https://registry.yarnpkg.com/@types/express-serve-static-core/-/express-serve-static-core-5.0.1.tgz#3c9997ae9d00bc236e45c6374e84f2596458d9db" + integrity sha512-CRICJIl0N5cXDONAdlTv5ShATZ4HEwk6kDDIW2/w9qOWKg+NU/5F8wYRWCrONad0/UKkloNSmmyN/wX4rtpbVA== + dependencies: + "@types/node" "*" + "@types/qs" "*" + "@types/range-parser" "*" + "@types/send" "*" + +"@types/express@*": + version "5.0.0" + resolved "https://registry.yarnpkg.com/@types/express/-/express-5.0.0.tgz#13a7d1f75295e90d19ed6e74cab3678488eaa96c" + integrity sha512-DvZriSMehGHL1ZNLzi6MidnsDhUZM/x2pRdDIKdwbUNqqwHxMlRdkxtn6/EPKyqKpHqTl/4nRZsRNLpZxZRpPQ== + dependencies: + "@types/body-parser" "*" + "@types/express-serve-static-core" "^5.0.0" + "@types/qs" "*" + "@types/serve-static" "*" + "@types/express@^4.17.21": version "4.17.21" resolved "https://registry.yarnpkg.com/@types/express/-/express-4.17.21.tgz#c26d4a151e60efe0084b23dc3369ebc631ed192d" @@ -222,6 +637,11 @@ "@types/qs" "*" "@types/serve-static" "*" +"@types/html-to-text@^9.0.4": + version "9.0.4" + resolved "https://registry.yarnpkg.com/@types/html-to-text/-/html-to-text-9.0.4.tgz#4a83dd8ae8bfa91457d0b1ffc26f4d0537eff58c" + integrity sha512-pUY3cKH/Nm2yYrEmDlPR1mR7yszjGx4DrwPjQ702C4/D5CwHuZTgZdIdwPkRbcuhs7BAh2L5rg3CL5cbRiGTCQ== + "@types/http-errors@*": version "2.0.4" resolved "https://registry.yarnpkg.com/@types/http-errors/-/http-errors-2.0.4.tgz#7eb47726c391b7345a6ec35ad7f4de469cf5ba4f" @@ -237,6 +657,13 @@ resolved "https://registry.yarnpkg.com/@types/mime/-/mime-1.3.5.tgz#1ef302e01cf7d2b5a0fa526790c9123bf1d06690" integrity sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w== +"@types/multer@^1.4.12": + version "1.4.12" + resolved "https://registry.yarnpkg.com/@types/multer/-/multer-1.4.12.tgz#da67bd0c809f3a63fe097c458c0d4af1fea50ab7" + integrity sha512-pQ2hoqvXiJt2FP9WQVLPRO+AmiIm/ZYkavPlIQnx282u4ZrVdztx0pkh3jjpQt0Kz+YI0YhSG264y08UJKoUQg== + dependencies: + "@types/express" "*" + "@types/node-fetch@^2.6.4": version "2.6.11" resolved "https://registry.yarnpkg.com/@types/node-fetch/-/node-fetch-2.6.11.tgz#9b39b78665dae0e82a08f02f4967d62c66f95d24" @@ -266,6 +693,11 @@ dependencies: undici-types "~5.26.4" +"@types/pdf-parse@^1.1.4": + version "1.1.4" + resolved "https://registry.yarnpkg.com/@types/pdf-parse/-/pdf-parse-1.1.4.tgz#21a539efd2f16009d08aeed3350133948b5d7ed1" + integrity sha512-+gbBHbNCVGGYw1S9lAIIvrHW47UYOhMIFUsJcMkMrzy1Jf0vulBN3XQIjPgnoOXveMuHnF3b57fXROnY/Or7eg== + "@types/qs@*": version "6.9.14" resolved "https://registry.yarnpkg.com/@types/qs/-/qs-6.9.14.tgz#169e142bfe493895287bee382af6039795e9b75b" @@ -311,11 +743,23 @@ resolved "https://registry.yarnpkg.com/@types/triple-beam/-/triple-beam-1.3.5.tgz#74fef9ffbaa198eb8b588be029f38b00299caa2c" integrity sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw== +"@types/uuid@^10.0.0": + version "10.0.0" + resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-10.0.0.tgz#e9c07fe50da0f53dc24970cca94d619ff03f6f6d" + integrity sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ== + "@types/uuid@^9.0.1": version "9.0.8" resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-9.0.8.tgz#7545ba4fc3c003d6c756f651f3bf163d8f0f29ba" 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": version "2.17.1" resolved "https://registry.yarnpkg.com/@xenova/transformers/-/transformers-2.17.1.tgz#712f7a72c76c8aa2075749382f83dc7dd4e5a9a5" @@ -327,6 +771,11 @@ optionalDependencies: onnxruntime-node "1.14.0" +"@xmldom/xmldom@^0.8.6": + version "0.8.10" + resolved "https://registry.yarnpkg.com/@xmldom/xmldom/-/xmldom-0.8.10.tgz#a1337ca426aa61cef9fe15b5b28e340a72f6fa99" + integrity sha512-2WALfTl4xo2SkGCYRt6rDTFfk9R1czmBvUQy12gK2KuRKIpWEhcbbzy8EZXtz/jkRqHX8bFEc6FC1HjX4TUWYw== + abbrev@1: version "1.1.1" resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8" @@ -377,6 +826,11 @@ anymatch@~3.1.2: normalize-path "^3.0.0" picomatch "^2.0.4" +append-field@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/append-field/-/append-field-1.0.0.tgz#1e3440e915f0b1203d23748e78edd7b9b5b43e56" + integrity sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw== + arg@^4.1.0: version "4.1.3" resolved "https://registry.yarnpkg.com/arg/-/arg-4.1.3.tgz#269fc7ad5b8e42cb63c896d5666017261c144089" @@ -387,6 +841,13 @@ argparse@^2.0.1: resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38" integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q== +argparse@~1.0.3: + version "1.0.10" + resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911" + integrity sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg== + dependencies: + sprintf-js "~1.0.2" + array-flatten@1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/array-flatten/-/array-flatten-1.1.1.tgz#9a5f699051b1e7073328f2a008968b64ea2955d2" @@ -464,6 +925,14 @@ base64-js@^1.3.1, base64-js@^1.5.1: resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.5.1.tgz#1b1b440160a5bf7ad40b650f095963481903930a" integrity sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA== +better-sqlite3@^11.0.0: + version "11.0.0" + resolved "https://registry.yarnpkg.com/better-sqlite3/-/better-sqlite3-11.0.0.tgz#12083acfe0ded6abdba908ed73520f2003e3ea0e" + integrity sha512-1NnNhmT3EZTsKtofJlMox1jkMxdedILury74PwUbQBjWgo4tL4kf7uTAjU55mgQwjdzqakSTjkf+E1imrFwjnA== + dependencies: + bindings "^1.5.0" + prebuild-install "^7.1.1" + binary-extensions@^2.0.0, binary-extensions@^2.2.0: version "2.3.0" resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-2.3.0.tgz#f6e14a97858d327252200242d4ccfe522c445522" @@ -474,6 +943,13 @@ binary-search@^1.3.5: resolved "https://registry.yarnpkg.com/binary-search/-/binary-search-1.3.6.tgz#e32426016a0c5092f0f3598836a1c7da3560565c" integrity sha512-nbE1WxOTTrUWIfsfZ4aHGYu5DOuNkbxGokjV6Z2kxfJK3uaAb8zNK1muzOeipoLHZjInT4Br88BHpzevc681xA== +bindings@^1.5.0: + version "1.5.0" + resolved "https://registry.yarnpkg.com/bindings/-/bindings-1.5.0.tgz#10353c9e945334bc0511a6d90b38fbc7c9c504df" + integrity sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ== + dependencies: + file-uri-to-path "1.0.0" + bl@^4.0.3: version "4.1.0" resolved "https://registry.yarnpkg.com/bl/-/bl-4.1.0.tgz#451535264182bec2fbbc83a62ab98cf11d9f7b3a" @@ -483,6 +959,11 @@ bl@^4.0.3: inherits "^2.0.4" readable-stream "^3.4.0" +bluebird@~3.4.0: + version "3.4.7" + resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-3.4.7.tgz#f72d760be09b7f76d08ed8fae98b289a8d05fab3" + integrity sha512-iD3898SR7sWVRHbiQv+sHUtHnMvC1o3nW5rAcqnq3uOn07DSAppZYUkIGslDz6gXC7HfunPe7YVBgoEJASPcHA== + body-parser@1.20.2: version "1.20.2" resolved "https://registry.yarnpkg.com/body-parser/-/body-parser-1.20.2.tgz#6feb0e21c4724d06de7ff38da36dad4f57a747fd" @@ -516,6 +997,11 @@ braces@~3.0.2: dependencies: fill-range "^7.0.1" +buffer-from@^1.0.0: + version "1.1.2" + resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.2.tgz#2b146a6fd72e80b4f55d255f35ed59a3a9a41bd5" + integrity sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ== + buffer@^5.5.0: version "5.7.1" resolved "https://registry.yarnpkg.com/buffer/-/buffer-5.7.1.tgz#ba62e7c13133053582197160851a8f648e99eed0" @@ -524,6 +1010,13 @@ buffer@^5.5.0: base64-js "^1.3.1" ieee754 "^1.1.13" +busboy@^1.0.0: + version "1.6.0" + resolved "https://registry.yarnpkg.com/busboy/-/busboy-1.6.0.tgz#966ea36a9502e43cdb9146962523b92f531f6893" + integrity sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA== + dependencies: + streamsearch "^1.1.0" + bytes@3.1.2: version "3.1.2" resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.1.2.tgz#8b0beeb98605adf1b128fa4386403c009e0221a5" @@ -669,6 +1162,16 @@ concat-map@0.0.1: resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" integrity sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg== +concat-stream@^1.5.2: + version "1.6.2" + resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-1.6.2.tgz#904bdf194cd3122fc675c77fc4ac3d4ff0fd1a34" + integrity sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw== + dependencies: + buffer-from "^1.0.0" + inherits "^2.0.3" + readable-stream "^2.2.2" + typedarray "^0.0.6" + content-disposition@0.5.4: version "0.5.4" resolved "https://registry.yarnpkg.com/content-disposition/-/content-disposition-0.5.4.tgz#8b82b4efac82512a02bb0b1dcec9d2c5e8eb5bfe" @@ -691,6 +1194,11 @@ cookie@0.6.0: resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.6.0.tgz#2798b04b071b0ecbff0dbb62a505a8efa4e19051" integrity sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw== +core-util-is@~1.0.0: + version "1.0.3" + resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.3.tgz#a6042d3634c2b27e9328f837b965fac83808db85" + integrity sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ== + cors@^2.8.5: version "2.8.5" resolved "https://registry.yarnpkg.com/cors/-/cors-2.8.5.tgz#eac11da51592dd86b9f06f6e7ac293b3df875d29" @@ -716,6 +1224,13 @@ debug@2.6.9: dependencies: ms "2.0.0" +debug@^3.1.0: + version "3.2.7" + resolved "https://registry.yarnpkg.com/debug/-/debug-3.2.7.tgz#72580b7e9145fb39b6676f9c5e5fb100b934179a" + integrity sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ== + dependencies: + ms "^2.1.1" + debug@^4: version "4.3.4" resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.4.tgz#1319f6579357f2338d3337d2cdd4914bb5dcc865" @@ -723,6 +1238,13 @@ debug@^4: dependencies: ms "2.1.2" +debug@^4.3.4: + version "4.3.5" + resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.5.tgz#e83444eceb9fedd4a1da56d671ae2446a01a6e1e" + integrity sha512-pt0bNEmneDIvdL1Xsd9oDQ/wrQRkXDT4AUWlNZNPKvW5x/jyO9VFXkJUP07vQ2upmw5PlaITaPKc31jK13V+jg== + dependencies: + ms "2.1.2" + decamelize@1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290" @@ -740,6 +1262,11 @@ deep-extend@^0.6.0: resolved "https://registry.yarnpkg.com/deep-extend/-/deep-extend-0.6.0.tgz#c4fa7c95404a17a9c3e8ca7e1537312b736330ac" integrity sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA== +deepmerge@^4.3.1: + version "4.3.1" + resolved "https://registry.yarnpkg.com/deepmerge/-/deepmerge-4.3.1.tgz#44b5f2147cd3b00d4b56137685966f26fd25dd4a" + integrity sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A== + define-data-property@^1.1.4: version "1.1.4" resolved "https://registry.yarnpkg.com/define-data-property/-/define-data-property-1.1.4.tgz#894dc141bb7d3060ae4366f6a0107e68fbe48c5e" @@ -782,11 +1309,67 @@ digest-fetch@^1.3.0: base-64 "^0.1.0" md5 "^2.3.0" +dingbat-to-unicode@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/dingbat-to-unicode/-/dingbat-to-unicode-1.0.1.tgz#5091dd673241453e6b5865e26e5a4452cdef5c83" + integrity sha512-98l0sW87ZT58pU4i61wa2OHwxbiYSbuxsCBozaVnYX2iCnr3bLM3fIes1/ej7h1YdOKuKt/MLs706TVnALA65w== + +dom-serializer@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/dom-serializer/-/dom-serializer-2.0.0.tgz#e41b802e1eedf9f6cae183ce5e622d789d7d8e53" + integrity sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg== + dependencies: + domelementtype "^2.3.0" + domhandler "^5.0.2" + entities "^4.2.0" + +domelementtype@^2.3.0: + version "2.3.0" + resolved "https://registry.yarnpkg.com/domelementtype/-/domelementtype-2.3.0.tgz#5c45e8e869952626331d7aab326d01daf65d589d" + integrity sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw== + +domhandler@^5.0.2, domhandler@^5.0.3: + version "5.0.3" + resolved "https://registry.yarnpkg.com/domhandler/-/domhandler-5.0.3.tgz#cc385f7f751f1d1fc650c21374804254538c7d31" + integrity sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w== + dependencies: + domelementtype "^2.3.0" + +domutils@^3.0.1: + version "3.1.0" + resolved "https://registry.yarnpkg.com/domutils/-/domutils-3.1.0.tgz#c47f551278d3dc4b0b1ab8cbb42d751a6f0d824e" + integrity sha512-H78uMmQtI2AhgDJjWeQmHwJJ2bLPD3GMmO7Zja/ZZh84wkm+4ut+IUnUdRa8uCGX88DiVx1j6FRe1XfxEgjEZA== + dependencies: + dom-serializer "^2.0.0" + domelementtype "^2.3.0" + domhandler "^5.0.3" + dotenv@^16.4.5: version "16.4.5" resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-16.4.5.tgz#cdd3b3b604cb327e286b4762e13502f717cb099f" integrity sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg== +drizzle-kit@^0.22.7: + version "0.22.7" + resolved "https://registry.yarnpkg.com/drizzle-kit/-/drizzle-kit-0.22.7.tgz#4339c3e24c6555ea8cbad605f005b3db3e604a9c" + integrity sha512-9THPCb2l1GPt7wxhws9LvTR0YG565ZlVgTuqGMwjs590Kch1pXu4GyjEArVijSF5m0OBj3qgdeKmuJXhKXgWFw== + dependencies: + "@esbuild-kit/esm-loader" "^2.5.5" + esbuild "^0.19.7" + esbuild-register "^3.5.0" + +drizzle-orm@^0.31.2: + version "0.31.2" + resolved "https://registry.yarnpkg.com/drizzle-orm/-/drizzle-orm-0.31.2.tgz#221a257dd487bab49ddb88a17bd82388600cf655" + integrity sha512-QnenevbnnAzmbNzQwbhklvIYrDE8YER8K7kSrAWQSV1YvFCdSQPzj+jzqRdTSsV2cDqSpQ0NXGyL1G9I43LDLg== + +duck@^0.1.12: + version "0.1.12" + resolved "https://registry.yarnpkg.com/duck/-/duck-0.1.12.tgz#de7adf758421230b6d7aee799ce42670586b9efa" + integrity sha512-wkctla1O6VfP89gQ+J/yDesM0S7B7XLXjKGzXxMDVFg7uEn706niAtyYovKbyq1oT9YwDcly721/iUWoc8MVRg== + dependencies: + underscore "^1.13.1" + ee-first@1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/ee-first/-/ee-first-1.1.1.tgz#590c61156b0ae2f4f0255732a158b266bc56b21d" @@ -809,6 +1392,11 @@ end-of-stream@^1.1.0, end-of-stream@^1.4.1: dependencies: once "^1.4.0" +entities@^4.2.0, entities@^4.4.0: + version "4.5.0" + resolved "https://registry.yarnpkg.com/entities/-/entities-4.5.0.tgz#5d268ea5e7113ec74c4d033b79ea5a35a488fb48" + integrity sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw== + es-define-property@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/es-define-property/-/es-define-property-1.0.0.tgz#c7faefbdff8b2696cf5f46921edfb77cc4ba3845" @@ -821,6 +1409,70 @@ es-errors@^1.3.0: resolved "https://registry.yarnpkg.com/es-errors/-/es-errors-1.3.0.tgz#05f75a25dab98e4fb1dcd5e1472c0546d5057c8f" integrity sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw== +esbuild-register@^3.5.0: + version "3.5.0" + resolved "https://registry.yarnpkg.com/esbuild-register/-/esbuild-register-3.5.0.tgz#449613fb29ab94325c722f560f800dd946dc8ea8" + integrity sha512-+4G/XmakeBAsvJuDugJvtyF1x+XJT4FMocynNpxrvEBViirpfUn2PgNpCHedfWhF4WokNsO/OvMKrmJOIJsI5A== + dependencies: + debug "^4.3.4" + +esbuild@^0.19.7: + version "0.19.12" + resolved "https://registry.yarnpkg.com/esbuild/-/esbuild-0.19.12.tgz#dc82ee5dc79e82f5a5c3b4323a2a641827db3e04" + integrity sha512-aARqgq8roFBj054KvQr5f1sFu0D65G+miZRCuJyJ0G13Zwx7vRar5Zhn2tkQNzIXcBrNVsv/8stehpj+GAjgbg== + optionalDependencies: + "@esbuild/aix-ppc64" "0.19.12" + "@esbuild/android-arm" "0.19.12" + "@esbuild/android-arm64" "0.19.12" + "@esbuild/android-x64" "0.19.12" + "@esbuild/darwin-arm64" "0.19.12" + "@esbuild/darwin-x64" "0.19.12" + "@esbuild/freebsd-arm64" "0.19.12" + "@esbuild/freebsd-x64" "0.19.12" + "@esbuild/linux-arm" "0.19.12" + "@esbuild/linux-arm64" "0.19.12" + "@esbuild/linux-ia32" "0.19.12" + "@esbuild/linux-loong64" "0.19.12" + "@esbuild/linux-mips64el" "0.19.12" + "@esbuild/linux-ppc64" "0.19.12" + "@esbuild/linux-riscv64" "0.19.12" + "@esbuild/linux-s390x" "0.19.12" + "@esbuild/linux-x64" "0.19.12" + "@esbuild/netbsd-x64" "0.19.12" + "@esbuild/openbsd-x64" "0.19.12" + "@esbuild/sunos-x64" "0.19.12" + "@esbuild/win32-arm64" "0.19.12" + "@esbuild/win32-ia32" "0.19.12" + "@esbuild/win32-x64" "0.19.12" + +esbuild@~0.18.20: + version "0.18.20" + resolved "https://registry.yarnpkg.com/esbuild/-/esbuild-0.18.20.tgz#4709f5a34801b43b799ab7d6d82f7284a9b7a7a6" + integrity sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA== + optionalDependencies: + "@esbuild/android-arm" "0.18.20" + "@esbuild/android-arm64" "0.18.20" + "@esbuild/android-x64" "0.18.20" + "@esbuild/darwin-arm64" "0.18.20" + "@esbuild/darwin-x64" "0.18.20" + "@esbuild/freebsd-arm64" "0.18.20" + "@esbuild/freebsd-x64" "0.18.20" + "@esbuild/linux-arm" "0.18.20" + "@esbuild/linux-arm64" "0.18.20" + "@esbuild/linux-ia32" "0.18.20" + "@esbuild/linux-loong64" "0.18.20" + "@esbuild/linux-mips64el" "0.18.20" + "@esbuild/linux-ppc64" "0.18.20" + "@esbuild/linux-riscv64" "0.18.20" + "@esbuild/linux-s390x" "0.18.20" + "@esbuild/linux-x64" "0.18.20" + "@esbuild/netbsd-x64" "0.18.20" + "@esbuild/openbsd-x64" "0.18.20" + "@esbuild/sunos-x64" "0.18.20" + "@esbuild/win32-arm64" "0.18.20" + "@esbuild/win32-ia32" "0.18.20" + "@esbuild/win32-x64" "0.18.20" + escape-html@~1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/escape-html/-/escape-html-1.0.3.tgz#0258eae4d3d0c0974de1c169188ef0051d1d1988" @@ -893,11 +1545,23 @@ fast-fifo@^1.1.0, fast-fifo@^1.2.0: resolved "https://registry.yarnpkg.com/fast-fifo/-/fast-fifo-1.3.2.tgz#286e31de96eb96d38a97899815740ba2a4f3640c" integrity sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ== +fast-xml-parser@^4.3.5: + version "4.4.0" + resolved "https://registry.yarnpkg.com/fast-xml-parser/-/fast-xml-parser-4.4.0.tgz#341cc98de71e9ba9e651a67f41f1752d1441a501" + integrity sha512-kLY3jFlwIYwBNDojclKsNAC12sfD6NwW74QB2CoNGPvtVxjliYehVunB3HYyNi+n4Tt1dAcgwYvmKF/Z18flqg== + dependencies: + strnum "^1.0.5" + fecha@^4.2.0: version "4.2.3" resolved "https://registry.yarnpkg.com/fecha/-/fecha-4.2.3.tgz#4d9ccdbc61e8629b259fdca67e65891448d569fd" integrity sha512-OP2IUU6HeYKJi3i0z4A19kHMQoLVs4Hc+DPqqxI2h/DPZHTm/vjsfC6P0b4jCMy14XizLBqvndQ+UilD7707Jw== +file-uri-to-path@1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz#553a7b8446ff6f684359c445f1e37a05dacc33dd" + integrity sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw== + fill-range@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.0.1.tgz#1919a6a7c75fe38b2c7c77e5198535da9acdda40" @@ -996,6 +1660,13 @@ get-intrinsic@^1.1.3, get-intrinsic@^1.2.4: has-symbols "^1.0.3" hasown "^2.0.0" +get-tsconfig@^4.7.0: + version "4.7.5" + resolved "https://registry.yarnpkg.com/get-tsconfig/-/get-tsconfig-4.7.5.tgz#5e012498579e9a6947511ed0cd403272c7acbbaf" + integrity sha512-ZCuZCnlqNzjb4QprAzXKdpp/gh6KTxSJuw3IBsPnV/7fV4NxC9ckB+vPTt8w7fJA0TaSD7c55BR47JD6MEDyDw== + dependencies: + resolve-pkg-maps "^1.0.0" + github-from-package@0.0.0: version "0.0.0" resolved "https://registry.yarnpkg.com/github-from-package/-/github-from-package-0.0.0.tgz#97fb5d96bfde8973313f20e8288ef9a167fa64ce" @@ -1049,6 +1720,27 @@ hasown@^2.0.0: dependencies: function-bind "^1.1.2" +html-to-text@^9.0.5: + version "9.0.5" + resolved "https://registry.yarnpkg.com/html-to-text/-/html-to-text-9.0.5.tgz#6149a0f618ae7a0db8085dca9bbf96d32bb8368d" + integrity sha512-qY60FjREgVZL03vJU6IfMV4GDjGBIoOyvuFdpBDIX9yTlDw0TjxVBQp+P8NvpdIXNJvfWBTNul7fsAQJq2FNpg== + dependencies: + "@selderee/plugin-htmlparser2" "^0.11.0" + deepmerge "^4.3.1" + dom-serializer "^2.0.0" + htmlparser2 "^8.0.2" + selderee "^0.11.0" + +htmlparser2@^8.0.2: + version "8.0.2" + resolved "https://registry.yarnpkg.com/htmlparser2/-/htmlparser2-8.0.2.tgz#f002151705b383e62433b5cf466f5b716edaec21" + integrity sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA== + dependencies: + domelementtype "^2.3.0" + domhandler "^5.0.3" + domutils "^3.0.1" + entities "^4.4.0" + http-errors@2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-2.0.0.tgz#b7774a1486ef73cf7667ac9ae0858c012c57b9d3" @@ -1084,7 +1776,12 @@ ignore-by-default@^1.0.1: resolved "https://registry.yarnpkg.com/ignore-by-default/-/ignore-by-default-1.0.1.tgz#48ca6d72f6c6a3af00a9ad4ae6876be3889e2b09" integrity sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA== -inherits@2.0.4, inherits@^2.0.3, inherits@^2.0.4: +immediate@~3.0.5: + version "3.0.6" + resolved "https://registry.yarnpkg.com/immediate/-/immediate-3.0.6.tgz#9db1dbd0faf8de6fbe0f5dd5e56bb606280de69b" + integrity sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ== + +inherits@2.0.4, inherits@^2.0.3, inherits@^2.0.4, inherits@~2.0.3: version "2.0.4" resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== @@ -1143,6 +1840,18 @@ is-stream@^2.0.0: resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-2.0.1.tgz#fac1e3d53b97ad5a9d0ae9cef2389f5810a5c077" integrity sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg== +isarray@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" + integrity sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ== + +js-tiktoken@^1.0.12: + version "1.0.12" + resolved "https://registry.yarnpkg.com/js-tiktoken/-/js-tiktoken-1.0.12.tgz#af0f5cf58e5e7318240d050c8413234019424211" + integrity sha512-L7wURW1fH9Qaext0VzaUDpFGVQgjkdE3Dgsy9/+yXyGEpBKnylTd0mU0bfbNkKDlXRb6TEsZkwuflu1B8uQbJQ== + dependencies: + base64-js "^1.5.1" + js-tiktoken@^1.0.7, js-tiktoken@^1.0.8: version "1.0.10" resolved "https://registry.yarnpkg.com/js-tiktoken/-/js-tiktoken-1.0.10.tgz#2b343ec169399dcee8f9ef9807dbd4fafd3b30dc" @@ -1162,11 +1871,43 @@ jsonpointer@^5.0.1: resolved "https://registry.yarnpkg.com/jsonpointer/-/jsonpointer-5.0.1.tgz#2110e0af0900fd37467b5907ecd13a7884a1b559" integrity sha512-p/nXbhSEcu3pZRdkW1OfJhpsVtW1gd4Wa1fnQc9YLiTfAjn0312eMKimbdIQzuZl9aa9xUGaRlP9T/CJE/ditQ== +jszip@^3.7.1: + version "3.10.1" + resolved "https://registry.yarnpkg.com/jszip/-/jszip-3.10.1.tgz#34aee70eb18ea1faec2f589208a157d1feb091c2" + integrity sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g== + dependencies: + lie "~3.3.0" + pako "~1.0.2" + readable-stream "~2.3.6" + setimmediate "^1.0.5" + kuler@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/kuler/-/kuler-2.0.0.tgz#e2c570a3800388fb44407e851531c1d670b061b3" integrity sha512-Xq9nH7KlWZmXAtodXDDRE7vs6DU1gTU8zYDHDiWLSip45Egwq3plLHzPn27NgvzL2r1LMPC1vdqh98sQxtqj4A== +langchain@0.2.3: + version "0.2.3" + resolved "https://registry.yarnpkg.com/langchain/-/langchain-0.2.3.tgz#c14bb05cf871b21bd63b84b3ab89580b1d62539f" + integrity sha512-T9xR7zd+Nj0oXy6WoYKmZLy0DlQiDLFPGYWdOXDxy+AvqlujoPdVQgDSpdqiOHvAjezrByAoKxoHCz5XMwTP/Q== + dependencies: + "@langchain/core" "~0.2.0" + "@langchain/openai" "~0.0.28" + "@langchain/textsplitters" "~0.0.0" + binary-extensions "^2.2.0" + js-tiktoken "^1.0.12" + js-yaml "^4.1.0" + jsonpointer "^5.0.1" + langchainhub "~0.0.8" + langsmith "~0.1.7" + ml-distance "^4.0.0" + openapi-types "^12.1.3" + p-retry "4" + uuid "^9.0.0" + yaml "^2.2.1" + zod "^3.22.4" + zod-to-json-schema "^3.22.3" + langchain@^0.1.30: version "0.1.30" resolved "https://registry.yarnpkg.com/langchain/-/langchain-0.1.30.tgz#e1adb3f1849fcd5c596c668300afd5dc8cb37a97" @@ -1195,6 +1936,18 @@ langchainhub@~0.0.8: resolved "https://registry.yarnpkg.com/langchainhub/-/langchainhub-0.0.8.tgz#fd4b96dc795e22e36c1a20bad31b61b0c33d3110" integrity sha512-Woyb8YDHgqqTOZvWIbm2CaFDGfZ4NTSyXV687AG4vXEfoNo7cGQp7nhl7wL3ehenKWmNEmcxCLgOZzW8jE6lOQ== +langsmith@^0.1.56-rc.1: + version "0.1.68" + resolved "https://registry.yarnpkg.com/langsmith/-/langsmith-0.1.68.tgz#848332e822fe5e6734a07f1c36b6530cc1798afb" + integrity sha512-otmiysWtVAqzMx3CJ4PrtUBhWRG5Co8Z4o7hSZENPjlit9/j3/vm3TSvbaxpDYakZxtMjhkcJTqrdYFipISEiQ== + dependencies: + "@types/uuid" "^10.0.0" + commander "^10.0.1" + p-queue "^6.6.2" + p-retry "4" + semver "^7.6.3" + uuid "^10.0.0" + langsmith@~0.1.1, langsmith@~0.1.7: version "0.1.14" resolved "https://registry.yarnpkg.com/langsmith/-/langsmith-0.1.14.tgz#2b889dbcfb49547614df276a4a5a063092a1585d" @@ -1206,6 +1959,35 @@ langsmith@~0.1.1, langsmith@~0.1.7: p-retry "4" uuid "^9.0.0" +langsmith@~0.1.30: + version "0.1.34" + resolved "https://registry.yarnpkg.com/langsmith/-/langsmith-0.1.34.tgz#801310495fef258ed9c22bb5575120e2c06d51cf" + integrity sha512-aMv2k8kEaovhTuZnK6/6DMCoM7Jurvm1AzdESn+yN+HramRxp3sK32jFRz3ogkXP6GjAjOIofcnNkzhHXSUXGA== + dependencies: + "@types/uuid" "^9.0.1" + commander "^10.0.1" + lodash.set "^4.3.2" + p-queue "^6.6.2" + p-retry "4" + uuid "^9.0.0" + +leac@^0.6.0: + version "0.6.0" + resolved "https://registry.yarnpkg.com/leac/-/leac-0.6.0.tgz#dcf136e382e666bd2475f44a1096061b70dc0912" + integrity sha512-y+SqErxb8h7nE/fiEX07jsbuhrpO9lL8eca7/Y1nuWV2moNlXhyd59iDGcRf6moVyDMbmTNzL40SUyrFU/yDpg== + +lie@~3.3.0: + version "3.3.0" + resolved "https://registry.yarnpkg.com/lie/-/lie-3.3.0.tgz#dcf82dee545f46074daf200c7c1c5a08e0f40f6a" + integrity sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ== + dependencies: + immediate "~3.0.5" + +lodash.set@^4.3.2: + version "4.3.2" + resolved "https://registry.yarnpkg.com/lodash.set/-/lodash.set-4.3.2.tgz#d8757b1da807dde24816b0d6a84bea1a76230b23" + integrity sha512-4hNPN5jlm/N/HLMCO43v8BXKq9Z7QdAGc/VGrRD61w8gN9g/6jF9A4L1pbUgBLCffi0w9VsXfTOij5x8iTyFvg== + logform@^2.3.2, logform@^2.4.0: version "2.6.0" resolved "https://registry.yarnpkg.com/logform/-/logform-2.6.0.tgz#8c82a983f05d6eaeb2d75e3decae7a768b2bf9b5" @@ -1223,6 +2005,15 @@ long@^4.0.0: resolved "https://registry.yarnpkg.com/long/-/long-4.0.0.tgz#9a7b71cfb7d361a194ea555241c92f7468d5bf28" integrity sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA== +lop@^0.4.1: + version "0.4.2" + resolved "https://registry.yarnpkg.com/lop/-/lop-0.4.2.tgz#c9c2f958a39b9da1c2f36ca9ad66891a9fe84640" + integrity sha512-RefILVDQ4DKoRZsJ4Pj22TxE3omDO47yFpkIBoDKzkqPRISs5U1cnAdg/5583YPkWPaLIYHOKRMQSvjFsO26cw== + dependencies: + duck "^0.1.12" + option "~0.2.1" + underscore "^1.13.1" + lru-cache@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-6.0.0.tgz#6d6fe6570ebd96aaf90fcad1dafa3b2566db3a94" @@ -1235,6 +2026,22 @@ make-error@^1.1.1: resolved "https://registry.yarnpkg.com/make-error/-/make-error-1.3.6.tgz#2eb2e37ea9b67c4891f684a1394799af484cf7a2" integrity sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw== +mammoth@^1.8.0: + version "1.8.0" + resolved "https://registry.yarnpkg.com/mammoth/-/mammoth-1.8.0.tgz#d8f1b0d3a0355fda129270346e9dc853f223028f" + integrity sha512-pJNfxSk9IEGVpau+tsZFz22ofjUsl2mnA5eT8PjPs2n0BP+rhVte4Nez6FdgEuxv3IGI3afiV46ImKqTGDVlbA== + dependencies: + "@xmldom/xmldom" "^0.8.6" + argparse "~1.0.3" + base64-js "^1.5.1" + bluebird "~3.4.0" + dingbat-to-unicode "^1.0.1" + jszip "^3.7.1" + lop "^0.4.1" + path-is-absolute "^1.0.0" + underscore "^1.13.1" + xmlbuilder "^10.0.0" + md5@^2.3.0: version "2.3.0" resolved "https://registry.yarnpkg.com/md5/-/md5-2.3.0.tgz#c3da9a6aae3a30b46b7b0c349b87b110dc3bda4f" @@ -1288,7 +2095,7 @@ minimatch@^3.1.2: dependencies: brace-expansion "^1.1.7" -minimist@^1.2.0, minimist@^1.2.3: +minimist@^1.2.0, minimist@^1.2.3, minimist@^1.2.6: version "1.2.8" resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.8.tgz#c1a464e7693302e082a075cee0c057741ac4772c" integrity sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA== @@ -1298,6 +2105,13 @@ mkdirp-classic@^0.5.2, mkdirp-classic@^0.5.3: resolved "https://registry.yarnpkg.com/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz#fa10c9115cc6d8865be221ba47ee9bed78601113" integrity sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A== +mkdirp@^0.5.4: + version "0.5.6" + resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.6.tgz#7def03d2432dcae4ba1d611445c48396062255f6" + integrity sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw== + dependencies: + minimist "^1.2.6" + ml-array-mean@^1.1.6: version "1.1.6" resolved "https://registry.yarnpkg.com/ml-array-mean/-/ml-array-mean-1.1.6.tgz#d951a700dc8e3a17b3e0a583c2c64abd0c619c56" @@ -1349,6 +2163,24 @@ ms@2.1.3, ms@^2.0.0, ms@^2.1.1: resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== +multer@^1.4.5-lts.1: + version "1.4.5-lts.1" + resolved "https://registry.yarnpkg.com/multer/-/multer-1.4.5-lts.1.tgz#803e24ad1984f58edffbc79f56e305aec5cfd1ac" + integrity sha512-ywPWvcDMeH+z9gQq5qYHCCy+ethsk4goepZ45GLD63fOu0YcNecQxi64nDs3qluZB+murG3/D4dJ7+dGctcCQQ== + dependencies: + append-field "^1.0.0" + busboy "^1.0.0" + concat-stream "^1.5.2" + mkdirp "^0.5.4" + object-assign "^4.1.1" + type-is "^1.6.4" + xtend "^4.0.0" + +mustache@^4.2.0: + version "4.2.0" + resolved "https://registry.yarnpkg.com/mustache/-/mustache-4.2.0.tgz#e5892324d60a12ec9c2a73359edca52972bf6f64" + integrity sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ== + napi-build-utils@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/napi-build-utils/-/napi-build-utils-1.0.2.tgz#b1fddc0b2c46e380a0b7a76f984dd47c41a13806" @@ -1376,6 +2208,11 @@ node-domexception@1.0.0: resolved "https://registry.yarnpkg.com/node-domexception/-/node-domexception-1.0.0.tgz#6888db46a1f71c0b76b3f7555016b63fe64766e5" integrity sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ== +node-ensure@^0.0.0: + version "0.0.0" + resolved "https://registry.yarnpkg.com/node-ensure/-/node-ensure-0.0.0.tgz#ecae764150de99861ec5c810fd5d096b183932a7" + integrity sha512-DRI60hzo2oKN1ma0ckc6nQWlHU69RH6xN0sjQTjMpChPfTYvKZdcQFfdYK2RWbJcKyUizSIy/l8OTGxMAM1QDw== + node-fetch@^2.6.7: version "2.7.0" resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.7.0.tgz#d0f0fa6e3e2dc1d27efcd8ad99d550bda94d187d" @@ -1416,7 +2253,7 @@ num-sort@^2.0.0: resolved "https://registry.yarnpkg.com/num-sort/-/num-sort-2.1.0.tgz#1cbb37aed071329fdf41151258bc011898577a9b" integrity sha512-1MQz1Ed8z2yckoBeSfkQHHO9K1yDRxxtotKSJ9yvcTUUxSvfvzEq5GwBrjjHEpMlq/k5gvXdmJ1SbYxWtpNoVg== -object-assign@^4: +object-assign@^4, object-assign@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" integrity sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg== @@ -1493,11 +2330,30 @@ openai@^4.26.0: node-fetch "^2.6.7" web-streams-polyfill "^3.2.1" +openai@^4.41.1, openai@^4.49.1: + version "4.52.2" + resolved "https://registry.yarnpkg.com/openai/-/openai-4.52.2.tgz#5d67271f3df84c0b54676b08990eaa9402151759" + integrity sha512-mMc0XgFuVSkcm0lRIi8zaw++otC82ZlfkCur1qguXYWPETr/+ZwL9A/vvp3YahX+shpaT6j03dwsmUyLAfmEfg== + dependencies: + "@types/node" "^18.11.18" + "@types/node-fetch" "^2.6.4" + abort-controller "^3.0.0" + agentkeepalive "^4.2.1" + form-data-encoder "1.7.2" + formdata-node "^4.3.2" + node-fetch "^2.6.7" + web-streams-polyfill "^3.2.1" + openapi-types@^12.1.3: version "12.1.3" resolved "https://registry.yarnpkg.com/openapi-types/-/openapi-types-12.1.3.tgz#471995eb26c4b97b7bd356aacf7b91b73e777dd3" integrity sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw== +option@~0.2.1: + version "0.2.4" + resolved "https://registry.yarnpkg.com/option/-/option-0.2.4.tgz#fd475cdf98dcabb3cb397a3ba5284feb45edbfe4" + integrity sha512-pkEqbDyl8ou5cpq+VsnQbe/WlEy5qS7xPzMS1U55OCG9KPvwFD46zDbxQIj3egJSFc3D+XhYOPUzz49zQAVy7A== + p-finally@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/p-finally/-/p-finally-1.0.0.tgz#3fbcfb15b899a44123b34b6dcc18b724336a2cae" @@ -1526,16 +2382,47 @@ p-timeout@^3.2.0: dependencies: p-finally "^1.0.0" +pako@~1.0.2: + version "1.0.11" + resolved "https://registry.yarnpkg.com/pako/-/pako-1.0.11.tgz#6c9599d340d54dfd3946380252a35705a6b992bf" + integrity sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw== + +parseley@^0.12.0: + version "0.12.1" + resolved "https://registry.yarnpkg.com/parseley/-/parseley-0.12.1.tgz#4afd561d50215ebe259e3e7a853e62f600683aef" + integrity sha512-e6qHKe3a9HWr0oMRVDTRhKce+bRO8VGQR3NyVwcjwrbhMmFCX9KszEV35+rn4AdilFAq9VPxP/Fe1wC9Qjd2lw== + dependencies: + leac "^0.6.0" + peberminta "^0.9.0" + parseurl@~1.3.3: version "1.3.3" resolved "https://registry.yarnpkg.com/parseurl/-/parseurl-1.3.3.tgz#9da19e7bee8d12dff0513ed5b76957793bc2e8d4" integrity sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ== +path-is-absolute@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" + integrity sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg== + path-to-regexp@0.1.7: version "0.1.7" resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-0.1.7.tgz#df604178005f522f15eb4490e7247a1bfaa67f8c" integrity sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ== +pdf-parse@^1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/pdf-parse/-/pdf-parse-1.1.1.tgz#745e07408679548b3995ff896fd38e96e19d14a7" + integrity sha512-v6ZJ/efsBpGrGGknjtq9J/oC8tZWq0KWL5vQrk2GlzLEQPUDB1ex+13Rmidl1neNN358Jn9EHZw5y07FFtaC7A== + dependencies: + debug "^3.1.0" + node-ensure "^0.0.0" + +peberminta@^0.9.0: + version "0.9.0" + resolved "https://registry.yarnpkg.com/peberminta/-/peberminta-0.9.0.tgz#8ec9bc0eb84b7d368126e71ce9033501dca2a352" + integrity sha512-XIxfHpEuSJbITd1H3EeQwpcZbTLHc+VVr8ANI9t5sit565tsI4/xK3KWTUFE2e6QiangUkh3B0jihzmGnNrRsQ== + picomatch@^2.0.4, picomatch@^2.2.1: version "2.3.1" resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.1.tgz#3ba3833733646d9d3e4995946c1365a67fb07a42" @@ -1569,6 +2456,11 @@ prettier@^3.2.5: resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.2.5.tgz#e52bc3090586e824964a8813b09aba6233b28368" integrity sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A== +process-nextick-args@~2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.1.tgz#7820d9b16120cc55ca9ae7792680ae7dba6d7fe2" + integrity sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag== + protobufjs@^6.8.8: version "6.11.4" resolved "https://registry.yarnpkg.com/protobufjs/-/protobufjs-6.11.4.tgz#29a412c38bf70d89e537b6d02d904a6f448173aa" @@ -1651,6 +2543,19 @@ rc@^1.2.7: minimist "^1.2.0" strip-json-comments "~2.0.1" +readable-stream@^2.2.2, readable-stream@~2.3.6: + version "2.3.8" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.8.tgz#91125e8042bba1b9887f49345f6277027ce8be9b" + integrity sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA== + dependencies: + core-util-is "~1.0.0" + inherits "~2.0.3" + isarray "~1.0.0" + process-nextick-args "~2.0.0" + safe-buffer "~5.1.1" + string_decoder "~1.1.1" + util-deprecate "~1.0.1" + readable-stream@^3.1.1, readable-stream@^3.4.0, readable-stream@^3.6.0: version "3.6.2" resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-3.6.2.tgz#56a9b36ea965c00c5a93ef31eb111a0f11056967" @@ -1667,6 +2572,11 @@ readdirp@~3.6.0: dependencies: picomatch "^2.2.1" +resolve-pkg-maps@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz#616b3dc2c57056b5588c31cdf4b3d64db133720f" + integrity sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw== + retry@^0.13.1: version "0.13.1" resolved "https://registry.yarnpkg.com/retry/-/retry-0.13.1.tgz#185b1587acf67919d63b357349e03537b2484658" @@ -1677,7 +2587,7 @@ safe-buffer@5.2.1, safe-buffer@^5.0.1, safe-buffer@~5.2.0: resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== -safe-buffer@~5.1.1: +safe-buffer@~5.1.0, safe-buffer@~5.1.1: version "5.1.2" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d" integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g== @@ -1692,6 +2602,13 @@ safe-stable-stringify@^2.3.1: resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg== +selderee@^0.11.0: + version "0.11.0" + resolved "https://registry.yarnpkg.com/selderee/-/selderee-0.11.0.tgz#6af0c7983e073ad3e35787ffe20cefd9daf0ec8a" + integrity sha512-5TF+l7p4+OsnP8BCCvSyZiSPc4x4//p5uPwK8TCnVPJYRmU2aYKMpOXvw8zM5a5JvuuCGN1jmsMwuU2W02ukfA== + dependencies: + parseley "^0.12.0" + semver@^7.3.5, semver@^7.5.3, semver@^7.5.4: version "7.6.0" resolved "https://registry.yarnpkg.com/semver/-/semver-7.6.0.tgz#1a46a4db4bffcccd97b743b5005c8325f23d4e2d" @@ -1699,6 +2616,11 @@ semver@^7.3.5, semver@^7.5.3, semver@^7.5.4: dependencies: lru-cache "^6.0.0" +semver@^7.6.3: + version "7.6.3" + resolved "https://registry.yarnpkg.com/semver/-/semver-7.6.3.tgz#980f7b5550bc175fb4dc09403085627f9eb33143" + integrity sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A== + send@0.18.0: version "0.18.0" resolved "https://registry.yarnpkg.com/send/-/send-0.18.0.tgz#670167cc654b05f5aa4a767f9113bb371bc706be" @@ -1740,6 +2662,11 @@ set-function-length@^1.2.1: gopd "^1.0.1" has-property-descriptors "^1.0.2" +setimmediate@^1.0.5: + version "1.0.5" + resolved "https://registry.yarnpkg.com/setimmediate/-/setimmediate-1.0.5.tgz#290cbb232e306942d7d7ea9b83732ab7856f8285" + integrity sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA== + setprototypeof@1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.2.0.tgz#66c9a24a73f9fc28cbe66b09fed3d33dcaf1b424" @@ -1797,6 +2724,24 @@ simple-update-notifier@^2.0.0: dependencies: semver "^7.5.3" +source-map-support@^0.5.21: + version "0.5.21" + resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.21.tgz#04fe7c7f9e1ed2d662233c28cb2b35b9f63f6e4f" + integrity sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w== + dependencies: + buffer-from "^1.0.0" + source-map "^0.6.0" + +source-map@^0.6.0: + version "0.6.1" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" + integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== + +sprintf-js@~1.0.2: + version "1.0.3" + resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" + integrity sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g== + stack-trace@0.0.x: version "0.0.10" resolved "https://registry.yarnpkg.com/stack-trace/-/stack-trace-0.0.10.tgz#547c70b347e8d32b4e108ea1a2a159e5fdde19c0" @@ -1807,6 +2752,11 @@ statuses@2.0.1: resolved "https://registry.yarnpkg.com/statuses/-/statuses-2.0.1.tgz#55cb000ccf1d48728bd23c685a063998cf1a1b63" integrity sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ== +streamsearch@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/streamsearch/-/streamsearch-1.1.0.tgz#404dd1e2247ca94af554e841a8ef0eaa238da764" + integrity sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg== + streamx@^2.15.0, streamx@^2.16.1: version "2.16.1" resolved "https://registry.yarnpkg.com/streamx/-/streamx-2.16.1.tgz#2b311bd34832f08aa6bb4d6a80297c9caef89614" @@ -1824,11 +2774,23 @@ string_decoder@^1.1.1: dependencies: safe-buffer "~5.2.0" +string_decoder@~1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.1.1.tgz#9cf1611ba62685d7030ae9e4ba34149c3af03fc8" + integrity sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg== + dependencies: + safe-buffer "~5.1.0" + strip-json-comments@~2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a" integrity sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ== +strnum@^1.0.5: + version "1.0.5" + resolved "https://registry.yarnpkg.com/strnum/-/strnum-1.0.5.tgz#5c4e829fe15ad4ff0d20c3db5ac97b73c9b072db" + integrity sha512-J8bbNyKKXl5qYcR36TIO8W3mVGVHrmmxsd5PAItGkmyzwJvybiw2IVq5nqd0i4LSNSkB/sx9VHllbfFdr9k1JA== + supports-color@^5.5.0: version "5.5.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f" @@ -1937,7 +2899,7 @@ tunnel-agent@^0.6.0: dependencies: safe-buffer "^5.0.1" -type-is@~1.6.18: +type-is@^1.6.4, type-is@~1.6.18: version "1.6.18" resolved "https://registry.yarnpkg.com/type-is/-/type-is-1.6.18.tgz#4e552cd05df09467dcbc4ef739de89f2cf37c131" integrity sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g== @@ -1945,6 +2907,11 @@ type-is@~1.6.18: media-typer "0.3.0" mime-types "~2.1.24" +typedarray@^0.0.6: + version "0.0.6" + resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" + integrity sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA== + typescript@^5.4.3: version "5.4.3" resolved "https://registry.yarnpkg.com/typescript/-/typescript-5.4.3.tgz#5c6fedd4c87bee01cd7a528a30145521f8e0feff" @@ -1955,6 +2922,11 @@ undefsafe@^2.0.5: resolved "https://registry.yarnpkg.com/undefsafe/-/undefsafe-2.0.5.tgz#38733b9327bdcd226db889fb723a6efd162e6e2c" integrity sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA== +underscore@^1.13.1: + version "1.13.7" + resolved "https://registry.yarnpkg.com/underscore/-/underscore-1.13.7.tgz#970e33963af9a7dda228f17ebe8399e5fbe63a10" + integrity sha512-GMXzWtsc57XAtguZgaQViUOzs0KTkk8ojr3/xAxXLITqf/3EMwxC0inyETfDFjH/Krbhuep0HNbbjI9i/q3F3g== + undici-types@~5.26.4: version "5.26.5" resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-5.26.5.tgz#bcd539893d00b56e964fd2657a4866b221a65617" @@ -1965,7 +2937,7 @@ unpipe@1.0.0, unpipe@~1.0.0: resolved "https://registry.yarnpkg.com/unpipe/-/unpipe-1.0.0.tgz#b2bf4ee8514aae6165b4817829d21b2ef49904ec" integrity sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ== -util-deprecate@^1.0.1: +util-deprecate@^1.0.1, util-deprecate@~1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" integrity sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw== @@ -1975,6 +2947,11 @@ utils-merge@1.0.1: resolved "https://registry.yarnpkg.com/utils-merge/-/utils-merge-1.0.1.tgz#9f95710f50a267947b2ccc124741c1028427e713" integrity sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA== +uuid@^10.0.0: + version "10.0.0" + resolved "https://registry.yarnpkg.com/uuid/-/uuid-10.0.0.tgz#5a95aa454e6e002725c79055fd42aaba30ca6294" + integrity sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ== + uuid@^9.0.0: version "9.0.1" resolved "https://registry.yarnpkg.com/uuid/-/uuid-9.0.1.tgz#e188d4c8853cc722220392c424cd637f32293f30" @@ -2054,10 +3031,20 @@ wrappy@1: resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" integrity sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ== -ws@^8.16.0: - version "8.16.0" - resolved "https://registry.yarnpkg.com/ws/-/ws-8.16.0.tgz#d1cd774f36fbc07165066a60e40323eab6446fd4" - integrity sha512-HS0c//TP7Ina87TfiPUz1rQzMhHrl/SG2guqRcTOIUYD2q8uhUdNHZYJUaQ8aTGPzCh+c6oawMKW35nFl1dxyQ== +ws@^8.17.1: + version "8.17.1" + resolved "https://registry.yarnpkg.com/ws/-/ws-8.17.1.tgz#9293da530bb548febc95371d90f9c878727d919b" + integrity sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ== + +xmlbuilder@^10.0.0: + version "10.1.1" + resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-10.1.1.tgz#8cae6688cc9b38d850b7c8d3c0a4161dcaf475b0" + integrity sha512-OyzrcFLL/nb6fMGHbiRDuPup9ljBycsdCypwuyg5AAHvyWzGfChJpCXMG88AGTIMFhGZ9RccFN1e6lhg3hkwKg== + +xtend@^4.0.0: + version "4.0.2" + resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.2.tgz#bb72779f5fa465186b1f438f674fa347fdb5db54" + integrity sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ== yallist@^4.0.0: version "4.0.0" @@ -2079,6 +3066,11 @@ zod-to-json-schema@^3.22.3: resolved "https://registry.yarnpkg.com/zod-to-json-schema/-/zod-to-json-schema-3.22.5.tgz#3646e81cfc318dbad2a22519e5ce661615418673" integrity sha512-+akaPo6a0zpVCCseDed504KBJUQpEW5QZw7RMneNmKw+fGaML1Z9tUNLnHHAC8x6dzVRO1eB2oEMyZRnuBZg7Q== +zod-to-json-schema@^3.22.4, zod-to-json-schema@^3.22.5: + version "3.23.1" + resolved "https://registry.yarnpkg.com/zod-to-json-schema/-/zod-to-json-schema-3.23.1.tgz#5225925b8ed5fa20096bd99be076c4b29b53d309" + integrity sha512-oT9INvydob1XV0v1d2IadrR74rLtDInLvDFfAa1CG0Pmg/vxATk7I2gSelfj271mbzeM4Da0uuDQE/Nkj3DWNw== + zod@^3.22.3, zod@^3.22.4: version "3.22.4" resolved "https://registry.yarnpkg.com/zod/-/zod-3.22.4.tgz#f31c3a9386f61b1f228af56faa9255e845cf3fff"