mirror of
https://github.com/ItzCrazyKns/Perplexica.git
synced 2025-05-02 17:22:32 +00:00
Compare commits
13 Commits
feat/model
...
8b2f1b9c49
Author | SHA1 | Date | |
---|---|---|---|
|
8b2f1b9c49 | ||
|
a85f762c58 | ||
|
3ddcceda0a | ||
|
02f5739070 | ||
|
e226645bc7 | ||
|
5447530ece | ||
|
ed6d46a440 | ||
|
588e68e93e | ||
|
c4440327db | ||
|
8097610baf | ||
|
64e2d457cc | ||
|
bf705afc21 | ||
|
2e4433a6b3 |
@ -33,6 +33,7 @@ The API accepts a JSON object in the request body, where you define the focus mo
|
||||
["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
|
||||
}
|
||||
```
|
||||
@ -63,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
|
||||
|
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "perplexica-frontend",
|
||||
"version": "1.10.1",
|
||||
"version": "1.10.2",
|
||||
"license": "MIT",
|
||||
"author": "ItzCrazyKns",
|
||||
"scripts": {
|
||||
|
@ -22,5 +22,8 @@ MODEL_NAME = ""
|
||||
[MODELS.OLLAMA]
|
||||
API_URL = "" # Ollama API URL - http://host.docker.internal:11434
|
||||
|
||||
[MODELS.DEEPSEEK]
|
||||
API_KEY = ""
|
||||
|
||||
[API_ENDPOINTS]
|
||||
SEARXNG = "" # SearxNG API URL - http://localhost:32768
|
@ -29,6 +29,7 @@ type Message = {
|
||||
messageId: string;
|
||||
chatId: string;
|
||||
content: string;
|
||||
userSessionId: string;
|
||||
};
|
||||
|
||||
type ChatModel = {
|
||||
@ -138,6 +139,7 @@ const handleHistorySave = async (
|
||||
where: eq(chats.id, message.chatId),
|
||||
});
|
||||
|
||||
let currentDate = new Date();
|
||||
if (!chat) {
|
||||
await db
|
||||
.insert(chats)
|
||||
@ -147,6 +149,8 @@ const handleHistorySave = async (
|
||||
createdAt: new Date().toString(),
|
||||
focusMode: focusMode,
|
||||
files: files.map(getFileDetails),
|
||||
userSessionId: message.userSessionId,
|
||||
timestamp: currentDate.toISOString(),
|
||||
})
|
||||
.execute();
|
||||
}
|
||||
|
@ -1,10 +1,47 @@
|
||||
import db from '@/lib/db';
|
||||
import { chats } from '@/lib/db/schema';
|
||||
import { eq, sql} from 'drizzle-orm';
|
||||
|
||||
export const GET = async (req: Request) => {
|
||||
try {
|
||||
let chats = await db.query.chats.findMany();
|
||||
chats = chats.reverse();
|
||||
return Response.json({ chats: chats }, { status: 200 });
|
||||
// get header from request
|
||||
const headers = await req.headers;
|
||||
const userSessionId = headers.get('user-session-id')?.toString() ?? '';
|
||||
const maxRecordLimit = parseInt(headers.get('max-record-limit') || '20', 10);
|
||||
|
||||
if (userSessionId == '') {
|
||||
return Response.json({ chats: {} }, { status: 200 });
|
||||
}
|
||||
|
||||
let chatsRes = await db.query.chats.findMany({
|
||||
where: eq(chats.userSessionId, userSessionId),
|
||||
});
|
||||
|
||||
chatsRes = chatsRes.reverse();
|
||||
// Keep only the latest records in the database. Delete older records.
|
||||
if (chatsRes.length > maxRecordLimit) {
|
||||
const deleteChatsQuery = sql`DELETE FROM chats
|
||||
WHERE userSessionId = ${userSessionId} AND (
|
||||
timestamp IS NULL OR
|
||||
timestamp NOT in (
|
||||
SELECT timestamp FROM chats
|
||||
WHERE userSessionId = ${userSessionId}
|
||||
ORDER BY timestamp DESC
|
||||
LIMIT ${maxRecordLimit}
|
||||
)
|
||||
)
|
||||
`;
|
||||
await db.run(deleteChatsQuery);
|
||||
// Delete messages that no longer link with the chat from the database.
|
||||
const deleteMessagesQuery = sql`DELETE FROM messages
|
||||
WHERE chatId NOT IN (
|
||||
SELECT id FROM chats
|
||||
)
|
||||
`;
|
||||
await db.run(deleteMessagesQuery);
|
||||
}
|
||||
|
||||
return Response.json({ chats: chatsRes }, { status: 200 });
|
||||
} catch (err) {
|
||||
console.error('Error in getting chats: ', err);
|
||||
return Response.json(
|
||||
|
@ -7,6 +7,7 @@ import {
|
||||
getGroqApiKey,
|
||||
getOllamaApiEndpoint,
|
||||
getOpenaiApiKey,
|
||||
getDeepseekApiKey,
|
||||
updateConfig,
|
||||
} from '@/lib/config';
|
||||
import {
|
||||
@ -53,6 +54,7 @@ export const GET = async (req: Request) => {
|
||||
config['anthropicApiKey'] = getAnthropicApiKey();
|
||||
config['groqApiKey'] = getGroqApiKey();
|
||||
config['geminiApiKey'] = getGeminiApiKey();
|
||||
config['deepseekApiKey'] = getDeepseekApiKey();
|
||||
config['customOpenaiApiUrl'] = getCustomOpenaiApiUrl();
|
||||
config['customOpenaiApiKey'] = getCustomOpenaiApiKey();
|
||||
config['customOpenaiModelName'] = getCustomOpenaiModelName();
|
||||
@ -88,6 +90,9 @@ export const POST = async (req: Request) => {
|
||||
OLLAMA: {
|
||||
API_URL: config.ollamaApiUrl,
|
||||
},
|
||||
DEEPSEEK: {
|
||||
API_KEY: config.deepseekApiKey,
|
||||
},
|
||||
CUSTOM_OPENAI: {
|
||||
API_URL: config.customOpenaiApiUrl,
|
||||
API_KEY: config.customOpenaiApiKey,
|
||||
|
@ -34,6 +34,7 @@ interface ChatRequestBody {
|
||||
query: string;
|
||||
history: Array<[string, string]>;
|
||||
stream?: boolean;
|
||||
systemInstructions?: string;
|
||||
}
|
||||
|
||||
export const POST = async (req: Request) => {
|
||||
@ -125,7 +126,7 @@ export const POST = async (req: Request) => {
|
||||
embeddings,
|
||||
body.optimizationMode,
|
||||
[],
|
||||
'',
|
||||
body.systemInstructions || '',
|
||||
);
|
||||
|
||||
if (!body.stream) {
|
||||
|
@ -1,5 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import crypto from 'crypto';
|
||||
import DeleteChat from '@/components/DeleteChat';
|
||||
import { cn, formatTimeDifference } from '@/lib/utils';
|
||||
import { BookOpenText, ClockIcon, Delete, ScanEye } from 'lucide-react';
|
||||
@ -21,10 +22,34 @@ const Page = () => {
|
||||
const fetchChats = async () => {
|
||||
setLoading(true);
|
||||
|
||||
let userSessionId = localStorage.getItem('userSessionId');
|
||||
if (!userSessionId) {
|
||||
userSessionId = crypto.randomBytes(20).toString('hex');
|
||||
localStorage.setItem('userSessionId', userSessionId)
|
||||
}
|
||||
|
||||
// Get maxRecordLimit from localStorage or set default
|
||||
let maxRecordLimit = localStorage.getItem('maxRecordLimit');
|
||||
if (!maxRecordLimit) {
|
||||
maxRecordLimit = '20';
|
||||
localStorage.setItem('maxRecordLimit', maxRecordLimit);
|
||||
} else {
|
||||
let valueInt = parseInt(maxRecordLimit, 10) || 20;
|
||||
if (valueInt < 1) {
|
||||
valueInt = 1;
|
||||
} else if (valueInt > 100) {
|
||||
valueInt = 100;
|
||||
}
|
||||
maxRecordLimit = valueInt.toString();
|
||||
localStorage.setItem('maxRecordLimit', maxRecordLimit);
|
||||
}
|
||||
|
||||
const res = await fetch(`/api/chats`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'user-session-id': userSessionId!,
|
||||
'max-record-limit': maxRecordLimit,
|
||||
},
|
||||
});
|
||||
|
||||
|
@ -20,9 +20,11 @@ interface SettingsType {
|
||||
anthropicApiKey: string;
|
||||
geminiApiKey: string;
|
||||
ollamaApiUrl: string;
|
||||
deepseekApiKey: string;
|
||||
customOpenaiApiKey: string;
|
||||
customOpenaiApiUrl: string;
|
||||
customOpenaiModelName: string;
|
||||
maxRecordLimit: string;
|
||||
}
|
||||
|
||||
interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
|
||||
@ -145,6 +147,7 @@ const Page = () => {
|
||||
const [automaticVideoSearch, setAutomaticVideoSearch] = useState(false);
|
||||
const [systemInstructions, setSystemInstructions] = useState<string>('');
|
||||
const [savingStates, setSavingStates] = useState<Record<string, boolean>>({});
|
||||
const [maxRecordLimit, setMaxRecordLimit] = useState<string>('20');
|
||||
|
||||
useEffect(() => {
|
||||
const fetchConfig = async () => {
|
||||
@ -207,6 +210,8 @@ const Page = () => {
|
||||
|
||||
setSystemInstructions(localStorage.getItem('systemInstructions')!);
|
||||
|
||||
setMaxRecordLimit(localStorage.getItem('maxRecordLimit') || data.maxRecordLimit || '20');
|
||||
|
||||
setIsLoading(false);
|
||||
};
|
||||
|
||||
@ -365,6 +370,15 @@ const Page = () => {
|
||||
localStorage.setItem('embeddingModel', value);
|
||||
} else if (key === 'systemInstructions') {
|
||||
localStorage.setItem('systemInstructions', value);
|
||||
} else if (key === 'maxRecordLimit') {
|
||||
let valueInt = parseInt(value, 10) || 20;
|
||||
if (valueInt < 1) {
|
||||
valueInt = 1;
|
||||
} else if (valueInt > 100) {
|
||||
valueInt = 100;
|
||||
}
|
||||
setMaxRecordLimit(valueInt.toString());
|
||||
localStorage.setItem('maxRecordLimit', valueInt.toString());
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to save:', err);
|
||||
@ -838,6 +852,56 @@ const Page = () => {
|
||||
onSave={(value) => saveConfig('geminiApiKey', value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col space-y-1">
|
||||
<p className="text-black/70 dark:text-white/70 text-sm">
|
||||
Deepseek API Key
|
||||
</p>
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Deepseek API Key"
|
||||
value={config.deepseekApiKey}
|
||||
isSaving={savingStates['deepseekApiKey']}
|
||||
onChange={(e) => {
|
||||
setConfig((prev) => ({
|
||||
...prev!,
|
||||
deepseekApiKey: e.target.value,
|
||||
}));
|
||||
}}
|
||||
onSave={(value) => saveConfig('deepseekApiKey', value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title="Chat History">
|
||||
<div className="flex flex-col space-y-4">
|
||||
<div className="flex flex-col space-y-1">
|
||||
<p className="text-black/70 dark:text-white/70 text-sm">
|
||||
Maximum Chat History Records
|
||||
</p>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
max="100"
|
||||
pattern="[0-9]*"
|
||||
inputMode="numeric"
|
||||
value={maxRecordLimit}
|
||||
isSaving={savingStates['maxRecordLimit']}
|
||||
onChange={(e) => {
|
||||
setMaxRecordLimit(e.target.value);
|
||||
}}
|
||||
onSave={(value) => saveConfig('maxRecordLimit', value)}
|
||||
/>
|
||||
<span className="text-black/60 dark:text-white/60 text-sm">
|
||||
records
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-xs text-black/60 dark:text-white/60 mt-1">
|
||||
Maximum number of chat records to keep in history. Older records will be automatically deleted.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</SettingsSection>
|
||||
</div>
|
||||
|
@ -95,6 +95,18 @@ const checkConfig = async (
|
||||
if (!embeddingModel || !embeddingModelProvider) {
|
||||
const embeddingModelProviders = providers.embeddingModelProviders;
|
||||
|
||||
let userSessionId = localStorage.getItem('userSessionId');
|
||||
if (!userSessionId) {
|
||||
userSessionId = crypto.randomBytes(20).toString('hex');
|
||||
localStorage.setItem('userSessionId', userSessionId!)
|
||||
}
|
||||
|
||||
let maxRecordLimit = localStorage.getItem('maxRecordLimit');
|
||||
if (!maxRecordLimit) {
|
||||
maxRecordLimit = '20';
|
||||
localStorage.setItem('maxRecordLimit', maxRecordLimit);
|
||||
}
|
||||
|
||||
if (
|
||||
!embeddingModelProviders ||
|
||||
Object.keys(embeddingModelProviders).length === 0
|
||||
@ -342,6 +354,7 @@ const ChatWindow = ({ id }: { id?: string }) => {
|
||||
let added = false;
|
||||
|
||||
messageId = messageId ?? crypto.randomBytes(7).toString('hex');
|
||||
let userSessionId = localStorage.getItem('userSessionId');
|
||||
|
||||
setMessages((prevMessages) => [
|
||||
...prevMessages,
|
||||
@ -466,6 +479,7 @@ const ChatWindow = ({ id }: { id?: string }) => {
|
||||
messageId: messageId,
|
||||
chatId: chatId!,
|
||||
content: message,
|
||||
userSessionId: userSessionId,
|
||||
},
|
||||
chatId: chatId!,
|
||||
files: fileIds,
|
||||
|
@ -48,6 +48,7 @@ const MessageBox = ({
|
||||
const [speechMessage, setSpeechMessage] = useState(message.content);
|
||||
|
||||
useEffect(() => {
|
||||
const citationRegex = /\[([^\]]+)\]/g;
|
||||
const regex = /\[(\d+)\]/g;
|
||||
let processedMessage = message.content;
|
||||
|
||||
@ -67,11 +68,33 @@ const MessageBox = ({
|
||||
) {
|
||||
setParsedMessage(
|
||||
processedMessage.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>`,
|
||||
citationRegex,
|
||||
(_, capturedContent: string) => {
|
||||
const numbers = capturedContent
|
||||
.split(',')
|
||||
.map((numStr) => numStr.trim());
|
||||
|
||||
const linksHtml = numbers
|
||||
.map((numStr) => {
|
||||
const number = parseInt(numStr);
|
||||
|
||||
if (isNaN(number) || number <= 0) {
|
||||
return `[${numStr}]`;
|
||||
}
|
||||
|
||||
const source = message.sources?.[number - 1];
|
||||
const url = source?.metadata?.url;
|
||||
|
||||
if (url) {
|
||||
return `<a href="${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">${numStr}</a>`;
|
||||
} else {
|
||||
return `[${numStr}]`;
|
||||
}
|
||||
})
|
||||
.join('');
|
||||
|
||||
return linksHtml;
|
||||
},
|
||||
),
|
||||
);
|
||||
return;
|
||||
|
@ -25,6 +25,9 @@ interface Config {
|
||||
OLLAMA: {
|
||||
API_URL: string;
|
||||
};
|
||||
DEEPSEEK: {
|
||||
API_KEY: string;
|
||||
};
|
||||
CUSTOM_OPENAI: {
|
||||
API_URL: string;
|
||||
API_KEY: string;
|
||||
@ -63,6 +66,8 @@ export const getSearxngApiEndpoint = () =>
|
||||
|
||||
export const getOllamaApiEndpoint = () => loadConfig().MODELS.OLLAMA.API_URL;
|
||||
|
||||
export const getDeepseekApiKey = () => loadConfig().MODELS.DEEPSEEK.API_KEY;
|
||||
|
||||
export const getCustomOpenaiApiKey = () =>
|
||||
loadConfig().MODELS.CUSTOM_OPENAI.API_KEY;
|
||||
|
||||
|
@ -25,4 +25,6 @@ export const chats = sqliteTable('chats', {
|
||||
files: text('files', { mode: 'json' })
|
||||
.$type<File[]>()
|
||||
.default(sql`'[]'`),
|
||||
userSessionId: text('userSessionId'),
|
||||
timestamp: text('timestamp'),
|
||||
});
|
||||
|
44
src/lib/providers/deepseek.ts
Normal file
44
src/lib/providers/deepseek.ts
Normal file
@ -0,0 +1,44 @@
|
||||
import { ChatOpenAI } from '@langchain/openai';
|
||||
import { getDeepseekApiKey } from '../config';
|
||||
import { ChatModel } from '.';
|
||||
import { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
||||
|
||||
const deepseekChatModels: Record<string, string>[] = [
|
||||
{
|
||||
displayName: 'Deepseek Chat (Deepseek V3)',
|
||||
key: 'deepseek-chat',
|
||||
},
|
||||
{
|
||||
displayName: 'Deepseek Reasoner (Deepseek R1)',
|
||||
key: 'deepseek-reasoner',
|
||||
},
|
||||
];
|
||||
|
||||
export const loadDeepseekChatModels = async () => {
|
||||
const deepseekApiKey = getDeepseekApiKey();
|
||||
|
||||
if (!deepseekApiKey) return {};
|
||||
|
||||
try {
|
||||
const chatModels: Record<string, ChatModel> = {};
|
||||
|
||||
deepseekChatModels.forEach((model) => {
|
||||
chatModels[model.key] = {
|
||||
displayName: model.displayName,
|
||||
model: new ChatOpenAI({
|
||||
openAIApiKey: deepseekApiKey,
|
||||
modelName: model.key,
|
||||
temperature: 0.7,
|
||||
configuration: {
|
||||
baseURL: 'https://api.deepseek.com',
|
||||
},
|
||||
}) as unknown as BaseChatModel,
|
||||
};
|
||||
});
|
||||
|
||||
return chatModels;
|
||||
} catch (err) {
|
||||
console.error(`Error loading Deepseek models: ${err}`);
|
||||
return {};
|
||||
}
|
||||
};
|
@ -40,8 +40,12 @@ const geminiChatModels: Record<string, string>[] = [
|
||||
|
||||
const geminiEmbeddingModels: Record<string, string>[] = [
|
||||
{
|
||||
displayName: 'Gemini Embedding',
|
||||
key: 'gemini-embedding-exp',
|
||||
displayName: 'Text Embedding 004',
|
||||
key: 'models/text-embedding-004',
|
||||
},
|
||||
{
|
||||
displayName: 'Embedding 001',
|
||||
key: 'models/embedding-001',
|
||||
},
|
||||
];
|
||||
|
||||
|
@ -12,6 +12,7 @@ import { loadGroqChatModels } from './groq';
|
||||
import { loadAnthropicChatModels } from './anthropic';
|
||||
import { loadGeminiChatModels, loadGeminiEmbeddingModels } from './gemini';
|
||||
import { loadTransformersEmbeddingsModels } from './transformers';
|
||||
import { loadDeepseekChatModels } from './deepseek';
|
||||
|
||||
export interface ChatModel {
|
||||
displayName: string;
|
||||
@ -32,6 +33,7 @@ export const chatModelProviders: Record<
|
||||
groq: loadGroqChatModels,
|
||||
anthropic: loadAnthropicChatModels,
|
||||
gemini: loadGeminiChatModels,
|
||||
deepseek: loadDeepseekChatModels,
|
||||
};
|
||||
|
||||
export const embeddingModelProviders: Record<
|
||||
|
Reference in New Issue
Block a user