diff --git a/.assets/manifest.json b/.assets/manifest.json new file mode 100644 index 0000000..e69de29 diff --git a/ui/.eslintrc.json b/.eslintrc.json similarity index 100% rename from ui/.eslintrc.json rename to .eslintrc.json diff --git a/.github/workflows/docker-build.yaml b/.github/workflows/docker-build.yaml index f658c29..29f7987 100644 --- a/.github/workflows/docker-build.yaml +++ b/.github/workflows/docker-build.yaml @@ -8,18 +8,12 @@ on: types: [published] jobs: - build-and-push: + build-amd64: 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: @@ -36,38 +30,109 @@ jobs: id: version run: echo "RELEASE_VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV - - name: Build and push Docker image for ${{ matrix.service }} + - name: Build and push AMD64 Docker image 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 \ + DOCKERFILE=app.dockerfile + IMAGE_NAME=perplexica + docker buildx build --platform linux/amd64 \ + --cache-from=type=registry,ref=itzcrazykns1337/${IMAGE_NAME}:amd64 \ --cache-to=type=inline \ + --provenance false \ -f $DOCKERFILE \ - -t itzcrazykns1337/${IMAGE_NAME}:main \ + -t itzcrazykns1337/${IMAGE_NAME}:amd64 \ --push . - - name: Build and push release Docker image for ${{ matrix.service }} + - name: Build and push AMD64 release Docker image 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 }} \ + DOCKERFILE=app.dockerfile + IMAGE_NAME=perplexica + docker buildx build --platform linux/amd64 \ + --cache-from=type=registry,ref=itzcrazykns1337/${IMAGE_NAME}:${{ env.RELEASE_VERSION }}-amd64 \ --cache-to=type=inline \ + --provenance false \ -f $DOCKERFILE \ - -t itzcrazykns1337/${IMAGE_NAME}:${{ env.RELEASE_VERSION }} \ + -t itzcrazykns1337/${IMAGE_NAME}:${{ env.RELEASE_VERSION }}-amd64 \ --push . + + build-arm64: + runs-on: ubuntu-24.04-arm + steps: + - name: Checkout code + uses: actions/checkout@v3 + + - 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 ARM64 Docker image + if: github.ref == 'refs/heads/master' && github.event_name == 'push' + run: | + DOCKERFILE=app.dockerfile + IMAGE_NAME=perplexica + docker buildx build --platform linux/arm64 \ + --cache-from=type=registry,ref=itzcrazykns1337/${IMAGE_NAME}:arm64 \ + --cache-to=type=inline \ + --provenance false \ + -f $DOCKERFILE \ + -t itzcrazykns1337/${IMAGE_NAME}:arm64 \ + --push . + + - name: Build and push ARM64 release Docker image + if: github.event_name == 'release' + run: | + DOCKERFILE=app.dockerfile + IMAGE_NAME=perplexica + docker buildx build --platform linux/arm64 \ + --cache-from=type=registry,ref=itzcrazykns1337/${IMAGE_NAME}:${{ env.RELEASE_VERSION }}-arm64 \ + --cache-to=type=inline \ + --provenance false \ + -f $DOCKERFILE \ + -t itzcrazykns1337/${IMAGE_NAME}:${{ env.RELEASE_VERSION }}-arm64 \ + --push . + + manifest: + needs: [build-amd64, build-arm64] + runs-on: ubuntu-latest + steps: + - 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: Create and push multi-arch manifest for main + if: github.ref == 'refs/heads/master' && github.event_name == 'push' + run: | + IMAGE_NAME=perplexica + docker manifest create itzcrazykns1337/${IMAGE_NAME}:main \ + --amend itzcrazykns1337/${IMAGE_NAME}:amd64 \ + --amend itzcrazykns1337/${IMAGE_NAME}:arm64 + docker manifest push itzcrazykns1337/${IMAGE_NAME}:main + + - name: Create and push multi-arch manifest for releases + if: github.event_name == 'release' + run: | + IMAGE_NAME=perplexica + docker manifest create itzcrazykns1337/${IMAGE_NAME}:${{ env.RELEASE_VERSION }} \ + --amend itzcrazykns1337/${IMAGE_NAME}:${{ env.RELEASE_VERSION }}-amd64 \ + --amend itzcrazykns1337/${IMAGE_NAME}:${{ env.RELEASE_VERSION }}-arm64 + docker manifest push itzcrazykns1337/${IMAGE_NAME}:${{ env.RELEASE_VERSION }} diff --git a/.gitignore b/.gitignore index 8391d19..9fb5e4c 100644 --- a/.gitignore +++ b/.gitignore @@ -4,9 +4,9 @@ npm-debug.log yarn-error.log # Build output -/.next/ -/out/ -/dist/ +.next/ +out/ +dist/ # IDE/Editor specific .vscode/ @@ -37,3 +37,5 @@ Thumbs.db # Db db.sqlite /searxng + +certificates \ No newline at end of file diff --git a/.prettierrc.js b/.prettierrc.js index 1937ff1..8ca480f 100644 --- a/.prettierrc.js +++ b/.prettierrc.js @@ -6,7 +6,6 @@ const config = { endOfLine: 'auto', singleQuote: true, tabWidth: 2, - semi: true, }; module.exports = config; diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 73256bd..7bbb280 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,31 +1,43 @@ # How to Contribute to Perplexica -Hey there, thanks for deciding to contribute to Perplexica. Anything you help with will support the development of Perplexica and will make it better. Let's walk you through the key aspects to ensure your contributions are effective and in harmony with the project's setup. +Thanks for your interest in contributing to Perplexica! Your help makes this project better. This guide explains how to contribute effectively. + +Perplexica is a modern AI chat application with advanced search capabilities. ## Project Structure -Perplexica's design consists of two main domains: +Perplexica's codebase is organized as follows: -- **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. +- **UI Components and Pages**: + - **Components (`src/components`)**: Reusable UI components. + - **Pages and Routes (`src/app`)**: Next.js app directory structure with page components. + - Main app routes include: home (`/`), chat (`/c`), discover (`/discover`), library (`/library`), and settings (`/settings`). + - **API Routes (`src/app/api`)**: API endpoints implemented with Next.js API routes. + - `/api/chat`: Handles chat interactions. + - `/api/search`: Provides direct access to Perplexica's search capabilities. + - Other endpoints for models, files, and suggestions. +- **Backend Logic (`src/lib`)**: Contains all the backend functionality including search, database, and API logic. + - The search functionality is present inside `src/lib/search` directory. + - All of the focus modes are implemented using the Meta Search Agent class in `src/lib/search/metaSearchAgent.ts`. + - Database functionality is in `src/lib/db`. + - Chat model and embedding model providers are managed in `src/lib/providers`. + - Prompt templates and LLM chain definitions are in `src/lib/prompts` and `src/lib/chains` respectively. + +## API Documentation + +Perplexica exposes several API endpoints for programmatic access, including: + +- **Search API**: Access Perplexica's advanced search capabilities directly via the `/api/search` endpoint. For detailed documentation, see `docs/api/search.md`. ## Setting Up Your Environment Before diving into coding, setting up your local environment is key. Here's what you need to do: -### Backend - 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. Run `npm run db:push` to set up the local sqlite. -5. Use `npm run dev` to start the backend in development mode. - -### Frontend - -1. Navigate to the `ui` folder and repeat the process of renaming `.env.example` to `.env`, making sure to provide the frontend-specific variables. -2. Execute `npm install` within the `ui` directory to get the frontend dependencies ready. -3. Launch the frontend development server with `npm run dev`. +2. Rename it to `config.toml` and fill in the necessary configuration fields. +3. Run `npm install` to install all dependencies. +4. Run `npm run db:push` to set up the local sqlite database. +5. Use `npm run dev` to start the application in development mode. **Please note**: Docker configurations are present for setting up production environments, whereas `npm run dev` is used for development purposes. diff --git a/README.md b/README.md index 721d41c..5eb0713 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,23 @@ # 🚀 Perplexica - An AI-powered search engine 🔎 +
+ Special thanks to: +
+
+ + Warp sponsorship + + +### [Warp, the AI Devtool that lives in your terminal](https://www.warp.dev/perplexica) + +[Available for MacOS, Linux, & Windows](https://www.warp.dev/perplexica) + +
+ +
+ +[![Discord](https://dcbadge.limes.pink/api/server/26aArMy8tT?style=flat)](https://discord.gg/26aArMy8tT) + ![preview](.assets/perplexica-screenshot.png?) ## Table of Contents @@ -41,7 +59,7 @@ Want to know more about its architecture and how it works? You can read it [here - **Normal Mode:** Processes your query and performs a web search. - **Focus Modes:** Special modes to better answer specific types of questions. Perplexica currently has 6 focus modes: - **All Mode:** Searches the entire web to find the best results. - - **Writing Assistant Mode:** Helpful for writing tasks that does not require searching the web. + - **Writing Assistant Mode:** Helpful for writing tasks that do not require searching the web. - **Academic Search Mode:** Finds articles and papers, ideal for academic research. - **YouTube Search Mode:** Finds YouTube videos based on the search query. - **Wolfram Alpha Search Mode:** Answers queries that need calculations or data analysis using Wolfram Alpha. @@ -72,6 +90,9 @@ There are mainly 2 ways of installing Perplexica - With Docker, Without Docker. - `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**. - `ANTHROPIC`: Your Anthropic API key. **You only need to fill this if you wish to use Anthropic models**. + - `Gemini`: Your Gemini API key. **You only need to fill this if you wish to use Google's models**. + - `DEEPSEEK`: Your Deepseek API key. **Only needed if you want Deepseek models.** + - `AIMLAPI`: Your AI/ML API key. **Only needed if you want to use AI/ML API models and embeddings.** **Note**: You can change these after starting Perplexica from the settings dialog. @@ -91,14 +112,13 @@ There are mainly 2 ways of installing Perplexica - With Docker, Without Docker. 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. +3. After populating the configuration run `npm i`. +4. Install the dependencies and then execute `npm run build`. +5. Finally, start the app by running `npm run start` **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. +See the [installation documentation](https://github.com/ItzCrazyKns/Perplexica/tree/master/docs/installation) for more information like updating, etc. ### Ollama Connection Errors @@ -115,7 +135,7 @@ If you're encountering an Ollama connection error, it is likely due to the backe 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) + - Inside `/etc/systemd/system/ollama.service`, you need to add `Environment="OLLAMA_HOST=0.0.0.0:11434"`. (Change the port number if you are using a different one.) Then reload the systemd manager configuration with `systemctl daemon-reload`, and 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. @@ -136,11 +156,13 @@ For more details, check out the full documentation [here](https://github.com/Itz ## 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). +Perplexica runs on Next.js and handles all API requests. It works right away on the same network and stays accessible even with port forwarding. ## One-Click Deployment +[![Deploy to Sealos](https://raw.githubusercontent.com/labring-actions/templates/main/Deploy-on-Sealos.svg)](https://usw.sealos.io/?openapp=system-template%3FtemplateName%3Dperplexica) [![Deploy to RepoCloud](https://d16t0pc4846x52.cloudfront.net/deploylobe.svg)](https://repocloud.io/details/?app_id=267) +[![Run on ClawCloud](https://raw.githubusercontent.com/ClawCloud/Run-Template/refs/heads/main/Run-on-ClawCloud.svg)](https://template.run.claw.cloud/?referralCode=U11MRQ8U9RM4&openapp=system-fastdeploy%3FtemplateName%3Dperplexica) ## Upcoming Features diff --git a/app.dockerfile b/app.dockerfile index 488e64b..c3c0fd0 100644 --- a/app.dockerfile +++ b/app.dockerfile @@ -1,15 +1,35 @@ -FROM node:20.18.0-alpine - -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} +FROM node:20.18.0-slim AS builder WORKDIR /home/perplexica -COPY ui /home/perplexica/ +COPY package.json yarn.lock ./ +RUN yarn install --frozen-lockfile --network-timeout 600000 -RUN yarn install --frozen-lockfile +COPY tsconfig.json next.config.mjs next-env.d.ts postcss.config.js drizzle.config.ts tailwind.config.ts ./ +COPY src ./src +COPY public ./public + +RUN mkdir -p /home/perplexica/data RUN yarn build -CMD ["yarn", "start"] \ No newline at end of file +RUN yarn add --dev @vercel/ncc +RUN yarn ncc build ./src/lib/db/migrate.ts -o migrator + +FROM node:20.18.0-slim + +WORKDIR /home/perplexica + +COPY --from=builder /home/perplexica/public ./public +COPY --from=builder /home/perplexica/.next/static ./public/_next/static + +COPY --from=builder /home/perplexica/.next/standalone ./ +COPY --from=builder /home/perplexica/data ./data +COPY drizzle ./drizzle +COPY --from=builder /home/perplexica/migrator/build ./build +COPY --from=builder /home/perplexica/migrator/index.js ./migrate.js + +RUN mkdir /home/perplexica/uploads + +COPY entrypoint.sh ./entrypoint.sh +RUN chmod +x ./entrypoint.sh +CMD ["./entrypoint.sh"] \ No newline at end of file diff --git a/backend.dockerfile b/backend.dockerfile deleted file mode 100644 index b6ab95a..0000000 --- a/backend.dockerfile +++ /dev/null @@ -1,17 +0,0 @@ -FROM node:18-slim - -WORKDIR /home/perplexica - -COPY src /home/perplexica/src -COPY tsconfig.json /home/perplexica/ -COPY drizzle.config.ts /home/perplexica/ -COPY package.json /home/perplexica/ -COPY yarn.lock /home/perplexica/ - -RUN mkdir /home/perplexica/data -RUN mkdir /home/perplexica/uploads - -RUN yarn install --frozen-lockfile --network-timeout 600000 -RUN yarn build - -CMD ["yarn", "start"] \ No newline at end of file diff --git a/docker-compose.yaml b/docker-compose.yaml index a0e1d73..b32e0a9 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -9,41 +9,22 @@ services: - perplexica-network restart: unless-stopped - perplexica-backend: - build: - context: . - dockerfile: backend.dockerfile - 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 - - perplexica-frontend: + app: + image: itzcrazykns1337/perplexica:main build: context: . dockerfile: app.dockerfile - 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 + environment: + - SEARXNG_API_URL=http://searxng:8080 + - DATA_DIR=/home/perplexica ports: - 3000:3000 networks: - perplexica-network + volumes: + - backend-dbstore:/home/perplexica/data + - uploads:/home/perplexica/uploads + - ./config.toml:/home/perplexica/config.toml restart: unless-stopped networks: diff --git a/docs/API/SEARCH.md b/docs/API/SEARCH.md index f87e788..b67b62b 100644 --- a/docs/API/SEARCH.md +++ b/docs/API/SEARCH.md @@ -6,9 +6,9 @@ Perplexica’s Search API makes it easy to use our AI-powered search engine. You ## Endpoint -### **POST** `http://localhost:3001/api/search` +### **POST** `http://localhost:3000/api/search` -**Note**: Replace `3001` with any other port if you've changed the default PORT +**Note**: Replace `3000` with any other port if you've changed the default PORT ### Request @@ -20,11 +20,11 @@ The API accepts a JSON object in the request body, where you define the focus mo { "chatModel": { "provider": "openai", - "model": "gpt-4o-mini" + "name": "gpt-4o-mini" }, "embeddingModel": { "provider": "openai", - "model": "text-embedding-3-large" + "name": "text-embedding-3-large" }, "optimizationMode": "speed", "focusMode": "webSearch", @@ -32,24 +32,26 @@ The API accepts a JSON object in the request body, where you define the focus mo "history": [ ["human", "Hi, how are you?"], ["assistant", "I am doing well, how can I help you today?"] - ] + ], + "systemInstructions": "Focus on providing technical details about Perplexica's architecture.", + "stream": false } ``` ### 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"). +- **`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:3000/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`). + - `name`: 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"). +- **`embeddingModel`** (object, optional): Defines the embedding model for similarity-based searching. For model details you can send a GET request at `http://localhost:3000/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`). + - `name`: The specific embedding model (e.g., `text-embedding-3-large`). - **`focusMode`** (string, required): Specifies which focus mode to use. Available modes: @@ -62,6 +64,8 @@ The API accepts a JSON object in the request body, where you define the focus mo - **`query`** (string, required): The search query or question. +- **`systemInstructions`** (string, optional): Custom instructions provided by the user to guide the AI's response. These instructions are treated as user preferences and have lower priority than the system's core instructions. For example, you can specify a particular writing style, format, or focus area. + - **`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 @@ -71,35 +75,59 @@ The API accepts a JSON object in the request body, where you define the focus mo ] ``` +- **`stream`** (boolean, optional): When set to `true`, enables streaming responses. Default is `false`. + ### Response The response from the API includes both the final message and the sources used to generate that message. -#### Example Response +#### Standard Response (stream: false) ```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" - } - } + "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" + } + } .... - ] + ] } ``` +#### Streaming Response (stream: true) + +When streaming is enabled, the API returns a stream of newline-delimited JSON objects. Each line contains a complete, valid JSON object. The response has Content-Type: application/json. + +Example of streamed response objects: + +``` +{"type":"init","data":"Stream connected"} +{"type":"sources","data":[{"pageContent":"...","metadata":{"title":"...","url":"..."}},...]} +{"type":"response","data":"Perplexica is an "} +{"type":"response","data":"innovative, open-source "} +{"type":"response","data":"AI-powered search engine..."} +{"type":"done"} +``` + +Clients should process each line as a separate JSON object. The different message types include: + +- **`init`**: Initial connection message +- **`sources`**: All sources used for the response +- **`response`**: Chunks of the generated answer text +- **`done`**: Indicates the stream is complete + ### Fields in the Response - **`message`** (string): The search result, generated based on the query and focus mode. 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..6bad4f9 100644 --- a/docs/architecture/WORKING.md +++ b/docs/architecture/WORKING.md @@ -1,19 +1,19 @@ -## 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). We'll understand how Perplexica works by taking an example of a scenario where a user asks: "How does an A.C. work?". We'll break down the process into steps to make it easier to understand. The steps are as follows: -1. The message is sent via WS to the backend server where it invokes the chain. The chain will depend on your focus mode. For this example, let's assume we use the "webSearch" focus mode. +1. The message is sent to the `/api/chat` route where it invokes the chain. The chain will depend on your focus mode. For this example, let's assume we use the "webSearch" focus mode. 2. The chain is now invoked; first, the message is passed to another chain where it first predicts (using the chat history and the question) whether there is a need for sources and searching the web. If there is, it will generate a query (in accordance with the chat history) for searching the web that we'll take up later. If not, the chain will end there, and then the answer generator chain, also known as the response generator, will be started. 3. The query returned by the first chain is passed to SearXNG to search the web for information. 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 deleted file mode 100644 index baad296..0000000 --- a/docs/installation/NETWORKING.md +++ /dev/null @@ -1,109 +0,0 @@ -# Expose Perplexica to a network - -This guide will show you how to make Perplexica available over a network. Follow these steps to allow computers on the same network to interact with Perplexica. Choose the instructions that match the operating system you are using. - -## Windows - -1. Open PowerShell as Administrator - -2. Navigate to the directory containing the `docker-compose.yaml` file - -3. Stop and remove the existing Perplexica containers and images: - -``` -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 -``` - -6. Save and close the `docker-compose.yaml` file - -7. Rebuild and restart the Perplexica container: - -``` -docker compose up -d --build -``` - -## macOS - -1. Open the Terminal application - -2. Navigate to the directory with the `docker-compose.yaml` file: - -``` -cd /path/to/docker-compose.yaml -``` - -3. Stop and remove existing containers and images: - -``` -docker compose down --rmi all -``` - -4. Open `docker-compose.yaml` in a text editor like Sublime Text: - -``` -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 -``` - -6. Save and exit the editor - -7. Rebuild and restart Perplexica: - -``` -docker compose up -d --build -``` - -## Linux - -1. Open the terminal - -2. Navigate to the `docker-compose.yaml` directory: - -``` -cd /path/to/docker-compose.yaml -``` - -3. Stop and remove containers and images: - -``` -docker compose down --rmi all -``` - -4. Edit `docker-compose.yaml`: - -``` -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 -``` - -6. Save and exit the editor - -7. Rebuild and restart Perplexica: - -``` -docker compose up -d --build -``` diff --git a/docs/installation/UPDATING.md b/docs/installation/UPDATING.md index 031a3e8..66edf5c 100644 --- a/docs/installation/UPDATING.md +++ b/docs/installation/UPDATING.md @@ -6,35 +6,41 @@ To update Perplexica to the latest version, follow these steps: 1. Clone the latest version of Perplexica from GitHub: -```bash + ```bash git clone https://github.com/ItzCrazyKns/Perplexica.git -``` + ``` -2. Navigate to the Project Directory. +2. Navigate to the project directory. -3. Pull latest images from registry. +3. Check for changes in the configuration files. If the `sample.config.toml` file contains new fields, delete your existing `config.toml` file, rename `sample.config.toml` to `config.toml`, and update the configuration accordingly. -```bash -docker compose pull -``` +4. Pull the latest images from the registry. -4. Update and Recreate containers. + ```bash + docker compose pull + ``` -```bash -docker compose up -d -``` +5. Update and recreate the containers. -5. Once the command completes running go to http://localhost:3000 and verify the latest changes. + ```bash + docker compose up -d + ``` -## For non Docker users +6. Once the command completes, go to http://localhost:3000 and verify the latest changes. + +## For non-Docker users 1. Clone the latest version of Perplexica from GitHub: -```bash + ```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. +2. Navigate to the project directory. + +3. Check for changes in the configuration files. If the `sample.config.toml` file contains new fields, delete your existing `config.toml` file, rename `sample.config.toml` to `config.toml`, and update the configuration accordingly. +4. After populating the configuration run `npm i`. +5. Install the dependencies and then execute `npm run build`. +6. Finally, start the app by running `npm run start` + +--- diff --git a/drizzle.config.ts b/drizzle.config.ts index 9ac3ec5..a029112 100644 --- a/drizzle.config.ts +++ b/drizzle.config.ts @@ -1,10 +1,11 @@ import { defineConfig } from 'drizzle-kit'; +import path from 'path'; export default defineConfig({ dialect: 'sqlite', - schema: './src/db/schema.ts', + schema: './src/lib/db/schema.ts', out: './drizzle', dbCredentials: { - url: './data/db.sqlite', + url: path.join(process.cwd(), 'data', 'db.sqlite'), }, }); diff --git a/drizzle/0000_fuzzy_randall.sql b/drizzle/0000_fuzzy_randall.sql new file mode 100644 index 0000000..0a2ff07 --- /dev/null +++ b/drizzle/0000_fuzzy_randall.sql @@ -0,0 +1,16 @@ +CREATE TABLE IF NOT EXISTS `chats` ( + `id` text PRIMARY KEY NOT NULL, + `title` text NOT NULL, + `createdAt` text NOT NULL, + `focusMode` text NOT NULL, + `files` text DEFAULT '[]' +); +--> statement-breakpoint +CREATE TABLE IF NOT EXISTS `messages` ( + `id` integer PRIMARY KEY NOT NULL, + `content` text NOT NULL, + `chatId` text NOT NULL, + `messageId` text NOT NULL, + `type` text, + `metadata` text +); diff --git a/drizzle/meta/0000_snapshot.json b/drizzle/meta/0000_snapshot.json new file mode 100644 index 0000000..850bcd3 --- /dev/null +++ b/drizzle/meta/0000_snapshot.json @@ -0,0 +1,116 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "ef3a044b-0f34-40b5-babb-2bb3a909ba27", + "prevId": "00000000-0000-0000-0000-000000000000", + "tables": { + "chats": { + "name": "chats", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "focusMode": { + "name": "focusMode", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "files": { + "name": "files", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "'[]'" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "messages": { + "name": "messages", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "chatId": { + "name": "chatId", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "messageId": { + "name": "messageId", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata": { + "name": "metadata", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json new file mode 100644 index 0000000..5db59d1 --- /dev/null +++ b/drizzle/meta/_journal.json @@ -0,0 +1,13 @@ +{ + "version": "7", + "dialect": "sqlite", + "entries": [ + { + "idx": 0, + "version": "6", + "when": 1748405503809, + "tag": "0000_fuzzy_randall", + "breakpoints": true + } + ] +} diff --git a/entrypoint.sh b/entrypoint.sh new file mode 100644 index 0000000..9f9448a --- /dev/null +++ b/entrypoint.sh @@ -0,0 +1,6 @@ +#!/bin/sh +set -e + +node migrate.js + +exec node server.js \ No newline at end of file diff --git a/next-env.d.ts b/next-env.d.ts new file mode 100644 index 0000000..1b3be08 --- /dev/null +++ b/next-env.d.ts @@ -0,0 +1,5 @@ +/// +/// + +// NOTE: This file should not be edited +// see https://nextjs.org/docs/app/api-reference/config/typescript for more information. diff --git a/ui/next.config.mjs b/next.config.mjs similarity index 75% rename from ui/next.config.mjs rename to next.config.mjs index c3f2e1a..2300ff4 100644 --- a/ui/next.config.mjs +++ b/next.config.mjs @@ -1,5 +1,6 @@ /** @type {import('next').NextConfig} */ const nextConfig = { + output: 'standalone', images: { remotePatterns: [ { @@ -7,6 +8,7 @@ const nextConfig = { }, ], }, + serverExternalPackages: ['pdf-parse'], }; export default nextConfig; diff --git a/package.json b/package.json index 3fce442..5715c2a 100644 --- a/package.json +++ b/package.json @@ -1,53 +1,70 @@ { - "name": "perplexica-backend", - "version": "1.10.0-rc2", + "name": "perplexica-frontend", + "version": "1.11.0-rc2", "license": "MIT", "author": "ItzCrazyKns", "scripts": { - "start": "npm run db:push && node dist/app.js", - "build": "tsc", - "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", - "typescript": "^5.4.3" + "dev": "next dev", + "build": "npm run db:push && next build", + "start": "next start", + "lint": "next lint", + "format:write": "prettier . --write", + "db:push": "drizzle-kit push" }, "dependencies": { + "@headlessui/react": "^2.2.0", "@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", + "@icons-pack/react-simple-icons": "^12.3.0", + "@langchain/anthropic": "^0.3.24", + "@langchain/community": "^0.3.49", + "@langchain/core": "^0.3.66", + "@langchain/google-genai": "^0.2.15", + "@langchain/groq": "^0.2.3", + "@langchain/ollama": "^0.2.3", + "@langchain/openai": "^0.6.2", + "@langchain/textsplitters": "^0.1.0", + "@tailwindcss/typography": "^0.5.12", + "@xenova/transformers": "^2.17.2", + "axios": "^1.8.3", + "better-sqlite3": "^11.9.1", + "clsx": "^2.1.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", + "drizzle-orm": "^0.40.1", "html-to-text": "^9.0.5", - "langchain": "^0.1.30", - "mammoth": "^1.8.0", - "multer": "^1.4.5-lts.1", + "jspdf": "^3.0.1", + "langchain": "^0.3.30", + "lucide-react": "^0.363.0", + "mammoth": "^1.9.1", + "markdown-to-jsx": "^7.7.2", + "next": "^15.2.2", + "next-themes": "^0.3.0", "pdf-parse": "^1.1.1", - "winston": "^3.13.0", - "ws": "^8.17.1", + "react": "^18", + "react-dom": "^18", + "react-text-to-speech": "^0.14.5", + "react-textarea-autosize": "^8.5.3", + "sonner": "^1.4.41", + "tailwind-merge": "^2.2.2", + "winston": "^3.17.0", + "yet-another-react-lightbox": "^3.17.2", "zod": "^3.22.4" + }, + "devDependencies": { + "@types/better-sqlite3": "^7.6.12", + "@types/html-to-text": "^9.0.4", + "@types/jspdf": "^2.0.0", + "@types/node": "^20", + "@types/pdf-parse": "^1.1.4", + "@types/react": "^18", + "@types/react-dom": "^18", + "autoprefixer": "^10.0.1", + "drizzle-kit": "^0.30.5", + "eslint": "^8", + "eslint-config-next": "14.1.4", + "postcss": "^8", + "prettier": "^3.2.5", + "tailwindcss": "^3.3.0", + "typescript": "^5" } } diff --git a/ui/postcss.config.js b/postcss.config.js similarity index 100% rename from ui/postcss.config.js rename to postcss.config.js diff --git a/public/icon-100.png b/public/icon-100.png new file mode 100644 index 0000000..98fa242 Binary files /dev/null and b/public/icon-100.png differ diff --git a/public/icon-50.png b/public/icon-50.png new file mode 100644 index 0000000..9bb7a0e Binary files /dev/null and b/public/icon-50.png differ diff --git a/public/icon.png b/public/icon.png new file mode 100644 index 0000000..f6fe3c7 Binary files /dev/null and b/public/icon.png differ diff --git a/ui/public/next.svg b/public/next.svg similarity index 100% rename from ui/public/next.svg rename to public/next.svg diff --git a/public/screenshots/p1.png b/public/screenshots/p1.png new file mode 100644 index 0000000..02f01e5 Binary files /dev/null and b/public/screenshots/p1.png differ diff --git a/public/screenshots/p1_small.png b/public/screenshots/p1_small.png new file mode 100644 index 0000000..13d9a42 Binary files /dev/null and b/public/screenshots/p1_small.png differ diff --git a/public/screenshots/p2.png b/public/screenshots/p2.png new file mode 100644 index 0000000..1171675 Binary files /dev/null and b/public/screenshots/p2.png differ diff --git a/public/screenshots/p2_small.png b/public/screenshots/p2_small.png new file mode 100644 index 0000000..bd8d673 Binary files /dev/null and b/public/screenshots/p2_small.png differ diff --git a/ui/public/vercel.svg b/public/vercel.svg similarity index 100% rename from ui/public/vercel.svg rename to public/vercel.svg diff --git a/public/weather-ico/clear-day.svg b/public/weather-ico/clear-day.svg new file mode 100644 index 0000000..d97d28b --- /dev/null +++ b/public/weather-ico/clear-day.svg @@ -0,0 +1,131 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/clear-night.svg b/public/weather-ico/clear-night.svg new file mode 100644 index 0000000..005ac63 --- /dev/null +++ b/public/weather-ico/clear-night.svg @@ -0,0 +1,159 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/cloudy-1-day.svg b/public/weather-ico/cloudy-1-day.svg new file mode 100644 index 0000000..823fea1 --- /dev/null +++ b/public/weather-ico/cloudy-1-day.svg @@ -0,0 +1,178 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/cloudy-1-night.svg b/public/weather-ico/cloudy-1-night.svg new file mode 100644 index 0000000..3fe1541 --- /dev/null +++ b/public/weather-ico/cloudy-1-night.svg @@ -0,0 +1,206 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/fog-day.svg b/public/weather-ico/fog-day.svg new file mode 100644 index 0000000..ed834cf --- /dev/null +++ b/public/weather-ico/fog-day.svg @@ -0,0 +1,244 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + F + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/fog-night.svg b/public/weather-ico/fog-night.svg new file mode 100644 index 0000000..d59f98f --- /dev/null +++ b/public/weather-ico/fog-night.svg @@ -0,0 +1,309 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/frost-day.svg b/public/weather-ico/frost-day.svg new file mode 100644 index 0000000..16d591c --- /dev/null +++ b/public/weather-ico/frost-day.svg @@ -0,0 +1,204 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + F + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/frost-night.svg b/public/weather-ico/frost-night.svg new file mode 100644 index 0000000..ff2c8dc --- /dev/null +++ b/public/weather-ico/frost-night.svg @@ -0,0 +1,269 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/rain-and-sleet-mix.svg b/public/weather-ico/rain-and-sleet-mix.svg new file mode 100644 index 0000000..172010d --- /dev/null +++ b/public/weather-ico/rain-and-sleet-mix.svg @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/rainy-1-day.svg b/public/weather-ico/rainy-1-day.svg new file mode 100644 index 0000000..2faf06e --- /dev/null +++ b/public/weather-ico/rainy-1-day.svg @@ -0,0 +1,179 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/rainy-1-night.svg b/public/weather-ico/rainy-1-night.svg new file mode 100644 index 0000000..ee8ffd8 --- /dev/null +++ b/public/weather-ico/rainy-1-night.svg @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/rainy-2-day.svg b/public/weather-ico/rainy-2-day.svg new file mode 100644 index 0000000..affdfff --- /dev/null +++ b/public/weather-ico/rainy-2-day.svg @@ -0,0 +1,204 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/rainy-2-night.svg b/public/weather-ico/rainy-2-night.svg new file mode 100644 index 0000000..9c3ae20 --- /dev/null +++ b/public/weather-ico/rainy-2-night.svg @@ -0,0 +1,256 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/rainy-3-day.svg b/public/weather-ico/rainy-3-day.svg new file mode 100644 index 0000000..b0b5754 --- /dev/null +++ b/public/weather-ico/rainy-3-day.svg @@ -0,0 +1,206 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/rainy-3-night.svg b/public/weather-ico/rainy-3-night.svg new file mode 100644 index 0000000..4078e7d --- /dev/null +++ b/public/weather-ico/rainy-3-night.svg @@ -0,0 +1,270 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/scattered-thunderstorms-day.svg b/public/weather-ico/scattered-thunderstorms-day.svg new file mode 100644 index 0000000..0cfbccc --- /dev/null +++ b/public/weather-ico/scattered-thunderstorms-day.svg @@ -0,0 +1,374 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/scattered-thunderstorms-night.svg b/public/weather-ico/scattered-thunderstorms-night.svg new file mode 100644 index 0000000..72cf7a6 --- /dev/null +++ b/public/weather-ico/scattered-thunderstorms-night.svg @@ -0,0 +1,283 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/severe-thunderstorm.svg b/public/weather-ico/severe-thunderstorm.svg new file mode 100644 index 0000000..223198b --- /dev/null +++ b/public/weather-ico/severe-thunderstorm.svg @@ -0,0 +1,307 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/snowy-1-day.svg b/public/weather-ico/snowy-1-day.svg new file mode 100644 index 0000000..fb73943 --- /dev/null +++ b/public/weather-ico/snowy-1-day.svg @@ -0,0 +1,241 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/snowy-1-night.svg b/public/weather-ico/snowy-1-night.svg new file mode 100644 index 0000000..039ea2e --- /dev/null +++ b/public/weather-ico/snowy-1-night.svg @@ -0,0 +1,269 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/snowy-2-day.svg b/public/weather-ico/snowy-2-day.svg new file mode 100644 index 0000000..323a616 --- /dev/null +++ b/public/weather-ico/snowy-2-day.svg @@ -0,0 +1,273 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/snowy-2-night.svg b/public/weather-ico/snowy-2-night.svg new file mode 100644 index 0000000..10dcbfa --- /dev/null +++ b/public/weather-ico/snowy-2-night.svg @@ -0,0 +1,301 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/snowy-3-day.svg b/public/weather-ico/snowy-3-day.svg new file mode 100644 index 0000000..846c17a --- /dev/null +++ b/public/weather-ico/snowy-3-day.svg @@ -0,0 +1,334 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/weather-ico/snowy-3-night.svg b/public/weather-ico/snowy-3-night.svg new file mode 100644 index 0000000..b3c8c24 --- /dev/null +++ b/public/weather-ico/snowy-3-night.svg @@ -0,0 +1,361 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/sample.config.toml b/sample.config.toml index 50ba95d..ba3e98e 100644 --- a/sample.config.toml +++ b/sample.config.toml @@ -1,14 +1,35 @@ [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 +[MODELS.OPENAI] +API_KEY = "" + +[MODELS.GROQ] +API_KEY = "" + +[MODELS.ANTHROPIC] +API_KEY = "" + +[MODELS.GEMINI] +API_KEY = "" + +[MODELS.CUSTOM_OPENAI] +API_KEY = "" +API_URL = "" +MODEL_NAME = "" + +[MODELS.OLLAMA] +API_URL = "" # Ollama API URL - http://host.docker.internal:11434 + +[MODELS.DEEPSEEK] +API_KEY = "" + +[MODELS.AIMLAPI] +API_KEY = "" # Required to use AI/ML API chat and embedding models + +[MODELS.LM_STUDIO] +API_URL = "" # LM Studio API URL - http://host.docker.internal:1234 [API_ENDPOINTS] -SEARXNG = "http://localhost:32768" # SearxNG API URL -OLLAMA = "" # Ollama API URL - http://host.docker.internal:11434 \ No newline at end of file +SEARXNG = "" # SearxNG API URL - http://localhost:32768 diff --git a/src/app.ts b/src/app.ts deleted file mode 100644 index 96b3a0c..0000000 --- a/src/app.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { startWebSocketServer } from './websocket'; -import express from 'express'; -import cors from 'cors'; -import http from 'http'; -import routes from './routes'; -import { getPort } from './config'; -import logger from './utils/logger'; - -const port = getPort(); - -const app = express(); -const server = http.createServer(app); - -const corsOptions = { - origin: '*', -}; - -app.use(cors(corsOptions)); -app.use(express.json()); - -app.use('/api', routes); -app.get('/api', (_, res) => { - res.status(200).json({ status: 'ok' }); -}); - -server.listen(port, () => { - logger.info(`Server is running on port ${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/app/api/chat/route.ts b/src/app/api/chat/route.ts new file mode 100644 index 0000000..ba88da6 --- /dev/null +++ b/src/app/api/chat/route.ts @@ -0,0 +1,310 @@ +import crypto from 'crypto'; +import { AIMessage, BaseMessage, HumanMessage } from '@langchain/core/messages'; +import { EventEmitter } from 'stream'; +import { + getAvailableChatModelProviders, + getAvailableEmbeddingModelProviders, +} from '@/lib/providers'; +import db from '@/lib/db'; +import { chats, messages as messagesSchema } from '@/lib/db/schema'; +import { and, eq, gt } from 'drizzle-orm'; +import { getFileDetails } from '@/lib/utils/files'; +import { BaseChatModel } from '@langchain/core/language_models/chat_models'; +import { ChatOpenAI } from '@langchain/openai'; +import { + getCustomOpenaiApiKey, + getCustomOpenaiApiUrl, + getCustomOpenaiModelName, +} from '@/lib/config'; +import { searchHandlers } from '@/lib/search'; + +export const runtime = 'nodejs'; +export const dynamic = 'force-dynamic'; + +type Message = { + messageId: string; + chatId: string; + content: string; +}; + +type ChatModel = { + provider: string; + name: string; +}; + +type EmbeddingModel = { + provider: string; + name: string; +}; + +type Body = { + message: Message; + optimizationMode: 'speed' | 'balanced' | 'quality'; + focusMode: string; + history: Array<[string, string]>; + files: Array; + chatModel: ChatModel; + embeddingModel: EmbeddingModel; + systemInstructions: string; +}; + +const handleEmitterEvents = async ( + stream: EventEmitter, + writer: WritableStreamDefaultWriter, + encoder: TextEncoder, + aiMessageId: string, + chatId: string, +) => { + let recievedMessage = ''; + let sources: any[] = []; + + stream.on('data', (data) => { + const parsedData = JSON.parse(data); + if (parsedData.type === 'response') { + writer.write( + encoder.encode( + JSON.stringify({ + type: 'message', + data: parsedData.data, + messageId: aiMessageId, + }) + '\n', + ), + ); + + recievedMessage += parsedData.data; + } else if (parsedData.type === 'sources') { + writer.write( + encoder.encode( + JSON.stringify({ + type: 'sources', + data: parsedData.data, + messageId: aiMessageId, + }) + '\n', + ), + ); + + sources = parsedData.data; + } + }); + stream.on('end', () => { + writer.write( + encoder.encode( + JSON.stringify({ + type: 'messageEnd', + messageId: aiMessageId, + }) + '\n', + ), + ); + writer.close(); + + db.insert(messagesSchema) + .values({ + content: recievedMessage, + chatId: chatId, + messageId: aiMessageId, + role: 'assistant', + metadata: JSON.stringify({ + createdAt: new Date(), + ...(sources && sources.length > 0 && { sources }), + }), + }) + .execute(); + }); + stream.on('error', (data) => { + const parsedData = JSON.parse(data); + writer.write( + encoder.encode( + JSON.stringify({ + type: 'error', + data: parsedData.data, + }), + ), + ); + writer.close(); + }); +}; + +const handleHistorySave = async ( + message: Message, + humanMessageId: string, + focusMode: string, + files: string[], +) => { + const chat = await db.query.chats.findFirst({ + where: eq(chats.id, message.chatId), + }); + + const fileData = files.map(getFileDetails); + + if (!chat) { + await db + .insert(chats) + .values({ + id: message.chatId, + title: message.content, + createdAt: new Date().toString(), + focusMode: focusMode, + files: fileData, + }) + .execute(); + } else if (JSON.stringify(chat.files ?? []) != JSON.stringify(fileData)) { + db.update(chats) + .set({ + files: files.map(getFileDetails), + }) + .where(eq(chats.id, message.chatId)); + } + + const messageExists = await db.query.messages.findFirst({ + where: eq(messagesSchema.messageId, humanMessageId), + }); + + if (!messageExists) { + await db + .insert(messagesSchema) + .values({ + content: message.content, + chatId: message.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, message.chatId), + ), + ) + .execute(); + } +}; + +export const POST = async (req: Request) => { + try { + const body = (await req.json()) as Body; + const { message } = body; + + if (message.content === '') { + return Response.json( + { + message: 'Please provide a message to process', + }, + { status: 400 }, + ); + } + + const [chatModelProviders, embeddingModelProviders] = await Promise.all([ + getAvailableChatModelProviders(), + getAvailableEmbeddingModelProviders(), + ]); + + const chatModelProvider = + chatModelProviders[ + body.chatModel?.provider || Object.keys(chatModelProviders)[0] + ]; + const chatModel = + chatModelProvider[ + body.chatModel?.name || Object.keys(chatModelProvider)[0] + ]; + + const embeddingProvider = + embeddingModelProviders[ + body.embeddingModel?.provider || Object.keys(embeddingModelProviders)[0] + ]; + const embeddingModel = + embeddingProvider[ + body.embeddingModel?.name || Object.keys(embeddingProvider)[0] + ]; + + let llm: BaseChatModel | undefined; + let embedding = embeddingModel.model; + + if (body.chatModel?.provider === 'custom_openai') { + llm = new ChatOpenAI({ + apiKey: getCustomOpenaiApiKey(), + modelName: getCustomOpenaiModelName(), + temperature: 0.7, + configuration: { + baseURL: getCustomOpenaiApiUrl(), + }, + }) as unknown as BaseChatModel; + } else if (chatModelProvider && chatModel) { + llm = chatModel.model; + } + + if (!llm) { + return Response.json({ error: 'Invalid chat model' }, { status: 400 }); + } + + if (!embedding) { + return Response.json( + { error: 'Invalid embedding model' }, + { status: 400 }, + ); + } + + const humanMessageId = + message.messageId ?? crypto.randomBytes(7).toString('hex'); + const aiMessageId = crypto.randomBytes(7).toString('hex'); + + 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 handler = searchHandlers[body.focusMode]; + + if (!handler) { + return Response.json( + { + message: 'Invalid focus mode', + }, + { status: 400 }, + ); + } + + const stream = await handler.searchAndAnswer( + message.content, + history, + llm, + embedding, + body.optimizationMode, + body.files, + body.systemInstructions, + ); + + const responseStream = new TransformStream(); + const writer = responseStream.writable.getWriter(); + const encoder = new TextEncoder(); + + handleEmitterEvents(stream, writer, encoder, aiMessageId, message.chatId); + handleHistorySave(message, humanMessageId, body.focusMode, body.files); + + return new Response(responseStream.readable, { + headers: { + 'Content-Type': 'text/event-stream', + Connection: 'keep-alive', + 'Cache-Control': 'no-cache, no-transform', + }, + }); + } catch (err) { + console.error('An error occurred while processing chat request:', err); + return Response.json( + { message: 'An error occurred while processing chat request' }, + { status: 500 }, + ); + } +}; diff --git a/src/app/api/chats/[id]/route.ts b/src/app/api/chats/[id]/route.ts new file mode 100644 index 0000000..6891454 --- /dev/null +++ b/src/app/api/chats/[id]/route.ts @@ -0,0 +1,69 @@ +import db from '@/lib/db'; +import { chats, messages } from '@/lib/db/schema'; +import { eq } from 'drizzle-orm'; + +export const GET = async ( + req: Request, + { params }: { params: Promise<{ id: string }> }, +) => { + try { + const { id } = await params; + + const chatExists = await db.query.chats.findFirst({ + where: eq(chats.id, id), + }); + + if (!chatExists) { + return Response.json({ message: 'Chat not found' }, { status: 404 }); + } + + const chatMessages = await db.query.messages.findMany({ + where: eq(messages.chatId, id), + }); + + return Response.json( + { + chat: chatExists, + messages: chatMessages, + }, + { status: 200 }, + ); + } catch (err) { + console.error('Error in getting chat by id: ', err); + return Response.json( + { message: 'An error has occurred.' }, + { status: 500 }, + ); + } +}; + +export const DELETE = async ( + req: Request, + { params }: { params: Promise<{ id: string }> }, +) => { + try { + const { id } = await params; + + const chatExists = await db.query.chats.findFirst({ + where: eq(chats.id, id), + }); + + if (!chatExists) { + return Response.json({ message: 'Chat not found' }, { status: 404 }); + } + + await db.delete(chats).where(eq(chats.id, id)).execute(); + await db.delete(messages).where(eq(messages.chatId, id)).execute(); + + return Response.json( + { message: 'Chat deleted successfully' }, + { status: 200 }, + ); + } catch (err) { + console.error('Error in deleting chat by id: ', err); + return Response.json( + { message: 'An error has occurred.' }, + { status: 500 }, + ); + } +}; diff --git a/src/app/api/chats/route.ts b/src/app/api/chats/route.ts new file mode 100644 index 0000000..986a192 --- /dev/null +++ b/src/app/api/chats/route.ts @@ -0,0 +1,15 @@ +import db from '@/lib/db'; + +export const GET = async (req: Request) => { + try { + let chats = await db.query.chats.findMany(); + chats = chats.reverse(); + return Response.json({ chats: chats }, { status: 200 }); + } catch (err) { + console.error('Error in getting chats: ', err); + return Response.json( + { message: 'An error has occurred.' }, + { status: 500 }, + ); + } +}; diff --git a/src/app/api/config/route.ts b/src/app/api/config/route.ts new file mode 100644 index 0000000..f117cce --- /dev/null +++ b/src/app/api/config/route.ts @@ -0,0 +1,127 @@ +import { + getAnthropicApiKey, + getCustomOpenaiApiKey, + getCustomOpenaiApiUrl, + getCustomOpenaiModelName, + getGeminiApiKey, + getGroqApiKey, + getOllamaApiEndpoint, + getOpenaiApiKey, + getDeepseekApiKey, + getAimlApiKey, + getLMStudioApiEndpoint, + updateConfig, + getOllamaApiKey, +} from '@/lib/config'; +import { + getAvailableChatModelProviders, + getAvailableEmbeddingModelProviders, +} from '@/lib/providers'; + +export const GET = async (req: Request) => { + try { + const config: Record = {}; + + const [chatModelProviders, embeddingModelProviders] = await Promise.all([ + getAvailableChatModelProviders(), + getAvailableEmbeddingModelProviders(), + ]); + + config['chatModelProviders'] = {}; + config['embeddingModelProviders'] = {}; + + for (const provider in chatModelProviders) { + config['chatModelProviders'][provider] = Object.keys( + chatModelProviders[provider], + ).map((model) => { + return { + name: model, + displayName: chatModelProviders[provider][model].displayName, + }; + }); + } + + for (const provider in embeddingModelProviders) { + config['embeddingModelProviders'][provider] = Object.keys( + embeddingModelProviders[provider], + ).map((model) => { + return { + name: model, + displayName: embeddingModelProviders[provider][model].displayName, + }; + }); + } + + config['openaiApiKey'] = getOpenaiApiKey(); + config['ollamaApiUrl'] = getOllamaApiEndpoint(); + config['ollamaApiKey'] = getOllamaApiKey(); + config['lmStudioApiUrl'] = getLMStudioApiEndpoint(); + config['anthropicApiKey'] = getAnthropicApiKey(); + config['groqApiKey'] = getGroqApiKey(); + config['geminiApiKey'] = getGeminiApiKey(); + config['deepseekApiKey'] = getDeepseekApiKey(); + config['aimlApiKey'] = getAimlApiKey(); + config['customOpenaiApiUrl'] = getCustomOpenaiApiUrl(); + config['customOpenaiApiKey'] = getCustomOpenaiApiKey(); + config['customOpenaiModelName'] = getCustomOpenaiModelName(); + + return Response.json({ ...config }, { status: 200 }); + } catch (err) { + console.error('An error occurred while getting config:', err); + return Response.json( + { message: 'An error occurred while getting config' }, + { status: 500 }, + ); + } +}; + +export const POST = async (req: Request) => { + try { + const config = await req.json(); + + const updatedConfig = { + MODELS: { + OPENAI: { + API_KEY: config.openaiApiKey, + }, + GROQ: { + API_KEY: config.groqApiKey, + }, + ANTHROPIC: { + API_KEY: config.anthropicApiKey, + }, + GEMINI: { + API_KEY: config.geminiApiKey, + }, + OLLAMA: { + API_URL: config.ollamaApiUrl, + API_KEY: config.ollamaApiKey, + }, + DEEPSEEK: { + API_KEY: config.deepseekApiKey, + }, + AIMLAPI: { + API_KEY: config.aimlApiKey, + }, + LM_STUDIO: { + API_URL: config.lmStudioApiUrl, + }, + CUSTOM_OPENAI: { + API_URL: config.customOpenaiApiUrl, + API_KEY: config.customOpenaiApiKey, + MODEL_NAME: config.customOpenaiModelName, + }, + }, + }; + + updateConfig(updatedConfig); + + return Response.json({ message: 'Config updated' }, { status: 200 }); + } catch (err) { + console.error('An error occurred while updating config:', err); + return Response.json( + { message: 'An error occurred while updating config' }, + { status: 500 }, + ); + } +}; diff --git a/src/app/api/discover/route.ts b/src/app/api/discover/route.ts new file mode 100644 index 0000000..415aee8 --- /dev/null +++ b/src/app/api/discover/route.ts @@ -0,0 +1,98 @@ +import { searchSearxng } from '@/lib/searxng'; + +const websitesForTopic = { + tech: { + query: ['technology news', 'latest tech', 'AI', 'science and innovation'], + links: ['techcrunch.com', 'wired.com', 'theverge.com'], + }, + finance: { + query: ['finance news', 'economy', 'stock market', 'investing'], + links: ['bloomberg.com', 'cnbc.com', 'marketwatch.com'], + }, + art: { + query: ['art news', 'culture', 'modern art', 'cultural events'], + links: ['artnews.com', 'hyperallergic.com', 'theartnewspaper.com'], + }, + sports: { + query: ['sports news', 'latest sports', 'cricket football tennis'], + links: ['espn.com', 'bbc.com/sport', 'skysports.com'], + }, + entertainment: { + query: ['entertainment news', 'movies', 'TV shows', 'celebrities'], + links: ['hollywoodreporter.com', 'variety.com', 'deadline.com'], + }, +}; + +type Topic = keyof typeof websitesForTopic; + +export const GET = async (req: Request) => { + try { + const params = new URL(req.url).searchParams; + + const mode: 'normal' | 'preview' = + (params.get('mode') as 'normal' | 'preview') || 'normal'; + const topic: Topic = (params.get('topic') as Topic) || 'tech'; + + const selectedTopic = websitesForTopic[topic]; + + let data = []; + + if (mode === 'normal') { + const seenUrls = new Set(); + + data = ( + await Promise.all( + selectedTopic.links.flatMap((link) => + selectedTopic.query.map(async (query) => { + return ( + await searchSearxng(`site:${link} ${query}`, { + engines: ['bing news'], + pageno: 1, + language: 'en', + }) + ).results; + }), + ), + ) + ) + .flat() + .filter((item) => { + const url = item.url?.toLowerCase().trim(); + if (seenUrls.has(url)) return false; + seenUrls.add(url); + return true; + }) + .sort(() => Math.random() - 0.5); + } else { + data = ( + await searchSearxng( + `site:${selectedTopic.links[Math.floor(Math.random() * selectedTopic.links.length)]} ${selectedTopic.query[Math.floor(Math.random() * selectedTopic.query.length)]}`, + { + engines: ['bing news'], + pageno: 1, + language: 'en', + }, + ) + ).results; + } + + return Response.json( + { + blogs: data, + }, + { + status: 200, + }, + ); + } catch (err) { + console.error(`An error occurred in discover route: ${err}`); + return Response.json( + { + message: 'An error has occurred', + }, + { + status: 500, + }, + ); + } +}; diff --git a/src/app/api/images/route.ts b/src/app/api/images/route.ts new file mode 100644 index 0000000..e02854d --- /dev/null +++ b/src/app/api/images/route.ts @@ -0,0 +1,83 @@ +import handleImageSearch from '@/lib/chains/imageSearchAgent'; +import { + getCustomOpenaiApiKey, + getCustomOpenaiApiUrl, + getCustomOpenaiModelName, +} from '@/lib/config'; +import { getAvailableChatModelProviders } from '@/lib/providers'; +import { BaseChatModel } from '@langchain/core/language_models/chat_models'; +import { AIMessage, BaseMessage, HumanMessage } from '@langchain/core/messages'; +import { ChatOpenAI } from '@langchain/openai'; + +interface ChatModel { + provider: string; + model: string; +} + +interface ImageSearchBody { + query: string; + chatHistory: any[]; + chatModel?: ChatModel; +} + +export const POST = async (req: Request) => { + try { + const body: ImageSearchBody = await req.json(); + + const chatHistory = body.chatHistory + .map((msg: any) => { + if (msg.role === 'user') { + return new HumanMessage(msg.content); + } else if (msg.role === 'assistant') { + return new AIMessage(msg.content); + } + }) + .filter((msg) => msg !== undefined) as BaseMessage[]; + + const chatModelProviders = await getAvailableChatModelProviders(); + + const chatModelProvider = + chatModelProviders[ + body.chatModel?.provider || Object.keys(chatModelProviders)[0] + ]; + const chatModel = + chatModelProvider[ + body.chatModel?.model || Object.keys(chatModelProvider)[0] + ]; + + let llm: BaseChatModel | undefined; + + if (body.chatModel?.provider === 'custom_openai') { + llm = new ChatOpenAI({ + apiKey: getCustomOpenaiApiKey(), + modelName: getCustomOpenaiModelName(), + temperature: 0.7, + configuration: { + baseURL: getCustomOpenaiApiUrl(), + }, + }) as unknown as BaseChatModel; + } else if (chatModelProvider && chatModel) { + llm = chatModel.model; + } + + if (!llm) { + return Response.json({ error: 'Invalid chat model' }, { status: 400 }); + } + + const images = await handleImageSearch( + { + chat_history: chatHistory, + query: body.query, + }, + llm, + ); + + return Response.json({ images }, { status: 200 }); + } catch (err) { + console.error(`An error occurred while searching images: ${err}`); + return Response.json( + { message: 'An error occurred while searching images' }, + { status: 500 }, + ); + } +}; diff --git a/src/app/api/models/route.ts b/src/app/api/models/route.ts new file mode 100644 index 0000000..04a6949 --- /dev/null +++ b/src/app/api/models/route.ts @@ -0,0 +1,47 @@ +import { + getAvailableChatModelProviders, + getAvailableEmbeddingModelProviders, +} from '@/lib/providers'; + +export const GET = async (req: Request) => { + try { + const [chatModelProviders, embeddingModelProviders] = await Promise.all([ + getAvailableChatModelProviders(), + getAvailableEmbeddingModelProviders(), + ]); + + Object.keys(chatModelProviders).forEach((provider) => { + Object.keys(chatModelProviders[provider]).forEach((model) => { + delete (chatModelProviders[provider][model] as { model?: unknown }) + .model; + }); + }); + + Object.keys(embeddingModelProviders).forEach((provider) => { + Object.keys(embeddingModelProviders[provider]).forEach((model) => { + delete (embeddingModelProviders[provider][model] as { model?: unknown }) + .model; + }); + }); + + return Response.json( + { + chatModelProviders, + embeddingModelProviders, + }, + { + status: 200, + }, + ); + } catch (err) { + console.error('An error occurred while fetching models', err); + return Response.json( + { + message: 'An error has occurred.', + }, + { + status: 500, + }, + ); + } +}; diff --git a/src/app/api/search/route.ts b/src/app/api/search/route.ts new file mode 100644 index 0000000..5f752ec --- /dev/null +++ b/src/app/api/search/route.ts @@ -0,0 +1,269 @@ +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 { AIMessage, BaseMessage, HumanMessage } from '@langchain/core/messages'; +import { MetaSearchAgentType } from '@/lib/search/metaSearchAgent'; +import { + getCustomOpenaiApiKey, + getCustomOpenaiApiUrl, + getCustomOpenaiModelName, +} from '@/lib/config'; +import { searchHandlers } from '@/lib/search'; + +interface chatModel { + provider: string; + name: string; + customOpenAIKey?: string; + customOpenAIBaseURL?: string; +} + +interface embeddingModel { + provider: string; + name: string; +} + +interface ChatRequestBody { + optimizationMode: 'speed' | 'balanced'; + focusMode: string; + chatModel?: chatModel; + embeddingModel?: embeddingModel; + query: string; + history: Array<[string, string]>; + stream?: boolean; + systemInstructions?: string; +} + +export const POST = async (req: Request) => { + try { + const body: ChatRequestBody = await req.json(); + + if (!body.focusMode || !body.query) { + return Response.json( + { message: 'Missing focus mode or query' }, + { status: 400 }, + ); + } + + body.history = body.history || []; + body.optimizationMode = body.optimizationMode || 'balanced'; + body.stream = body.stream || false; + + const history: BaseMessage[] = body.history.map((msg) => { + return msg[0] === 'human' + ? new HumanMessage({ content: msg[1] }) + : 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?.name || + Object.keys(chatModelProviders[chatModelProvider])[0]; + + const embeddingModelProvider = + body.embeddingModel?.provider || Object.keys(embeddingModelProviders)[0]; + const embeddingModel = + body.embeddingModel?.name || + Object.keys(embeddingModelProviders[embeddingModelProvider])[0]; + + let llm: BaseChatModel | undefined; + let embeddings: Embeddings | undefined; + + if (body.chatModel?.provider === 'custom_openai') { + llm = new ChatOpenAI({ + modelName: body.chatModel?.name || getCustomOpenaiModelName(), + apiKey: body.chatModel?.customOpenAIKey || getCustomOpenaiApiKey(), + temperature: 0.7, + configuration: { + baseURL: + body.chatModel?.customOpenAIBaseURL || getCustomOpenaiApiUrl(), + }, + }) 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 Response.json( + { message: 'Invalid model selected' }, + { status: 400 }, + ); + } + + const searchHandler: MetaSearchAgentType = searchHandlers[body.focusMode]; + + if (!searchHandler) { + return Response.json({ message: 'Invalid focus mode' }, { status: 400 }); + } + + const emitter = await searchHandler.searchAndAnswer( + body.query, + history, + llm, + embeddings, + body.optimizationMode, + [], + body.systemInstructions || '', + ); + + if (!body.stream) { + return new Promise( + ( + resolve: (value: Response) => void, + reject: (value: Response) => void, + ) => { + let message = ''; + let sources: any[] = []; + + emitter.on('data', (data: string) => { + try { + const parsedData = JSON.parse(data); + if (parsedData.type === 'response') { + message += parsedData.data; + } else if (parsedData.type === 'sources') { + sources = parsedData.data; + } + } catch (error) { + reject( + Response.json( + { message: 'Error parsing data' }, + { status: 500 }, + ), + ); + } + }); + + emitter.on('end', () => { + resolve(Response.json({ message, sources }, { status: 200 })); + }); + + emitter.on('error', (error: any) => { + reject( + Response.json( + { message: 'Search error', error }, + { status: 500 }, + ), + ); + }); + }, + ); + } + + const encoder = new TextEncoder(); + + const abortController = new AbortController(); + const { signal } = abortController; + + const stream = new ReadableStream({ + start(controller) { + let sources: any[] = []; + + controller.enqueue( + encoder.encode( + JSON.stringify({ + type: 'init', + data: 'Stream connected', + }) + '\n', + ), + ); + + signal.addEventListener('abort', () => { + emitter.removeAllListeners(); + + try { + controller.close(); + } catch (error) {} + }); + + emitter.on('data', (data: string) => { + if (signal.aborted) return; + + try { + const parsedData = JSON.parse(data); + + if (parsedData.type === 'response') { + controller.enqueue( + encoder.encode( + JSON.stringify({ + type: 'response', + data: parsedData.data, + }) + '\n', + ), + ); + } else if (parsedData.type === 'sources') { + sources = parsedData.data; + controller.enqueue( + encoder.encode( + JSON.stringify({ + type: 'sources', + data: sources, + }) + '\n', + ), + ); + } + } catch (error) { + controller.error(error); + } + }); + + emitter.on('end', () => { + if (signal.aborted) return; + + controller.enqueue( + encoder.encode( + JSON.stringify({ + type: 'done', + }) + '\n', + ), + ); + controller.close(); + }); + + emitter.on('error', (error: any) => { + if (signal.aborted) return; + + controller.error(error); + }); + }, + cancel() { + abortController.abort(); + }, + }); + + return new Response(stream, { + headers: { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache, no-transform', + Connection: 'keep-alive', + }, + }); + } catch (err: any) { + console.error(`Error in getting search results: ${err.message}`); + return Response.json( + { message: 'An error has occurred.' }, + { status: 500 }, + ); + } +}; diff --git a/src/app/api/suggestions/route.ts b/src/app/api/suggestions/route.ts new file mode 100644 index 0000000..99179d2 --- /dev/null +++ b/src/app/api/suggestions/route.ts @@ -0,0 +1,81 @@ +import generateSuggestions from '@/lib/chains/suggestionGeneratorAgent'; +import { + getCustomOpenaiApiKey, + getCustomOpenaiApiUrl, + getCustomOpenaiModelName, +} from '@/lib/config'; +import { getAvailableChatModelProviders } from '@/lib/providers'; +import { BaseChatModel } from '@langchain/core/language_models/chat_models'; +import { AIMessage, BaseMessage, HumanMessage } from '@langchain/core/messages'; +import { ChatOpenAI } from '@langchain/openai'; + +interface ChatModel { + provider: string; + model: string; +} + +interface SuggestionsGenerationBody { + chatHistory: any[]; + chatModel?: ChatModel; +} + +export const POST = async (req: Request) => { + try { + const body: SuggestionsGenerationBody = await req.json(); + + const chatHistory = body.chatHistory + .map((msg: any) => { + if (msg.role === 'user') { + return new HumanMessage(msg.content); + } else if (msg.role === 'assistant') { + return new AIMessage(msg.content); + } + }) + .filter((msg) => msg !== undefined) as BaseMessage[]; + + const chatModelProviders = await getAvailableChatModelProviders(); + + const chatModelProvider = + chatModelProviders[ + body.chatModel?.provider || Object.keys(chatModelProviders)[0] + ]; + const chatModel = + chatModelProvider[ + body.chatModel?.model || Object.keys(chatModelProvider)[0] + ]; + + let llm: BaseChatModel | undefined; + + if (body.chatModel?.provider === 'custom_openai') { + llm = new ChatOpenAI({ + apiKey: getCustomOpenaiApiKey(), + modelName: getCustomOpenaiModelName(), + temperature: 0.7, + configuration: { + baseURL: getCustomOpenaiApiUrl(), + }, + }) as unknown as BaseChatModel; + } else if (chatModelProvider && chatModel) { + llm = chatModel.model; + } + + if (!llm) { + return Response.json({ error: 'Invalid chat model' }, { status: 400 }); + } + + const suggestions = await generateSuggestions( + { + chat_history: chatHistory, + }, + llm, + ); + + return Response.json({ suggestions }, { status: 200 }); + } catch (err) { + console.error(`An error occurred while generating suggestions: ${err}`); + return Response.json( + { message: 'An error occurred while generating suggestions' }, + { status: 500 }, + ); + } +}; diff --git a/src/app/api/uploads/route.ts b/src/app/api/uploads/route.ts new file mode 100644 index 0000000..9fbaf2d --- /dev/null +++ b/src/app/api/uploads/route.ts @@ -0,0 +1,134 @@ +import { NextResponse } from 'next/server'; +import fs from 'fs'; +import path from 'path'; +import crypto from 'crypto'; +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'; + +interface FileRes { + fileName: string; + fileExtension: string; + fileId: string; +} + +const uploadDir = path.join(process.cwd(), 'uploads'); + +if (!fs.existsSync(uploadDir)) { + fs.mkdirSync(uploadDir, { recursive: true }); +} + +const splitter = new RecursiveCharacterTextSplitter({ + chunkSize: 500, + chunkOverlap: 100, +}); + +export async function POST(req: Request) { + try { + const formData = await req.formData(); + + const files = formData.getAll('files') as File[]; + const embedding_model = formData.get('embedding_model'); + const embedding_model_provider = formData.get('embedding_model_provider'); + + if (!embedding_model || !embedding_model_provider) { + return NextResponse.json( + { message: 'Missing embedding model or provider' }, + { status: 400 }, + ); + } + + const embeddingModels = await getAvailableEmbeddingModelProviders(); + const provider = + embedding_model_provider ?? Object.keys(embeddingModels)[0]; + const embeddingModel = + embedding_model ?? Object.keys(embeddingModels[provider as string])[0]; + + let embeddingsModel = + embeddingModels[provider as string]?.[embeddingModel as string]?.model; + if (!embeddingsModel) { + return NextResponse.json( + { message: 'Invalid embedding model selected' }, + { status: 400 }, + ); + } + + const processedFiles: FileRes[] = []; + + await Promise.all( + files.map(async (file: any) => { + const fileExtension = file.name.split('.').pop(); + if (!['pdf', 'docx', 'txt'].includes(fileExtension!)) { + return NextResponse.json( + { message: 'File type not supported' }, + { status: 400 }, + ); + } + + const uniqueFileName = `${crypto.randomBytes(16).toString('hex')}.${fileExtension}`; + const filePath = path.join(uploadDir, uniqueFileName); + + const buffer = Buffer.from(await file.arrayBuffer()); + fs.writeFileSync(filePath, new Uint8Array(buffer)); + + let docs: any[] = []; + if (fileExtension === 'pdf') { + const loader = new PDFLoader(filePath); + docs = await loader.load(); + } else if (fileExtension === 'docx') { + const loader = new DocxLoader(filePath); + docs = await loader.load(); + } else if (fileExtension === 'txt') { + const text = fs.readFileSync(filePath, 'utf-8'); + docs = [ + new Document({ pageContent: text, metadata: { title: file.name } }), + ]; + } + + const splitted = await splitter.splitDocuments(docs); + + const extractedDataPath = filePath.replace(/\.\w+$/, '-extracted.json'); + fs.writeFileSync( + extractedDataPath, + JSON.stringify({ + title: file.name, + contents: splitted.map((doc) => doc.pageContent), + }), + ); + + const embeddings = await embeddingsModel.embedDocuments( + splitted.map((doc) => doc.pageContent), + ); + const embeddingsDataPath = filePath.replace( + /\.\w+$/, + '-embeddings.json', + ); + fs.writeFileSync( + embeddingsDataPath, + JSON.stringify({ + title: file.name, + embeddings, + }), + ); + + processedFiles.push({ + fileName: file.name, + fileExtension: fileExtension, + fileId: uniqueFileName.replace(/\.\w+$/, ''), + }); + }), + ); + + return NextResponse.json({ + files: processedFiles, + }); + } catch (error) { + console.error('Error uploading file:', error); + return NextResponse.json( + { message: 'An error has occurred.' }, + { status: 500 }, + ); + } +} diff --git a/src/app/api/videos/route.ts b/src/app/api/videos/route.ts new file mode 100644 index 0000000..7e8288b --- /dev/null +++ b/src/app/api/videos/route.ts @@ -0,0 +1,83 @@ +import handleVideoSearch from '@/lib/chains/videoSearchAgent'; +import { + getCustomOpenaiApiKey, + getCustomOpenaiApiUrl, + getCustomOpenaiModelName, +} from '@/lib/config'; +import { getAvailableChatModelProviders } from '@/lib/providers'; +import { BaseChatModel } from '@langchain/core/language_models/chat_models'; +import { AIMessage, BaseMessage, HumanMessage } from '@langchain/core/messages'; +import { ChatOpenAI } from '@langchain/openai'; + +interface ChatModel { + provider: string; + model: string; +} + +interface VideoSearchBody { + query: string; + chatHistory: any[]; + chatModel?: ChatModel; +} + +export const POST = async (req: Request) => { + try { + const body: VideoSearchBody = await req.json(); + + const chatHistory = body.chatHistory + .map((msg: any) => { + if (msg.role === 'user') { + return new HumanMessage(msg.content); + } else if (msg.role === 'assistant') { + return new AIMessage(msg.content); + } + }) + .filter((msg) => msg !== undefined) as BaseMessage[]; + + const chatModelProviders = await getAvailableChatModelProviders(); + + const chatModelProvider = + chatModelProviders[ + body.chatModel?.provider || Object.keys(chatModelProviders)[0] + ]; + const chatModel = + chatModelProvider[ + body.chatModel?.model || Object.keys(chatModelProvider)[0] + ]; + + let llm: BaseChatModel | undefined; + + if (body.chatModel?.provider === 'custom_openai') { + llm = new ChatOpenAI({ + apiKey: getCustomOpenaiApiKey(), + modelName: getCustomOpenaiModelName(), + temperature: 0.7, + configuration: { + baseURL: getCustomOpenaiApiUrl(), + }, + }) as unknown as BaseChatModel; + } else if (chatModelProvider && chatModel) { + llm = chatModel.model; + } + + if (!llm) { + return Response.json({ error: 'Invalid chat model' }, { status: 400 }); + } + + const videos = await handleVideoSearch( + { + chat_history: chatHistory, + query: body.query, + }, + llm, + ); + + return Response.json({ videos }, { status: 200 }); + } catch (err) { + console.error(`An error occurred while searching videos: ${err}`); + return Response.json( + { message: 'An error occurred while searching videos' }, + { status: 500 }, + ); + } +}; diff --git a/src/app/api/weather/route.ts b/src/app/api/weather/route.ts new file mode 100644 index 0000000..afaf8a6 --- /dev/null +++ b/src/app/api/weather/route.ts @@ -0,0 +1,174 @@ +export const POST = async (req: Request) => { + try { + const body: { + lat: number; + lng: number; + measureUnit: 'Imperial' | 'Metric'; + } = await req.json(); + + if (!body.lat || !body.lng) { + return Response.json( + { + message: 'Invalid request.', + }, + { status: 400 }, + ); + } + + const res = await fetch( + `https://api.open-meteo.com/v1/forecast?latitude=${body.lat}&longitude=${body.lng}¤t=weather_code,temperature_2m,is_day,relative_humidity_2m,wind_speed_10m&timezone=auto${ + body.measureUnit === 'Metric' ? '' : '&temperature_unit=fahrenheit' + }${body.measureUnit === 'Metric' ? '' : '&wind_speed_unit=mph'}`, + ); + + const data = await res.json(); + + if (data.error) { + console.error(`Error fetching weather data: ${data.reason}`); + return Response.json( + { + message: 'An error has occurred.', + }, + { status: 500 }, + ); + } + + const weather: { + temperature: number; + condition: string; + humidity: number; + windSpeed: number; + icon: string; + temperatureUnit: 'C' | 'F'; + windSpeedUnit: 'm/s' | 'mph'; + } = { + temperature: data.current.temperature_2m, + condition: '', + humidity: data.current.relative_humidity_2m, + windSpeed: data.current.wind_speed_10m, + icon: '', + temperatureUnit: body.measureUnit === 'Metric' ? 'C' : 'F', + windSpeedUnit: body.measureUnit === 'Metric' ? 'm/s' : 'mph', + }; + + const code = data.current.weather_code; + const isDay = data.current.is_day === 1; + const dayOrNight = isDay ? 'day' : 'night'; + + switch (code) { + case 0: + weather.icon = `clear-${dayOrNight}`; + weather.condition = 'Clear'; + break; + + case 1: + weather.condition = 'Mainly Clear'; + case 2: + weather.condition = 'Partly Cloudy'; + case 3: + weather.icon = `cloudy-1-${dayOrNight}`; + weather.condition = 'Cloudy'; + break; + + case 45: + weather.condition = 'Fog'; + case 48: + weather.icon = `fog-${dayOrNight}`; + weather.condition = 'Fog'; + break; + + case 51: + weather.condition = 'Light Drizzle'; + case 53: + weather.condition = 'Moderate Drizzle'; + case 55: + weather.icon = `rainy-1-${dayOrNight}`; + weather.condition = 'Dense Drizzle'; + break; + + case 56: + weather.condition = 'Light Freezing Drizzle'; + case 57: + weather.icon = `frost-${dayOrNight}`; + weather.condition = 'Dense Freezing Drizzle'; + break; + + case 61: + weather.condition = 'Slight Rain'; + case 63: + weather.condition = 'Moderate Rain'; + case 65: + weather.condition = 'Heavy Rain'; + weather.icon = `rainy-2-${dayOrNight}`; + break; + + case 66: + weather.condition = 'Light Freezing Rain'; + case 67: + weather.condition = 'Heavy Freezing Rain'; + weather.icon = 'rain-and-sleet-mix'; + break; + + case 71: + weather.condition = 'Slight Snow Fall'; + case 73: + weather.condition = 'Moderate Snow Fall'; + case 75: + weather.condition = 'Heavy Snow Fall'; + weather.icon = `snowy-2-${dayOrNight}`; + break; + + case 77: + weather.condition = 'Snow'; + weather.icon = `snowy-1-${dayOrNight}`; + break; + + case 80: + weather.condition = 'Slight Rain Showers'; + case 81: + weather.condition = 'Moderate Rain Showers'; + case 82: + weather.condition = 'Heavy Rain Showers'; + weather.icon = `rainy-3-${dayOrNight}`; + break; + + case 85: + weather.condition = 'Slight Snow Showers'; + case 86: + weather.condition = 'Moderate Snow Showers'; + case 87: + weather.condition = 'Heavy Snow Showers'; + weather.icon = `snowy-3-${dayOrNight}`; + break; + + case 95: + weather.condition = 'Thunderstorm'; + weather.icon = `scattered-thunderstorms-${dayOrNight}`; + break; + + case 96: + weather.condition = 'Thunderstorm with Slight Hail'; + case 99: + weather.condition = 'Thunderstorm with Heavy Hail'; + weather.icon = 'severe-thunderstorm'; + break; + + default: + weather.icon = `clear-${dayOrNight}`; + weather.condition = 'Clear'; + break; + } + + return Response.json(weather); + } catch (err) { + console.error('An error occurred while getting home widgets', err); + return Response.json( + { + message: 'An error has occurred.', + }, + { + status: 500, + }, + ); + } +}; diff --git a/src/app/c/[chatId]/page.tsx b/src/app/c/[chatId]/page.tsx new file mode 100644 index 0000000..672107a --- /dev/null +++ b/src/app/c/[chatId]/page.tsx @@ -0,0 +1,17 @@ +'use client'; + +import ChatWindow from '@/components/ChatWindow'; +import { useParams } from 'next/navigation'; +import React from 'react'; +import { ChatProvider } from '@/lib/hooks/useChat'; + +const Page = () => { + const { chatId }: { chatId: string } = useParams(); + return ( + + + + ); +}; + +export default Page; diff --git a/src/app/discover/page.tsx b/src/app/discover/page.tsx new file mode 100644 index 0000000..8e20e50 --- /dev/null +++ b/src/app/discover/page.tsx @@ -0,0 +1,158 @@ +'use client'; + +import { Search } from 'lucide-react'; +import { useEffect, useState } from 'react'; +import Link from 'next/link'; +import { toast } from 'sonner'; +import { cn } from '@/lib/utils'; + +interface Discover { + title: string; + content: string; + url: string; + thumbnail: string; +} + +const topics: { key: string; display: string }[] = [ + { + display: 'Tech & Science', + key: 'tech', + }, + { + display: 'Finance', + key: 'finance', + }, + { + display: 'Art & Culture', + key: 'art', + }, + { + display: 'Sports', + key: 'sports', + }, + { + display: 'Entertainment', + key: 'entertainment', + }, +]; + +const Page = () => { + const [discover, setDiscover] = useState(null); + const [loading, setLoading] = useState(true); + const [activeTopic, setActiveTopic] = useState(topics[0].key); + + const fetchArticles = async (topic: string) => { + setLoading(true); + try { + const res = await fetch(`/api/discover?topic=${topic}`, { + 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); + } + }; + + useEffect(() => { + fetchArticles(activeTopic); + }, [activeTopic]); + + return ( + <> +
+
+
+ +

Discover

+
+
+
+ +
+ {topics.map((t, i) => ( +
setActiveTopic(t.key)} + > + {t.display} +
+ ))} +
+ + {loading ? ( +
+ +
+ ) : ( +
+ {discover && + discover?.map((item, i) => ( + + {item.title} +
+
+ {item.title.slice(0, 100)}... +
+

+ {item.content.slice(0, 100)}... +

+
+ + ))} +
+ )} +
+ + ); +}; + +export default Page; diff --git a/ui/app/favicon.ico b/src/app/favicon.ico similarity index 100% rename from ui/app/favicon.ico rename to src/app/favicon.ico diff --git a/ui/app/globals.css b/src/app/globals.css similarity index 63% rename from ui/app/globals.css rename to src/app/globals.css index f75daca..6bdc1a8 100644 --- a/ui/app/globals.css +++ b/src/app/globals.css @@ -11,3 +11,11 @@ display: none; } } + +@media screen and (-webkit-min-device-pixel-ratio: 0) { + select, + textarea, + input { + font-size: 16px !important; + } +} diff --git a/ui/app/layout.tsx b/src/app/layout.tsx similarity index 100% rename from ui/app/layout.tsx rename to src/app/layout.tsx diff --git a/ui/app/library/layout.tsx b/src/app/library/layout.tsx similarity index 100% rename from ui/app/library/layout.tsx rename to src/app/library/layout.tsx diff --git a/ui/app/library/page.tsx b/src/app/library/page.tsx similarity index 98% rename from ui/app/library/page.tsx rename to src/app/library/page.tsx index 379596c..9c40b2b 100644 --- a/ui/app/library/page.tsx +++ b/src/app/library/page.tsx @@ -21,7 +21,7 @@ const Page = () => { const fetchChats = async () => { setLoading(true); - const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/chats`, { + const res = await fetch(`/api/chats`, { method: 'GET', headers: { 'Content-Type': 'application/json', diff --git a/src/app/manifest.ts b/src/app/manifest.ts new file mode 100644 index 0000000..792e752 --- /dev/null +++ b/src/app/manifest.ts @@ -0,0 +1,54 @@ +import type { MetadataRoute } from 'next'; + +export default function manifest(): MetadataRoute.Manifest { + return { + name: 'Perplexica - Chat with the internet', + short_name: 'Perplexica', + description: + 'Perplexica is an AI powered chatbot that is connected to the internet.', + start_url: '/', + display: 'standalone', + background_color: '#0a0a0a', + theme_color: '#0a0a0a', + screenshots: [ + { + src: '/screenshots/p1.png', + form_factor: 'wide', + sizes: '2560x1600', + }, + { + src: '/screenshots/p2.png', + form_factor: 'wide', + sizes: '2560x1600', + }, + { + src: '/screenshots/p1_small.png', + form_factor: 'narrow', + sizes: '828x1792', + }, + { + src: '/screenshots/p2_small.png', + form_factor: 'narrow', + sizes: '828x1792', + }, + ], + icons: [ + { + src: '/icon-50.png', + sizes: '50x50', + type: 'image/png' as const, + }, + { + src: '/icon-100.png', + sizes: '100x100', + type: 'image/png', + }, + { + src: '/icon.png', + sizes: '440x440', + type: 'image/png', + purpose: 'any', + }, + ], + }; +} diff --git a/ui/app/page.tsx b/src/app/page.tsx similarity index 74% rename from ui/app/page.tsx rename to src/app/page.tsx index e18aca9..25981b5 100644 --- a/ui/app/page.tsx +++ b/src/app/page.tsx @@ -1,4 +1,5 @@ import ChatWindow from '@/components/ChatWindow'; +import { ChatProvider } from '@/lib/hooks/useChat'; import { Metadata } from 'next'; import { Suspense } from 'react'; @@ -11,7 +12,9 @@ const Home = () => { return (
- + + +
); diff --git a/src/app/settings/page.tsx b/src/app/settings/page.tsx new file mode 100644 index 0000000..6fb8255 --- /dev/null +++ b/src/app/settings/page.tsx @@ -0,0 +1,963 @@ +'use client'; + +import { Settings as SettingsIcon, ArrowLeft, Loader2 } from 'lucide-react'; +import { useEffect, useState } from 'react'; +import { cn } from '@/lib/utils'; +import { Switch } from '@headlessui/react'; +import ThemeSwitcher from '@/components/theme/Switcher'; +import { ImagesIcon, VideoIcon } from 'lucide-react'; +import Link from 'next/link'; +import { PROVIDER_METADATA } from '@/lib/providers'; + +interface SettingsType { + chatModelProviders: { + [key: string]: [Record]; + }; + embeddingModelProviders: { + [key: string]: [Record]; + }; + openaiApiKey: string; + groqApiKey: string; + anthropicApiKey: string; + geminiApiKey: string; + ollamaApiUrl: string; + ollamaApiKey: string; + lmStudioApiUrl: string; + deepseekApiKey: string; + aimlApiKey: string; + customOpenaiApiKey: string; + customOpenaiApiUrl: string; + customOpenaiModelName: string; +} + +interface InputProps extends React.InputHTMLAttributes { + isSaving?: boolean; + onSave?: (value: string) => void; +} + +const Input = ({ className, isSaving, onSave, ...restProps }: InputProps) => { + return ( +
+ onSave?.(e.target.value)} + /> + {isSaving && ( +
+ +
+ )} +
+ ); +}; + +interface TextareaProps extends React.InputHTMLAttributes { + isSaving?: boolean; + onSave?: (value: string) => void; +} + +const Textarea = ({ + className, + isSaving, + onSave, + ...restProps +}: TextareaProps) => { + return ( +
+