Compare commits

..

8 Commits

35 changed files with 609 additions and 427 deletions

View File

@ -10,6 +10,9 @@ on:
jobs:
build-and-push:
runs-on: ubuntu-latest
strategy:
matrix:
service: [backend, app]
steps:
- name: Checkout code
uses: actions/checkout@v3
@ -33,24 +36,38 @@ jobs:
id: version
run: echo "RELEASE_VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV
- name: Build and push Docker image (latest)
- name: Build and push Docker image for ${{ matrix.service }}
if: github.ref == 'refs/heads/master' && github.event_name == 'push'
run: |
docker buildx create --use
docker buildx build --platform linux/amd64,linux/arm64,linux/arm/v7 \
--cache-from=type=registry,ref=itzcrazykns1337/perplexica:latest \
if [[ "${{ matrix.service }}" == "backend" ]]; then \
DOCKERFILE=backend.dockerfile; \
IMAGE_NAME=perplexica-backend; \
else \
DOCKERFILE=app.dockerfile; \
IMAGE_NAME=perplexica-frontend; \
fi
docker buildx build --platform linux/amd64,linux/arm64 \
--cache-from=type=registry,ref=itzcrazykns1337/${IMAGE_NAME}:main \
--cache-to=type=inline \
-f docker/Dockerfile \
-t itzcrazykns1337/perplexica:latest \
-f $DOCKERFILE \
-t itzcrazykns1337/${IMAGE_NAME}:main \
--push .
- name: Build and push Docker image (release)
- name: Build and push release Docker image for ${{ matrix.service }}
if: github.event_name == 'release'
run: |
docker buildx create --use
docker buildx build --platform linux/amd64,linux/arm64,linux/arm/v7 \
--cache-from=type=registry,ref=itzcrazykns1337/perplexica:${{ env.RELEASE_VERSION }} \
if [[ "${{ matrix.service }}" == "backend" ]]; then \
DOCKERFILE=backend.dockerfile; \
IMAGE_NAME=perplexica-backend; \
else \
DOCKERFILE=app.dockerfile; \
IMAGE_NAME=perplexica-frontend; \
fi
docker buildx build --platform linux/amd64,linux/arm64 \
--cache-from=type=registry,ref=itzcrazykns1337/${IMAGE_NAME}:${{ env.RELEASE_VERSION }} \
--cache-to=type=inline \
-f docker/Dockerfile \
-t itzcrazykns1337/perplexica:${{ env.RELEASE_VERSION }} \
-f $DOCKERFILE \
-t itzcrazykns1337/${IMAGE_NAME}:${{ env.RELEASE_VERSION }} \
--push .

View File

