Compare commits

..

7 Commits

Author SHA1 Message Date
c690c20417 Merge 7dfcac07cd into 4c73caadf6 2025-02-19 11:04:53 +00:00
7dfcac07cd Merge branch 'ItzCrazyKns:master' into feature-improvement 2025-02-19 15:04:49 +04:00
76ed952aa2 fix: update LMStudio endpoint from /health to /v1/models
- Replace health check endpoint with proper model listing endpoint
- Remove workaround that returned 200 for unexpected GET /v1/health
2025-02-16 15:21:28 +04:00
b20ea70089 Your commit message describing the changes 2025-02-16 03:04:54 +04:00
5220abae05 LM Studio Integration:
- Added LM Studio provider with OpenAI-compatible API support
- Dynamic model discovery via /v1/models endpoint
- Support for both chat and embeddings models
- Docker-compatible networking configuration
- Thinking Model Panel:

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

These improvements enhance the app's compatibility with local LLMs and provide better visibility into model reasoning processes while maintaining existing functionality.
2025-02-16 02:43:13 +04:00
9668056554 save current changes 2025-02-16 02:34:21 +04:00
1d6ab2c90c feat: Add LM Studio Support and Thinking Model Panel
LM Studio Integration:
- Added LM Studio provider with OpenAI-compatible API support
- Dynamic model discovery via /v1/models endpoint
- Support for both chat and embeddings models
- Docker-compatible networking configuration

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

These improvements enhance the app's compatibility with local LLMs and
provide better visibility into model reasoning processes while maintaining
existing functionality.
2025-02-16 02:33:45 +04:00
20 changed files with 7262 additions and 446 deletions

View File

