UPDATED cache in suggestions
This commit is contained in:
parent
dcb7c54800
commit
7a887f59bc
5 changed files with 70 additions and 21 deletions
|
@ -39,7 +39,7 @@ app.use(async (req: Request, res: Response, next: NextFunction) => {
|
||||||
const result = originalSend(body);
|
const result = originalSend(body);
|
||||||
|
|
||||||
redisClient
|
redisClient
|
||||||
.setEx(cacheKey, 3600, JSON.stringify(body))
|
.setEx(cacheKey, 86400, JSON.stringify(body))
|
||||||
.then(() => logger.info(`Cache set for ${cacheKey}`))
|
.then(() => logger.info(`Cache set for ${cacheKey}`))
|
||||||
.catch((err) => logger.error(`Redis setEx error: ${err}`));
|
.catch((err) => logger.error(`Redis setEx error: ${err}`));
|
||||||
|
|
||||||
|
|
|
@ -4,13 +4,19 @@ import { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
||||||
import { getAvailableChatModelProviders } from '../lib/providers';
|
import { getAvailableChatModelProviders } from '../lib/providers';
|
||||||
import { HumanMessage, AIMessage } from '@langchain/core/messages';
|
import { HumanMessage, AIMessage } from '@langchain/core/messages';
|
||||||
import logger from '../utils/logger';
|
import logger from '../utils/logger';
|
||||||
|
import redisClient from '../utils/redisClient';
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
router.post('/', async (req, res) => {
|
router.post('/', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
let { chat_history, chat_model, chat_model_provider } = req.body;
|
let { chat_history, chat_model, chat_model_provider } = req.body;
|
||||||
|
const messageId = chat_history[1]?.messageId;
|
||||||
|
const cachedResponse = await redisClient.get(messageId);
|
||||||
|
|
||||||
|
if (cachedResponse) {
|
||||||
|
logger.info(`Cache hit for messageId: ${messageId}`);
|
||||||
|
return res.status(200).json(JSON.parse(cachedResponse));
|
||||||
|
}
|
||||||
chat_history = chat_history.map((msg: any) => {
|
chat_history = chat_history.map((msg: any) => {
|
||||||
if (msg.role === 'user') {
|
if (msg.role === 'user') {
|
||||||
return new HumanMessage(msg.content);
|
return new HumanMessage(msg.content);
|
||||||
|
@ -36,6 +42,7 @@ router.post('/', async (req, res) => {
|
||||||
|
|
||||||
const suggestions = await generateSuggestions({ chat_history }, llm);
|
const suggestions = await generateSuggestions({ chat_history }, llm);
|
||||||
|
|
||||||
|
await redisClient.setEx(messageId, 86400, JSON.stringify({ suggestions }));
|
||||||
res.status(200).json({ suggestions: suggestions });
|
res.status(200).json({ suggestions: suggestions });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
res.status(500).json({ message: 'An error has occurred.' });
|
res.status(500).json({ message: 'An error has occurred.' });
|
||||||
|
|
|
@ -178,7 +178,7 @@ export const handleMessage = async (
|
||||||
.values({
|
.values({
|
||||||
content: parsedMessage.content,
|
content: parsedMessage.content,
|
||||||
chatId: parsedMessage.chatId,
|
chatId: parsedMessage.chatId,
|
||||||
messageId: id,
|
messageId: jsonDatabase.messageId,
|
||||||
role: 'user',
|
role: 'user',
|
||||||
metadata: JSON.stringify({
|
metadata: JSON.stringify({
|
||||||
createdAt: new Date(),
|
createdAt: new Date(),
|
||||||
|
@ -190,7 +190,7 @@ export const handleMessage = async (
|
||||||
.values({
|
.values({
|
||||||
content: jsonDatabase.content,
|
content: jsonDatabase.content,
|
||||||
chatId: parsedMessage.chatId,
|
chatId: parsedMessage.chatId,
|
||||||
messageId: id,
|
messageId: jsonDatabase.messageId,
|
||||||
role: jsonDatabase.role,
|
role: jsonDatabase.role,
|
||||||
metadata: JSON.stringify({
|
metadata: JSON.stringify({
|
||||||
createdAt: new Date(),
|
createdAt: new Date(),
|
||||||
|
|
|
@ -167,7 +167,7 @@ const useSocket = (
|
||||||
'Failed to connect to the server. Please try again later.',
|
'Failed to connect to the server. Please try again later.',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}, 10000);
|
}, 1000);
|
||||||
|
|
||||||
ws.onopen = () => {
|
ws.onopen = () => {
|
||||||
console.log('[DEBUG] open');
|
console.log('[DEBUG] open');
|
||||||
|
@ -280,6 +280,8 @@ const ChatWindow = ({ id }: { id?: string }) => {
|
||||||
const [isMessagesLoaded, setIsMessagesLoaded] = useState(false);
|
const [isMessagesLoaded, setIsMessagesLoaded] = useState(false);
|
||||||
|
|
||||||
const [notFound, setNotFound] = useState(false);
|
const [notFound, setNotFound] = useState(false);
|
||||||
|
const [cache, setCache] = useState(false);
|
||||||
|
const [newRequest, setNewRequest] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (
|
if (
|
||||||
|
@ -361,6 +363,7 @@ const ChatWindow = ({ id }: { id?: string }) => {
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const messageHandler = async (e: MessageEvent) => {
|
const messageHandler = async (e: MessageEvent) => {
|
||||||
|
setNewRequest(true);
|
||||||
const data = JSON.parse(e.data);
|
const data = JSON.parse(e.data);
|
||||||
|
|
||||||
if (data.type === 'error') {
|
if (data.type === 'error') {
|
||||||
|
@ -371,6 +374,9 @@ const ChatWindow = ({ id }: { id?: string }) => {
|
||||||
|
|
||||||
if (data.type === 'sources') {
|
if (data.type === 'sources') {
|
||||||
sources = data.data;
|
sources = data.data;
|
||||||
|
if (data.cache) {
|
||||||
|
setCache(true);
|
||||||
|
}
|
||||||
if (typeof sources === 'string') {
|
if (typeof sources === 'string') {
|
||||||
sources = JSON.parse(data.data);
|
sources = JSON.parse(data.data);
|
||||||
added = false;
|
added = false;
|
||||||
|
@ -490,12 +496,39 @@ const ChatWindow = ({ id }: { id?: string }) => {
|
||||||
sendMessage(message.content);
|
sendMessage(message.content);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const getSuggestionsWithPreviewInfo = async () => {
|
||||||
|
if (
|
||||||
|
messages[1].role === 'assistant' &&
|
||||||
|
messages[1].sources &&
|
||||||
|
messages[1].sources.length > 0 &&
|
||||||
|
!messages[1].suggestions
|
||||||
|
) {
|
||||||
|
const suggestions = await getSuggestions(messagesRef.current);
|
||||||
|
setMessages((prev) =>
|
||||||
|
prev.map((msg) => {
|
||||||
|
if (msg.messageId === messages[1].messageId) {
|
||||||
|
return { ...msg, suggestions: suggestions };
|
||||||
|
}
|
||||||
|
return msg;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isReady && initialMessage) {
|
if (isReady && initialMessage) {
|
||||||
sendMessage(initialMessage);
|
sendMessage(initialMessage);
|
||||||
}
|
}
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [isReady, initialMessage]);
|
}, [isReady, initialMessage]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (
|
||||||
|
(messages.length > 1 && cache) ||
|
||||||
|
(messages.length > 1 && !newRequest)
|
||||||
|
) {
|
||||||
|
getSuggestionsWithPreviewInfo();
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [messages]);
|
||||||
|
|
||||||
if (hasError) {
|
if (hasError) {
|
||||||
return (
|
return (
|
||||||
|
|
|
@ -1,22 +1,31 @@
|
||||||
import { Message } from '@/components/ChatWindow';
|
import { Message } from '@/components/ChatWindow';
|
||||||
|
|
||||||
export const getSuggestions = async (chatHisory: Message[]) => {
|
export const getSuggestions = async (chatHistory: Message[]) => {
|
||||||
const chatModel = localStorage.getItem('chatModel');
|
try {
|
||||||
const chatModelProvider = localStorage.getItem('chatModelProvider');
|
const chatModel = localStorage.getItem('chatModel');
|
||||||
|
const chatModelProvider = localStorage.getItem('chatModelProvider');
|
||||||
|
|
||||||
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/suggestions`, {
|
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/suggestions`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
chat_history: chatHisory,
|
chat_history: chatHistory,
|
||||||
chat_model: chatModel,
|
chat_model: chatModel,
|
||||||
chat_model_provider: chatModelProvider,
|
chat_model_provider: chatModelProvider,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = (await res.json()) as { suggestions: string[] };
|
if (!res.ok) {
|
||||||
|
throw new Error(`Error: ${res.status} ${res.statusText}`);
|
||||||
|
}
|
||||||
|
|
||||||
return data.suggestions;
|
const data = (await res.json()) as { suggestions: string[] };
|
||||||
|
|
||||||
|
return data.suggestions;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching suggestions:', error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
Loading…
Add table
Reference in a new issue