@ -26,13 +26,12 @@
- [Preview](#preview)
- [Features](#features)
- [Installation](#installation)
- [Docker Installation (Recommended)](#docker-installation-recommended)
- [Getting Started with Docker (Recommended)](#getting-started-with-docker-recommended)
- [Non-Docker Installation](#non-docker-installation)
- [Nginx Reverse Proxy](#nginx-reverse-proxy)
- [Ollama Connection Errors](#ollama-connection-errors)
- [Using as a Search Engine](#using-as-a-search-engine)
- [Using Perplexica's API](#using-perplexicas-api)
- [Expose Perplexica to a Network](#expose-perplexica-to-a-network)
- [Expose Perplexica to a network](#expose-perplexica-to-network)
- [One-Click Deployment](#one-click-deployment)
- [Upcoming Features](#upcoming-features)
- [Support Us](#support-us)
@ -72,9 +71,9 @@ It has many more features like image and video search. Some of the planned featu
## Installation
Perplexica can be installed using Docker (recommended) or directly on your system.
There are mainly 2 ways of installing Perplexica - With Docker, Without Docker. Using Docker is highly recommended.
### Docker Installation (Recommended)
### Getting Started with Docker (Recommended)
1. Ensure Docker is installed and running on your system.
2. Clone the Perplexica repository:
@ -102,15 +101,10 @@ Perplexica can be installed using Docker (recommended) or directly on your syste
docker compose up -d
```
6. Wait a few minutes for the setup to complete. You can access Perplexica at http://localhost:8080 in your web browser.
6. Wait a few minutes for the setup to complete. You can access Perplexica at http://localhost:3000 in your web browser.
**Note**: After the containers are built, you can start Perplexica directly from Docker without having to open a terminal.
The Docker configuration is located in the `docker/` directory, containing:
- Dockerfile with multi-stage build for efficient images
- Service configurations for the integrated process manager
- Nginx reverse proxy configuration
### Non-Docker Installation
1. Install SearXNG and allow `JSON` format in the SearXNG settings.
@ -124,17 +118,6 @@ The Docker configuration is located in the `docker/` directory, containing:
See the [installation documentation](https://github.com/ItzCrazyKns/Perplexica/tree/master/docs/installation) for more information like exposing it your network, etc.
### Nginx Reverse Proxy
Perplexica includes an Nginx reverse proxy that provides several key benefits:
- **Single Port Access**: Access both frontend and backend through a single port (8080)
- **Dynamic Configuration**: Works with any domain or IP without rebuilding
- **WebSocket Support**: Automatic WebSocket URL configuration based on the current domain
- **Security Headers**: Enhanced security with proper HTTP headers
When using Docker, the reverse proxy is automatically configured. Access Perplexica at `http://localhost:8080` or `http://your-ip:8080` after starting the containers.
### Ollama Connection Errors
If you're encountering an Ollama connection error, it is likely due to the backend being unable to connect to Ollama's API. To fix this issue you can:
@ -160,7 +143,7 @@ If you wish to use Perplexica as an alternative to traditional search engines li
1. Open your browser's settings.
2. Navigate to the 'Search Engines' section.
3. Add a new site search with the following URL: `http://localhost:8080/?q=%s`. Replace `localhost` with your IP address or domain name if needed.
3. Add a new site search with the following URL: `http://localhost:3000/?q=%s`. Replace `localhost` with your IP address or domain name, and `3000` with the port number if Perplexica is not hosted locally.
4. Click the add button. Now, you can use Perplexica directly from your browser's search bar.
## Using Perplexica's API
@ -169,15 +152,9 @@ Perplexica also provides an API for developers looking to integrate its powerful
For more details, check out the full documentation [here](https://github.com/ItzCrazyKns/Perplexica/tree/master/docs/API/SEARCH.md).
## Expose Perplexica to a Network
## Expose Perplexica to network
Perplexica can be easily accessed over your home network or exposed to the internet through the Nginx reverse proxy. With this setup:
1. **Local Network Access**: Access Perplexica from any device on your network using `http://server-ip:8080`
2. **Domain Configuration**: If you have a domain name, point it to your server and access Perplexica with `http://your-domain.com:8080`
3. **SSL Support**: Configure SSL certificates in Nginx for secure `https://` access
For more network configuration details, see our [networking guide](https://github.com/ItzCrazyKns/Perplexica/blob/master/docs/installation/NETWORKING.md).
You can access Perplexica over your home network by following our networking guide [here](https://github.com/ItzCrazyKns/Perplexica/blob/master/docs/installation/NETWORKING.md).
## One-Click Deployment

15
app.dockerfile Normal file
View File

@ -0,0 +1,15 @@
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}
WORKDIR /home/perplexica
COPY ui /home/perplexica/
RUN yarn install --frozen-lockfile
RUN yarn build
CMD ["yarn", "start"]

17
backend.dockerfile Normal file
View File

@ -0,0 +1,17 @@
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"]

View File

@ -2,43 +2,49 @@ services:
searxng:
image: docker.io/searxng/searxng:latest
volumes:
- ./searxng:/etc/searxng
- ./searxng:/etc/searxng:rw
ports:
- 4000:8080
networks:
- perplexica-network
restart: unless-stopped
perplexica:
image: itzcrazykns1337/perplexica:latest
ports:
- "8080:8080"
perplexica-backend:
build:
context: .
dockerfile: backend.dockerfile
image: itzcrazykns1337/perplexica-backend:main
environment:
- SEARXNG_API_URL=http://searxng:4000
- SIMILARITY_MEASURE=cosine
- KEEP_ALIVE=5m
- OPENAI_API_KEY=${OPENAI_API_KEY:-}
- GROQ_API_KEY=${GROQ_API_KEY:-}
- ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY:-}
- GEMINI_API_KEY=${GEMINI_API_KEY:-}
- OLLAMA_API_URL=${OLLAMA_API_URL:-}
- CUSTOM_OPENAI_API_KEY=${CUSTOM_OPENAI_API_KEY:-}
- CUSTOM_OPENAI_API_URL=${CUSTOM_OPENAI_API_URL:-}
- CUSTOM_OPENAI_MODEL_NAME=${CUSTOM_OPENAI_MODEL_NAME:-}
volumes:
- backend-dbstore:/app/backend/data
- uploads:/app/backend/uploads
extra_hosts:
- 'host.docker.internal:host-gateway'
- 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:
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
ports:
- 3000:3000
networks:
- perplexica-network
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/"]
interval: 30s
timeout: 10s
retries: 3
start_period: 5s
networks:
perplexica-network:

View File

@ -1,93 +0,0 @@
# Multi-stage build for Perplexica
# Stage 1: Build the backend
FROM node:lts-alpine as backend-builder
WORKDIR /app
COPY src ./src
COPY tsconfig.json drizzle.config.ts package.json yarn.lock ./
RUN yarn install --frozen-lockfile --network-timeout 600000 && \
yarn build
# Stage 2: Build the frontend
FROM node:lts-alpine as frontend-builder
WORKDIR /app
COPY ui ./
ARG NEXT_PUBLIC_API_URL=/api
ARG NEXT_PUBLIC_WS_URL=auto
ENV NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL}
ENV NEXT_PUBLIC_WS_URL=${NEXT_PUBLIC_WS_URL}
RUN yarn install --frozen-lockfile && \
yarn build
# Stage 3: Final image
FROM node:lts-alpine
# Install curl and jq for GitHub API access
RUN apk add --no-cache curl jq
# Determine latest S6 overlay version at build time
RUN S6_OVERLAY_VERSION=$(curl -s https://api.github.com/repos/just-containers/s6-overlay/releases/latest | jq -r .tag_name | sed 's/^v//') && \
echo "Using S6 overlay version: $S6_OVERLAY_VERSION" && \
echo "$S6_OVERLAY_VERSION" > /tmp/s6-version
# Use Docker's TARGETARCH for automatic architecture detection
ARG TARGETARCH
# Install additional required packages and create directory structure in one layer
RUN apk add --no-cache \
nginx \
tzdata \
bash && \
mkdir -p /app/backend /app/frontend /app/data /app/uploads
# Map Docker's architecture names to s6-overlay architecture names and download/install
RUN S6_OVERLAY_VERSION=$(cat /tmp/s6-version) && \
case "${TARGETARCH}" in \
"amd64") S6_OVERLAY_ARCH="x86_64" ;; \
"arm64") S6_OVERLAY_ARCH="aarch64" ;; \
"arm") S6_OVERLAY_ARCH="arm" ;; \
*) echo "Unsupported architecture: ${TARGETARCH}. Only amd64, arm64, and arm are supported." && exit 1 ;; \
esac && \
echo "Target architecture: ${TARGETARCH} -> S6 architecture: ${S6_OVERLAY_ARCH}" && \
echo "Downloading s6-overlay v${S6_OVERLAY_VERSION} for architecture: ${S6_OVERLAY_ARCH}" && \
curl -L -s -o /tmp/s6-overlay-noarch.tar.xz "https://github.com/just-containers/s6-overlay/releases/download/v${S6_OVERLAY_VERSION}/s6-overlay-noarch.tar.xz" && \
tar -C / -Jxpf /tmp/s6-overlay-noarch.tar.xz && \
curl -L -s -o /tmp/s6-overlay-arch.tar.xz "https://github.com/just-containers/s6-overlay/releases/download/v${S6_OVERLAY_VERSION}/s6-overlay-${S6_OVERLAY_ARCH}.tar.xz" && \
tar -C / -Jxpf /tmp/s6-overlay-arch.tar.xz && \
curl -L -s -o /tmp/s6-overlay-symlinks-noarch.tar.xz "https://github.com/just-containers/s6-overlay/releases/download/v${S6_OVERLAY_VERSION}/s6-overlay-symlinks-noarch.tar.xz" && \
tar -C / -Jxpf /tmp/s6-overlay-symlinks-noarch.tar.xz && \
rm -f /tmp/s6-overlay-*.tar.xz /tmp/s6-version
# Copy configuration files
COPY docker/etc/s6-overlay/services /etc/services.d/
COPY docker/etc/nginx/nginx.conf /etc/nginx/nginx.conf
# Make service scripts executable
RUN chmod +x /etc/services.d/*/run /etc/services.d/*/finish
# Copy application files from builders
COPY --from=backend-builder /app/dist /app/backend/dist
COPY --from=backend-builder /app/node_modules /app/backend/node_modules
COPY --from=backend-builder /app/package.json /app/backend/package.json
COPY --from=backend-builder /app/drizzle.config.ts /app/backend/drizzle.config.ts
# Copy only the schema file for Drizzle migrations
COPY --from=backend-builder /app/src/db/schema.ts /app/backend/src/db/schema.ts
COPY --from=frontend-builder /app/.next /app/frontend/.next
COPY --from=frontend-builder /app/node_modules /app/frontend/node_modules
COPY --from=frontend-builder /app/package.json /app/frontend/package.json
COPY --from=frontend-builder /app/public /app/frontend/public
# Configure volumes and ports
VOLUME ["/app/backend/data", "/app/backend/uploads"]
EXPOSE 8080
# Set up healthcheck
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8080/ || exit 1
ENTRYPOINT ["/init"]

View File

@ -1,55 +0,0 @@
events {
worker_connections 1024;
}
http {
port_in_redirect on;
absolute_redirect off;
server {
listen 8080;
server_name localhost;
# Global timeout settings for all locations
proxy_read_timeout 86400s; # 24 hours
proxy_send_timeout 86400s; # 24 hours
proxy_connect_timeout 60s; # Connection establishment timeout
# API requests
location /api {
proxy_pass http://localhost:3001;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# WebSocket requests
location /ws {
proxy_pass http://localhost:3001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# Frontend requests
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# Security headers
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
server_tokens off;
}
}

View File

@ -1,3 +0,0 @@
#!/usr/bin/with-contenv bash
s6-svc -d /var/run/s6/services/frontend
s6-svc -d /var/run/s6/services/nginx

View File

@ -1,8 +0,0 @@
#!/usr/bin/with-contenv bash
cd /app/backend
# Run database migrations before starting the app
yarn db:push
# Start the application
exec node dist/app.js

View File

@ -1,2 +0,0 @@
#!/usr/bin/with-contenv bash
s6-svc -d /var/run/s6/services/nginx

View File

@ -1,3 +0,0 @@
#!/usr/bin/with-contenv bash
cd /app/frontend
exec node_modules/.bin/next start

View File

@ -1,2 +0,0 @@
#!/usr/bin/with-contenv bash
exec nginx -g "daemon off;"

View File

@ -1,46 +1,109 @@
# Accessing Perplexica over a Network
# Expose Perplexica to a network
This guide explains how to access Perplexica over your network using the nginx reverse proxy included in the Docker setup.
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.
## Basic Network Access
## Windows
Perplexica is automatically accessible from any device on your network:
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:
1. Start Perplexica using Docker Compose:
```bash
docker compose up -d
docker compose down --rmi all
```
2. Find your server's IP address:
- **Windows**: `ipconfig` in Command Prompt
- **macOS**: `ifconfig | grep "inet "` in Terminal
- **Linux**: `ip addr show | grep "inet "` in Terminal
4. Open the `docker-compose.yaml` file in a text editor like Notepad++
3. Access Perplexica from any device on your network:
```
http://YOUR_SERVER_IP:8080
```
5. Replace `127.0.0.1` with the IP address of the server Perplexica is running on in these two lines:
## Custom Port Configuration
If you need to use a different port instead of the default 8080:
1. Modify the `docker-compose.yaml` file:
```yaml
perplexica:
ports:
- "YOUR_CUSTOM_PORT:8080"
```
2. Restart the containers:
```bash
docker compose down && docker compose up -d
args:
- NEXT_PUBLIC_API_URL=http://127.0.0.1:3001/api
- NEXT_PUBLIC_WS_URL=ws://127.0.0.1:3001
```
## Troubleshooting
6. Save and close the `docker-compose.yaml` file
If you encounter issues accessing Perplexica over your network:
7. Rebuild and restart the Perplexica container:
1. **Firewall Settings**: Ensure port 8080 (or your custom port) is allowed in your firewall
2. **Docker Logs**: Check for any connection issues with `docker logs perplexica`
3. **Network Access**: Make sure your devices are on the same network and can reach the server
```bash
docker compose up -d --build
```
## macOS
1. Open the Terminal application
2. Navigate to the directory with the `docker-compose.yaml` file:
```bash
cd /path/to/docker-compose.yaml
```
3. Stop and remove existing containers and images:
```bash
docker compose down --rmi all
```
4. Open `docker-compose.yaml` in a text editor like Sublime Text:
```bash
nano docker-compose.yaml
```
5. Replace `127.0.0.1` with the server IP in these lines:
```bash
args:
- NEXT_PUBLIC_API_URL=http://127.0.0.1:3001/api
- NEXT_PUBLIC_WS_URL=ws://127.0.0.1:3001
```
6. Save and exit the editor
7. Rebuild and restart Perplexica:
```bash
docker compose up -d --build
```
## Linux
1. Open the terminal
2. Navigate to the `docker-compose.yaml` directory:
```bash
cd /path/to/docker-compose.yaml
```
3. Stop and remove containers and images:
```bash
docker compose down --rmi all
```
4. Edit `docker-compose.yaml`:
```bash
nano docker-compose.yaml
```
5. Replace `127.0.0.1` with the server IP:
```bash
args:
- NEXT_PUBLIC_API_URL=http://127.0.0.1:3001/api
- NEXT_PUBLIC_WS_URL=ws://127.0.0.1:3001
```
6. Save and exit the editor
7. Rebuild and restart Perplexica:
```bash
docker compose up -d --build
```

View File

@ -1,6 +1,10 @@
[GENERAL]
PORT = 3001 # Port to run the server on
SIMILARITY_MEASURE = "cosine" # "cosine" or "dot"
CONFIG_PASSWORD = "lorem_ipsum" # Password to access config
DISCOVER_ENABLED = true
LIBRARY_ENABLED = true
COPILOT_ENABLED = true
KEEP_ALIVE = "5m" # How long to keep Ollama models loaded into memory. (Instead of using -1 use "-1m")
[MODELS.OPENAI]
@ -18,6 +22,7 @@ API_KEY = ""
[MODELS.CUSTOM_OPENAI]
API_KEY = ""
API_URL = ""
MODEL_NAME = ""
[MODELS.OLLAMA]
API_URL = "" # Ollama API URL - http://host.docker.internal:11434

View File

@ -8,6 +8,10 @@ interface Config {
GENERAL: {
PORT: number;
SIMILARITY_MEASURE: string;
CONFIG_PASSWORD: string;
DISCOVER_ENABLED: boolean;
LIBRARY_ENABLED: boolean;
COPILOT_ENABLED: boolean;
KEEP_ALIVE: string;
};
MODELS: {
@ -41,83 +45,47 @@ type RecursivePartial<T> = {
[P in keyof T]?: RecursivePartial<T[P]>;
};
const loadConfig = () => {
try {
return toml.parse(
fs.readFileSync(path.join(__dirname, `../${configFileName}`), 'utf-8'),
) as any as Config;
} catch (error) {
// Return default config if file doesn't exist
return {
GENERAL: {
PORT: 3001,
SIMILARITY_MEASURE: 'cosine',
KEEP_ALIVE: '5m',
},
MODELS: {
OPENAI: {
API_KEY: '',
},
GROQ: {
API_KEY: '',
},
ANTHROPIC: {
API_KEY: '',
},
GEMINI: {
API_KEY: '',
},
OLLAMA: {
API_URL: '',
},
CUSTOM_OPENAI: {
API_URL: '',
API_KEY: '',
MODEL_NAME: '',
},
},
API_ENDPOINTS: {
SEARXNG: '',
},
};
}
};
const loadConfig = () =>
toml.parse(
fs.readFileSync(path.join(__dirname, `../${configFileName}`), 'utf-8'),
) as any as Config;
export const getPort = () =>
process.env.PORT ? parseInt(process.env.PORT, 10) : loadConfig().GENERAL.PORT;
export const getPort = () => loadConfig().GENERAL.PORT;
export const getSimilarityMeasure = () =>
process.env.SIMILARITY_MEASURE || loadConfig().GENERAL.SIMILARITY_MEASURE;
loadConfig().GENERAL.SIMILARITY_MEASURE;
export const getKeepAlive = () =>
process.env.KEEP_ALIVE || loadConfig().GENERAL.KEEP_ALIVE;
export const getConfigPassword = () => loadConfig().GENERAL.CONFIG_PASSWORD;
export const getOpenaiApiKey = () =>
process.env.OPENAI_API_KEY || loadConfig().MODELS.OPENAI.API_KEY;
export const isDiscoverEnabled = () => loadConfig().GENERAL.DISCOVER_ENABLED;
export const getGroqApiKey = () =>
process.env.GROQ_API_KEY || loadConfig().MODELS.GROQ.API_KEY;
export const isLibraryEnabled = () => loadConfig().GENERAL.LIBRARY_ENABLED;
export const getAnthropicApiKey = () =>
process.env.ANTHROPIC_API_KEY || loadConfig().MODELS.ANTHROPIC.API_KEY;
export const isCopilotEnabled = () => loadConfig().GENERAL.COPILOT_ENABLED;
export const getGeminiApiKey = () =>
process.env.GEMINI_API_KEY || loadConfig().MODELS.GEMINI.API_KEY;
export const getKeepAlive = () => loadConfig().GENERAL.KEEP_ALIVE;
export const getOpenaiApiKey = () => loadConfig().MODELS.OPENAI.API_KEY;
export const getGroqApiKey = () => loadConfig().MODELS.GROQ.API_KEY;
export const getAnthropicApiKey = () => loadConfig().MODELS.ANTHROPIC.API_KEY;
export const getGeminiApiKey = () => loadConfig().MODELS.GEMINI.API_KEY;
export const getSearxngApiEndpoint = () =>
process.env.SEARXNG_API_URL || loadConfig().API_ENDPOINTS.SEARXNG;
export const getOllamaApiEndpoint = () =>
process.env.OLLAMA_API_URL || loadConfig().MODELS.OLLAMA.API_URL;
export const getOllamaApiEndpoint = () => loadConfig().MODELS.OLLAMA.API_URL;
export const getCustomOpenaiApiKey = () =>
process.env.CUSTOM_OPENAI_API_KEY || loadConfig().MODELS.CUSTOM_OPENAI.API_KEY;
loadConfig().MODELS.CUSTOM_OPENAI.API_KEY;
export const getCustomOpenaiApiUrl = () =>
process.env.CUSTOM_OPENAI_API_URL || loadConfig().MODELS.CUSTOM_OPENAI.API_URL;
loadConfig().MODELS.CUSTOM_OPENAI.API_URL;
export const getCustomOpenaiModelName = () =>
process.env.CUSTOM_OPENAI_MODEL_NAME || loadConfig().MODELS.CUSTOM_OPENAI.MODEL_NAME;
loadConfig().MODELS.CUSTOM_OPENAI.MODEL_NAME;
const mergeConfigs = (current: any, update: any): any => {
if (update === null || update === undefined) {

View File

@ -10,6 +10,10 @@ import {
getGeminiApiKey,
getOpenaiApiKey,
updateConfig,
getConfigPassword,
isLibraryEnabled,
isCopilotEnabled,
isDiscoverEnabled,
getCustomOpenaiApiUrl,
getCustomOpenaiApiKey,
getCustomOpenaiModelName,
@ -18,8 +22,16 @@ import logger from '../utils/logger';
const router = express.Router();
router.get('/', async (_, res) => {
router.get('/', async (req, res) => {
try {
const authHeader = req.headers['authorization']?.split(' ')[1];
const password = getConfigPassword();
if (authHeader !== password) {
res.status(401).json({ message: 'Unauthorized' });
return;
}
const config = {};
const [chatModelProviders, embeddingModelProviders] = await Promise.all([
@ -69,9 +81,22 @@ router.get('/', async (_, res) => {
});
router.post('/', async (req, res) => {
const authHeader = req.headers['authorization']?.split(' ')[1];
const password = getConfigPassword();
if (authHeader !== password) {
res.status(401).json({ message: 'Unauthorized' });
return;
}
const config = req.body;
const updatedConfig = {
GENERAL: {
DISCOVER_ENABLED: config.isDiscoverEnabled,
LIBRARY_ENABLED: config.isLibraryEnabled,
COPILOT_ENABLED: config.isCopilotEnabled,
},
MODELS: {
OPENAI: {
API_KEY: config.openaiApiKey,
@ -101,4 +126,14 @@ router.post('/', async (req, res) => {
res.status(200).json({ message: 'Config updated' });
});
router.get('/preferences', (_, res) => {
const preferences = {
isLibraryEnabled: isLibraryEnabled(),
isCopilotEnabled: isCopilotEnabled(),
isDiscoverEnabled: isDiscoverEnabled(),
};
res.status(200).json(preferences);
});
export default router;

View File

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

View File

@ -5,8 +5,9 @@ import type { Embeddings } from '@langchain/core/embeddings';
import logger from '../utils/logger';
import db from '../db';
import { chats, messages as messagesSchema } from '../db/schema';
import { eq, asc, gt, and } from 'drizzle-orm';
import { eq, gt, and } from 'drizzle-orm';
import crypto from 'crypto';
import { isLibraryEnabled } from '../config';
import { getFileDetails } from '../utils/files';
import MetaSearchAgent, {
MetaSearchAgentType,
@ -94,6 +95,8 @@ const handleEmitterEvents = (
let recievedMessage = '';
let sources = [];
const libraryEnabled = isLibraryEnabled();
emitter.on('data', (data) => {
const parsedData = JSON.parse(data);
if (parsedData.type === 'response') {
@ -119,18 +122,20 @@ const handleEmitterEvents = (
emitter.on('end', () => {
ws.send(JSON.stringify({ type: 'messageEnd', messageId: messageId }));
db.insert(messagesSchema)
.values({
content: recievedMessage,
chatId: chatId,
messageId: messageId,
role: 'assistant',
metadata: JSON.stringify({
createdAt: new Date(),
...(sources && sources.length > 0 && { sources }),
}),
})
.execute();
if (libraryEnabled) {
db.insert(messagesSchema)
.values({
content: recievedMessage,
chatId: chatId,
messageId: messageId,
role: 'assistant',
metadata: JSON.stringify({
createdAt: new Date(),
...(sources && sources.length > 0 && { sources }),
}),
})
.execute();
}
});
emitter.on('error', (data) => {
const parsedData = JSON.parse(data);
@ -188,6 +193,8 @@ export const handleMessage = async (
const handler: MetaSearchAgentType =
searchHandlers[parsedWSMessage.focusMode];
const libraryEnabled = isLibraryEnabled();
if (handler) {
try {
const emitter = await handler.searchAndAnswer(
@ -201,50 +208,52 @@ export const handleMessage = async (
handleEmitterEvents(emitter, ws, aiMessageId, parsedMessage.chatId);
const chat = await db.query.chats.findFirst({
where: eq(chats.id, parsedMessage.chatId),
});
if (libraryEnabled) {
const chat = await db.query.chats.findFirst({
where: eq(chats.id, parsedMessage.chatId),
});
if (!chat) {
await db
.insert(chats)
.values({
id: parsedMessage.chatId,
title: parsedMessage.content,
createdAt: new Date().toString(),
focusMode: parsedWSMessage.focusMode,
files: parsedWSMessage.files.map(getFileDetails),
})
.execute();
}
if (!chat) {
await db
.insert(chats)
.values({
id: parsedMessage.chatId,
title: parsedMessage.content,
createdAt: new Date().toString(),
focusMode: parsedWSMessage.focusMode,
files: parsedWSMessage.files.map(getFileDetails),
})
.execute();
}
const messageExists = await db.query.messages.findFirst({
where: eq(messagesSchema.messageId, humanMessageId),
});
const messageExists = await db.query.messages.findFirst({
where: eq(messagesSchema.messageId, humanMessageId),
});
if (!messageExists) {
await db
.insert(messagesSchema)
.values({
content: parsedMessage.content,
chatId: parsedMessage.chatId,
messageId: humanMessageId,
role: 'user',
metadata: JSON.stringify({
createdAt: new Date(),
}),
})
.execute();
} else {
await db
.delete(messagesSchema)
.where(
and(
gt(messagesSchema.id, messageExists.id),
eq(messagesSchema.chatId, parsedMessage.chatId),
),
)
.execute();
if (!messageExists) {
await db
.insert(messagesSchema)
.values({
content: parsedMessage.content,
chatId: parsedMessage.chatId,
messageId: humanMessageId,
role: 'user',
metadata: JSON.stringify({
createdAt: new Date(),
}),
})
.execute();
} else {
await db
.delete(messagesSchema)
.where(
and(
gt(messagesSchema.id, messageExists.id),
eq(messagesSchema.chatId, parsedMessage.chatId),
),
)
.execute();
}
}
} catch (err) {
console.log(err);

View File

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

View File

@ -1,8 +1,9 @@
'use client';
import DeleteChat from '@/components/DeleteChat';
import { cn, formatTimeDifference } from '@/lib/utils';
import { BookOpenText, ClockIcon, Delete, ScanEye } from 'lucide-react';
import { formatTimeDifference } from '@/lib/utils';
import { cn } from '@/lib/utils';
import { BookOpenText, ClockIcon } from 'lucide-react';
import Link from 'next/link';
import { useEffect, useState } from 'react';

View File

@ -113,12 +113,90 @@ const Page = () => {
const [automaticVideoSearch, setAutomaticVideoSearch] = useState(false);
const [savingStates, setSavingStates] = useState<Record<string, boolean>>({});
const [password, setPassword] = useState('');
const [passwordSubmitted, setPasswordSubmitted] = useState(false);
const [isPasswordValid, setIsPasswordValid] = useState(true);
const handlePasswordSubmit = async () => {
setIsLoading(true);
setPasswordSubmitted(true);
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/config`, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${password}`,
},
});
if (res.status === 401) {
setIsPasswordValid(false);
setPasswordSubmitted(false);
setIsLoading(false);
return;
} else {
setIsPasswordValid(true);
}
const data = (await res.json()) as SettingsType;
setConfig(data);
const chatModelProvidersKeys = Object.keys(data.chatModelProviders || {});
const embeddingModelProvidersKeys = Object.keys(
data.embeddingModelProviders || {},
);
const defaultChatModelProvider =
chatModelProvidersKeys.length > 0 ? chatModelProvidersKeys[0] : '';
const defaultEmbeddingModelProvider =
embeddingModelProvidersKeys.length > 0
? embeddingModelProvidersKeys[0]
: '';
const chatModelProvider =
localStorage.getItem('chatModelProvider') ||
defaultChatModelProvider ||
'';
const chatModel =
localStorage.getItem('chatModel') ||
(data.chatModelProviders &&
data.chatModelProviders[chatModelProvider]?.length > 0
? data.chatModelProviders[chatModelProvider][0].name
: undefined) ||
'';
const embeddingModelProvider =
localStorage.getItem('embeddingModelProvider') ||
defaultEmbeddingModelProvider ||
'';
const embeddingModel =
localStorage.getItem('embeddingModel') ||
(data.embeddingModelProviders &&
data.embeddingModelProviders[embeddingModelProvider]?.[0].name) ||
'';
setSelectedChatModelProvider(chatModelProvider);
setSelectedChatModel(chatModel);
setSelectedEmbeddingModelProvider(embeddingModelProvider);
setSelectedEmbeddingModel(embeddingModel);
setChatModels(data.chatModelProviders || {});
setEmbeddingModels(data.embeddingModelProviders || {});
setAutomaticImageSearch(
localStorage.getItem('autoImageSearch') === 'true',
);
setAutomaticVideoSearch(
localStorage.getItem('autoVideoSearch') === 'true',
);
setIsLoading(false);
};
useEffect(() => {
const fetchConfig = async () => {
setIsLoading(true);
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/config`, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${password}`,
},
});
@ -193,11 +271,16 @@ const Page = () => {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${password}`,
},
body: JSON.stringify(updatedConfig),
},
);
if (response.status === 401) {
throw new Error('Unauthorized');
}
if (!response.ok) {
throw new Error('Failed to update config');
}
@ -211,6 +294,7 @@ const Page = () => {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/config`, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${password}`,
},
});
@ -376,6 +460,33 @@ const Page = () => {
/>
</svg>
</div>
) : !passwordSubmitted ? (
<div className="flex flex-col max-w-md mx-auto mt-10 p-6 bg-light-secondary dark:bg-dark-secondary border border-light-200 dark:border-dark-200 rounded-2xl">
<h2 className="text-sm text-black/80 dark:text-white/80">
Enter the password to access the settings
</h2>
<div className="flex flex-col">
<Input
type="password"
placeholder="Password"
className="mt-4"
disabled={isLoading}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
{!isPasswordValid && (
<p className="text-xs text-red-500 mt-2">
Password is incorrect
</p>
)}
<button
onClick={handlePasswordSubmit}
disabled={isLoading}
className="bg-[#24A0ED] flex flex-row items-center text-xs mt-4 text-white disabled:text-white/50 hover:bg-opacity-85 transition duration-100 disabled:bg-[#ececec21] rounded-full px-4 py-2"
>
Submit
</button>
</div>
) : (
config && (
<div className="flex flex-col space-y-6 pb-28 lg:pb-8">

View File

@ -368,7 +368,7 @@ const loadMessages = async (
const ChatWindow = ({ id }: { id?: string }) => {
const searchParams = useSearchParams();
const initialMessage = searchParams?.get('q');
const initialMessage = searchParams.get('q');
const [chatId, setChatId] = useState<string | undefined>(id);
const [newChatCreated, setNewChatCreated] = useState(false);
@ -378,9 +378,7 @@ const ChatWindow = ({ id }: { id?: string }) => {
const [isWSReady, setIsWSReady] = useState(false);
const ws = useSocket(
process.env.NEXT_PUBLIC_WS_URL === 'auto'
? `${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${window.location.host}/ws`
: process.env.NEXT_PUBLIC_WS_URL!,
process.env.NEXT_PUBLIC_WS_URL!,
setIsWSReady,
setHasError,
);

View File

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

View File

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