@ -1,23 +1,8 @@
# 🚀 Perplexica - An AI-powered search engine 🔎 <!-- omit in toc -->
<div align="center" markdown="1">
<sup>Special thanks to:</sup>
<br>
<br>
<a href="https://www.warp.dev/perplexica">
<img alt="Warp sponsorship" width="400" src="https://github.com/user-attachments/assets/775dd593-9b5f-40f1-bf48-479faff4c27b">
</a>
### [Warp, the AI Devtool that lives in your terminal](https://www.warp.dev/perplexica)
[Available for MacOS, Linux, & Windows](https://www.warp.dev/perplexica)
</div>
<hr/>
[![Discord](https://dcbadge.vercel.app/api/server/26aArMy8tT?style=flat&compact=true)](https://discord.gg/26aArMy8tT)
![preview](.assets/perplexica-screenshot.png?)
## Table of Contents <!-- omit in toc -->
@ -59,7 +44,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 do not require searching the web.
- **Writing Assistant Mode:** Helpful for writing tasks that does 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.
@ -158,7 +143,6 @@ You can access Perplexica over your home network by following our networking gui
## 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)
## Upcoming Features

View File

@ -37,6 +37,7 @@ services:
args:
- NEXT_PUBLIC_API_URL=http://127.0.0.1:3001/api
- NEXT_PUBLIC_WS_URL=ws://127.0.0.1:3001
network: host
image: itzcrazykns1337/perplexica-frontend:main
depends_on:
- perplexica-backend

6912
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,10 +1,6 @@
[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]
@ -19,13 +15,16 @@ API_KEY = ""
[MODELS.GEMINI]
API_KEY = ""
[MODELS.OLLAMA]
API_URL = "" # Ollama API URL - http://host.docker.internal:11434
[MODELS.LMSTUDIO]
API_URL = "" # LM STUDIO API URL - http://host.docker.internal:1234
[MODELS.CUSTOM_OPENAI]
API_KEY = ""
API_URL = ""
MODEL_NAME = ""
[MODELS.OLLAMA]
API_URL = "" # Ollama API URL - http://host.docker.internal:11434
[API_ENDPOINTS]
SEARXNG = "http://localhost:32768" # SearxNG API URL

View File

@ -8,10 +8,6 @@ interface Config {
GENERAL: {
PORT: number;
SIMILARITY_MEASURE: string;
CONFIG_PASSWORD: string;
DISCOVER_ENABLED: boolean;
LIBRARY_ENABLED: boolean;
COPILOT_ENABLED: boolean;
KEEP_ALIVE: string;
};
MODELS: {
@ -30,6 +26,9 @@ interface Config {
OLLAMA: {
API_URL: string;
};
LMSTUDIO: {
API_URL: string;
};
CUSTOM_OPENAI: {
API_URL: string;
API_KEY: string;
@ -55,14 +54,6 @@ export const getPort = () => loadConfig().GENERAL.PORT;
export const getSimilarityMeasure = () =>
loadConfig().GENERAL.SIMILARITY_MEASURE;
export const getConfigPassword = () => loadConfig().GENERAL.CONFIG_PASSWORD;
export const isDiscoverEnabled = () => loadConfig().GENERAL.DISCOVER_ENABLED;
export const isLibraryEnabled = () => loadConfig().GENERAL.LIBRARY_ENABLED;
export const isCopilotEnabled = () => loadConfig().GENERAL.COPILOT_ENABLED;
export const getKeepAlive = () => loadConfig().GENERAL.KEEP_ALIVE;
export const getOpenaiApiKey = () => loadConfig().MODELS.OPENAI.API_KEY;
@ -78,6 +69,8 @@ export const getSearxngApiEndpoint = () =>
export const getOllamaApiEndpoint = () => loadConfig().MODELS.OLLAMA.API_URL;
export const getLMStudioApiEndpoint = () => loadConfig().MODELS.LMSTUDIO.API_URL;
export const getCustomOpenaiApiKey = () =>
loadConfig().MODELS.CUSTOM_OPENAI.API_KEY;
@ -88,10 +81,6 @@ export const getCustomOpenaiModelName = () =>
loadConfig().MODELS.CUSTOM_OPENAI.MODEL_NAME;
const mergeConfigs = (current: any, update: any): any => {
if (update === null || update === undefined) {
return current;
}
if (typeof current !== 'object' || current === null) {
return update;
}

1
src/lib/chat/service.ts Normal file
View File

@ -0,0 +1 @@

View File

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

View File

@ -0,0 +1,125 @@
import { OpenAIEmbeddings } from '@langchain/openai';
import { ChatOpenAI } from '@langchain/openai';
import { getKeepAlive, getLMStudioApiEndpoint } from '../../config';
import logger from '../../utils/logger';
import axios from 'axios';
const ensureV1Endpoint = (endpoint: string): string => {
return endpoint.endsWith('/v1') ? endpoint : `${endpoint}/v1`;
};
interface LMStudioModel {
id: string;
// add other properties if LM Studio API provides them
}
interface ChatModelConfig {
displayName: string;
model: ChatOpenAI;
}
const checkLMStudioAvailability = async (endpoint: string): Promise<boolean> => {
const v1Endpoint = ensureV1Endpoint(endpoint);
try {
await axios.get(`${v1Endpoint}/models`, {
timeout: 1000, // 1 second timeout
headers: {
'Content-Type': 'application/json',
},
});
return true;
} catch (err) {
logger.debug(`LM Studio server not available at ${endpoint}`);
return false;
}
};
export const loadLMStudioChatModels = async (): Promise<Record<string, ChatModelConfig>> => {
const lmStudioEndpoint = getLMStudioApiEndpoint();
if (!lmStudioEndpoint) {
logger.debug('LM Studio endpoint not configured, skipping');
return {};
}
// Check if server is available before attempting to load models
const isAvailable = await checkLMStudioAvailability(lmStudioEndpoint);
if (!isAvailable) {
return {};
}
try {
const v1Endpoint = ensureV1Endpoint(lmStudioEndpoint);
const response = await axios.get<{ data: LMStudioModel[] }>(`${v1Endpoint}/models`, {
timeout: 5000, // 5 second timeout for model loading
headers: {
'Content-Type': 'application/json',
},
});
const lmStudioModels = response.data.data;
const chatModels = lmStudioModels.reduce<Record<string, ChatModelConfig>>((acc, model) => {
acc[model.id] = {
displayName: model.id,
model: new ChatOpenAI({
openAIApiKey: 'lm-studio',
configuration: {
baseURL: ensureV1Endpoint(lmStudioEndpoint),
},
modelName: model.id,
temperature: 0.7,
}),
};
return acc;
}, {});
return chatModels;
} catch (err) {
logger.error(`Error loading LM Studio models: ${err}`);
return {};
}
};
export const loadLMStudioEmbeddingsModels = async () => {
const lmStudioEndpoint = getLMStudioApiEndpoint();
if (!lmStudioEndpoint) return {};
// Check if server is available before attempting to load models
const isAvailable = await checkLMStudioAvailability(lmStudioEndpoint);
if (!isAvailable) {
return {};
}
try {
const v1Endpoint = ensureV1Endpoint(lmStudioEndpoint);
const response = await axios.get(`${v1Endpoint}/models`, {
timeout: 5000, // 5 second timeout for model loading
headers: {
'Content-Type': 'application/json',
},
});
const lmStudioModels = response.data.data;
const embeddingsModels = lmStudioModels.reduce((acc, model) => {
acc[model.id] = {
displayName: model.id,
model: new OpenAIEmbeddings({
openAIApiKey: 'lm-studio', // Dummy key required by LangChain
configuration: {
baseURL: ensureV1Endpoint(lmStudioEndpoint),
},
modelName: model.id,
}),
};
return acc;
}, {});
return embeddingsModels;
} catch (err) {
logger.error(`Error loading LM Studio embeddings model: ${err}`);
return {};
}
};

View File

@ -6,14 +6,11 @@ import {
import {
getGroqApiKey,
getOllamaApiEndpoint,
getLMStudioApiEndpoint,
getAnthropicApiKey,
getGeminiApiKey,
getOpenaiApiKey,
updateConfig,
getConfigPassword,
isLibraryEnabled,
isCopilotEnabled,
isDiscoverEnabled,
getCustomOpenaiApiUrl,
getCustomOpenaiApiKey,
getCustomOpenaiModelName,
@ -22,16 +19,8 @@ import logger from '../utils/logger';
const router = express.Router();
router.get('/', async (req, res) => {
router.get('/', async (_, 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([
@ -66,12 +55,13 @@ router.get('/', async (req, res) => {
config['openaiApiKey'] = getOpenaiApiKey();
config['ollamaApiUrl'] = getOllamaApiEndpoint();
config['lmStudioApiUrl'] = getLMStudioApiEndpoint();
config['anthropicApiKey'] = getAnthropicApiKey();
config['groqApiKey'] = getGroqApiKey();
config['geminiApiKey'] = getGeminiApiKey();
config['customOpenaiApiUrl'] = getCustomOpenaiApiUrl();
config['customOpenaiApiKey'] = getCustomOpenaiApiKey();
config['customOpenaiModelName'] = getCustomOpenaiModelName();
config['customOpenaiModelName'] = getCustomOpenaiModelName()
res.status(200).json(config);
} catch (err: any) {
@ -81,22 +71,9 @@ router.get('/', async (req, res) => {
});
router.post('/', async (req, res) => {
const authHeader = req.headers['authorization']?.split(' ')[1];
const password = getConfigPassword();
if (authHeader !== password) {
res.status(401).json({ message: 'Unauthorized' });
return;
}
const config = req.body;
const updatedConfig = {
GENERAL: {
DISCOVER_ENABLED: config.isDiscoverEnabled,
LIBRARY_ENABLED: config.isLibraryEnabled,
COPILOT_ENABLED: config.isCopilotEnabled,
},
MODELS: {
OPENAI: {
API_KEY: config.openaiApiKey,
@ -113,6 +90,9 @@ router.post('/', async (req, res) => {
OLLAMA: {
API_URL: config.ollamaApiUrl,
},
LMSTUDIO: {
API_URL: config.lmStudioApiUrl,
},
CUSTOM_OPENAI: {
API_URL: config.customOpenaiApiUrl,
API_KEY: config.customOpenaiApiKey,
@ -126,14 +106,4 @@ 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,33 +9,10 @@ const router = express.Router();
router.get('/', async (req, res) => {
try {
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] = {};
});
});
const [chatModelProviders, embeddingModelProviders] = await Promise.all([
getAvailableChatModelProviders(),
getAvailableEmbeddingModelProviders(),
]);
Object.keys(chatModelProviders).forEach((provider) => {
Object.keys(chatModelProviders[provider]).forEach((model) => {

View File

@ -5,9 +5,8 @@ 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, gt, and } from 'drizzle-orm';
import { eq, asc, gt, and } from 'drizzle-orm';
import crypto from 'crypto';
import { isLibraryEnabled } from '../config';
import { getFileDetails } from '../utils/files';
import MetaSearchAgent, {
MetaSearchAgentType,
@ -95,8 +94,6 @@ const handleEmitterEvents = (
let recievedMessage = '';
let sources = [];
const libraryEnabled = isLibraryEnabled();
emitter.on('data', (data) => {
const parsedData = JSON.parse(data);
if (parsedData.type === 'response') {
@ -122,20 +119,18 @@ const handleEmitterEvents = (
emitter.on('end', () => {
ws.send(JSON.stringify({ type: 'messageEnd', messageId: messageId }));
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();
}
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);
@ -193,8 +188,6 @@ export const handleMessage = async (
const handler: MetaSearchAgentType =
searchHandlers[parsedWSMessage.focusMode];
const libraryEnabled = isLibraryEnabled();
if (handler) {
try {
const emitter = await handler.searchAndAnswer(
@ -208,52 +201,50 @@ export const handleMessage = async (
handleEmitterEvents(emitter, ws, aiMessageId, parsedMessage.chatId);
if (libraryEnabled) {
const chat = await db.query.chats.findFirst({
where: eq(chats.id, parsedMessage.chatId),
});
const chat = await db.query.chats.findFirst({
where: eq(chats.id, parsedMessage.chatId),
});
if (!chat) {
await db
.insert(chats)
.values({
id: parsedMessage.chatId,
title: parsedMessage.content,
createdAt: new Date().toString(),
focusMode: parsedWSMessage.focusMode,
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,31 +5,7 @@ export const metadata: Metadata = {
title: 'Library - Perplexica',
};
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>
);
}
const Layout = ({ children }: { children: React.ReactNode }) => {
return <div>{children}</div>;
};

View File

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

View File

@ -112,83 +112,6 @@ const Page = () => {
const [automaticImageSearch, setAutomaticImageSearch] = useState(false);
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 () => {
@ -196,7 +119,6 @@ const Page = () => {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/config`, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${password}`,
},
});
@ -271,16 +193,11 @@ 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');
}
@ -294,7 +211,6 @@ const Page = () => {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/config`, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${password}`,
},
});
@ -460,33 +376,6 @@ 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

@ -11,6 +11,8 @@ import {
StopCircle,
Layers3,
Plus,
Brain,
ChevronDown,
} from 'lucide-react';
import Markdown from 'markdown-to-jsx';
import Copy from './MessageActions/Copy';
@ -41,26 +43,58 @@ const MessageBox = ({
}) => {
const [parsedMessage, setParsedMessage] = useState(message.content);
const [speechMessage, setSpeechMessage] = useState(message.content);
const [thinking, setThinking] = useState<string>('');
const [answer, setAnswer] = useState<string>('');
const [isThinkingExpanded, setIsThinkingExpanded] = useState(false);
useEffect(() => {
const regex = /\[(\d+)\]/g;
const thinkRegex = /<think>(.*?)(?:<\/think>|$)(.*)/s;
if (
message.role === 'assistant' &&
message?.sources &&
message.sources.length > 0
) {
return setParsedMessage(
message.content.replace(
regex,
(_, number) =>
`<a href="${message.sources?.[number - 1]?.metadata?.url}" target="_blank" className="bg-light-secondary dark:bg-dark-secondary px-1 rounded ml-1 no-underline text-xs text-black/70 dark:text-white/70 relative">${number}</a>`,
),
);
// Check for thinking content, including partial tags
const match = message.content.match(thinkRegex);
if (match) {
const [_, thinkingContent, answerContent] = match;
// Set thinking content even if </think> hasn't appeared yet
if (thinkingContent) {
setThinking(thinkingContent.trim());
setIsThinkingExpanded(true); // Auto-expand when thinking starts
}
// Only set answer content if we have it (after </think>)
if (answerContent) {
setAnswer(answerContent.trim());
// Process the answer part for sources if needed
if (message.role === 'assistant' && message?.sources && message.sources.length > 0) {
setParsedMessage(
answerContent.trim().replace(
regex,
(_, number) =>
`<a href="${message.sources?.[number - 1]?.metadata?.url}" target="_blank" className="bg-light-secondary dark:bg-dark-secondary px-1 rounded ml-1 no-underline text-xs text-black/70 dark:text-white/70 relative">${number}</a>`,
),
);
} else {
setParsedMessage(answerContent.trim());
}
setSpeechMessage(answerContent.trim().replace(regex, ''));
}
} else {
// No thinking content - process as before
if (message.role === 'assistant' && message?.sources && message.sources.length > 0) {
setParsedMessage(
message.content.replace(
regex,
(_, number) =>
`<a href="${message.sources?.[number - 1]?.metadata?.url}" target="_blank" className="bg-light-secondary dark:bg-dark-secondary px-1 rounded ml-1 no-underline text-xs text-black/70 dark:text-white/70 relative">${number}</a>`,
),
);
} else {
setParsedMessage(message.content);
}
setSpeechMessage(message.content.replace(regex, ''));
}
setSpeechMessage(message.content.replace(regex, ''));
setParsedMessage(message.content);
}, [message.content, message.sources, message.role]);
const { speechStatus, start, stop } = useSpeech({ text: speechMessage });
@ -68,7 +102,7 @@ const MessageBox = ({
return (
<div>
{message.role === 'user' && (
<div className={cn('w-full', messageIndex === 0 ? 'pt-16' : 'pt-8', 'break-words')}>
<div className={cn('w-full', messageIndex === 0 ? 'pt-16' : 'pt-8')}>
<h2 className="text-black dark:text-white font-medium text-3xl lg:w-9/12">
{message.content}
</h2>
@ -92,27 +126,71 @@ const MessageBox = ({
<MessageSources sources={message.sources} />
</div>
)}
<div className="flex flex-col space-y-2">
<div className="flex flex-row items-center space-x-2">
<Disc3
className={cn(
'text-black dark:text-white',
isLast && loading ? 'animate-spin' : 'animate-none',
<div className="flex flex-col space-y-4">
{thinking && (
<div className="flex flex-col space-y-2 mb-4">
<button
onClick={() => setIsThinkingExpanded(!isThinkingExpanded)}
className="flex flex-row items-center space-x-2 group text-black/70 dark:text-white/70 hover:text-black dark:hover:text-white transition duration-200"
>
<Brain size={20} />
<h3 className="font-medium text-xl">Reasoning</h3>
<ChevronDown
size={16}
className={cn(
"transition-transform duration-200",
isThinkingExpanded ? "rotate-180" : ""
)}
/>
</button>
{isThinkingExpanded && (
<div className="rounded-lg bg-light-secondary/50 dark:bg-dark-secondary/50 p-4">
{thinking.split('\n\n').map((paragraph, index) => {
if (!paragraph.trim()) return null;
const content = paragraph.replace(/^[•\-\d.]\s*/, '');
return (
<div key={index} className="mb-2 last:mb-0">
<details className="group [&_summary::-webkit-details-marker]:hidden">
<summary className="flex items-center cursor-pointer list-none text-sm text-black/70 dark:text-white/70 hover:text-black dark:hover:text-white">
<span className="arrow mr-2 inline-block transition-transform duration-200 group-open:rotate-90 group-open:self-start group-open:mt-1"></span>
<p className="relative whitespace-normal line-clamp-1 group-open:line-clamp-none after:content-['...'] after:inline group-open:after:hidden transition-all duration-200 text-ellipsis overflow-hidden group-open:overflow-visible">
{content}
</p>
</summary>
</details>
</div>
);
})}
</div>
)}
size={20}
/>
<h3 className="text-black dark:text-white font-medium text-xl">
Answer
</h3>
</div>
)}
<div className="flex flex-col space-y-2">
<div className="flex flex-row items-center space-x-2">
<Disc3
className={cn(
'text-black dark:text-white',
isLast && loading ? 'animate-spin' : 'animate-none',
)}
size={20}
/>
<h3 className="text-black dark:text-white font-medium text-xl">
Answer
</h3>
</div>
<Markdown
className={cn(
'prose prose-h1:mb-3 prose-h2:mb-2 prose-h2:mt-6 prose-h2:font-[800] prose-h3:mt-4 prose-h3:mb-1.5 prose-h3:font-[600] dark:prose-invert prose-p:leading-relaxed prose-pre:p-0 font-[400]',
'max-w-none break-words text-black dark:text-white',
)}
>
{parsedMessage}
</Markdown>
</div>
<Markdown
className={cn(
'prose prose-h1:mb-3 prose-h2:mb-2 prose-h2:mt-6 prose-h2:font-[800] prose-h3:mt-4 prose-h3:mb-1.5 prose-h3:font-[600] dark:prose-invert prose-p:leading-relaxed prose-pre:p-0 font-[400]',
'max-w-none break-words text-black dark:text-white',
)}
>
{parsedMessage}
</Markdown>
{loading && isLast ? null : (
<div className="flex flex-row items-center justify-between w-full text-black dark:text-white py-4 -mx-2">
<div className="flex flex-row items-center space-x-1">

View File

@ -110,7 +110,7 @@ const Attach = ({
<button
type="button"
onClick={() => fileInputRef.current.click()}
className="flex flex-row items-center space-x-1 text-black/70 dark:text-white/70 hover:text-black hover:dark:text-white transition duration-200"
className="flex flex-row items-center space-x-1 text-white/70 hover:text-white transition duration-200"
>
<input
type="file"
@ -128,7 +128,7 @@ const Attach = ({
setFiles([]);
setFileIds([]);
}}
className="flex flex-row items-center space-x-1 text-black/70 dark:text-white/70 hover:text-black hover:dark:text-white transition duration-200"
className="flex flex-row items-center space-x-1 text-white/70 hover:text-white transition duration-200"
>
<Trash size={14} />
<p className="text-xs">Clear</p>
@ -145,7 +145,7 @@ const Attach = ({
<div className="bg-dark-100 flex items-center justify-center w-10 h-10 rounded-md">
<File size={16} className="text-white/70" />
</div>
<p className="text-black/70 dark:text-white/70 text-sm">
<p className="text-white/70 text-sm">
{file.fileName.length > 25
? file.fileName.replace(/\.\w+$/, '').substring(0, 25) +
'...' +

View File

@ -82,7 +82,7 @@ const AttachSmall = ({
<button
type="button"
onClick={() => fileInputRef.current.click()}
className="flex flex-row items-center space-x-1 text-black/70 dark:text-white/70 hover:text-black hover:dark:text-white transition duration-200"
className="flex flex-row items-center space-x-1 text-white/70 hover:text-white transition duration-200"
>
<input
type="file"
@ -100,7 +100,7 @@ const AttachSmall = ({
setFiles([]);
setFileIds([]);
}}
className="flex flex-row items-center space-x-1 text-black/70 dark:text-white/70 hover:text-black hover:dark:text-white transition duration-200"
className="flex flex-row items-center space-x-1 text-white/70 hover:text-white transition duration-200"
>
<Trash size={14} />
<p className="text-xs">Clear</p>
@ -117,7 +117,7 @@ const AttachSmall = ({
<div className="bg-dark-100 flex items-center justify-center w-10 h-10 rounded-md">
<File size={16} className="text-white/70" />
</div>
<p className="text-black/70 dark:text-white/70 text-sm">
<p className="text-white/70 text-sm">
{file.fileName.length > 25
? file.fileName.replace(/\.\w+$/, '').substring(0, 25) +
'...' +

View File

@ -1,6 +1,5 @@
import { cn } from '@/lib/utils';
import { Switch } from '@headlessui/react';
import { useEffect } from 'react';
const CopilotToggle = ({
copilotEnabled,
@ -9,33 +8,11 @@ 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,15 +4,9 @@ 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, { useEffect, useMemo, useState, type ReactNode } from 'react';
import React, { 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>
@ -23,31 +17,6 @@ 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 = [
{
@ -55,44 +24,22 @@ 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 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>
) : (
return (
<div>
<div className="hidden lg:fixed lg:inset-y-0 lg:z-50 lg:flex lg:w-20 lg:flex-col">
<div className="flex grow flex-col items-center justify-between gap-y-5 overflow-y-auto bg-light-secondary dark:bg-dark-secondary px-2 py-8">
@ -100,26 +47,23 @@ const Sidebar = ({ children }: { children: React.ReactNode }) => {
<SquarePen className="cursor-pointer" />
</a>
<VerticalIconContainer>
{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>
),
)}
{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>
))}
</VerticalIconContainer>
<Link href="/settings">

View File

@ -1,5 +1,6 @@
{
"compilerOptions": {
"target": "es2018",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,