From 61c0347ef29256fc70311f40a6b4a20ddd6f9b7e Mon Sep 17 00:00:00 2001 From: ItzCrazyKns <95534749+ItzCrazyKns@users.noreply.github.com> Date: Tue, 15 Oct 2024 16:20:45 +0530 Subject: [PATCH 1/6] feat(app): add discover --- src/routes/discover.ts | 48 +++++++++++++++++ src/routes/index.ts | 2 + ui/app/discover/page.tsx | 112 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 162 insertions(+) create mode 100644 src/routes/discover.ts create mode 100644 ui/app/discover/page.tsx diff --git a/src/routes/discover.ts b/src/routes/discover.ts new file mode 100644 index 0000000..b6f8ff9 --- /dev/null +++ b/src/routes/discover.ts @@ -0,0 +1,48 @@ +import express from 'express'; +import { searchSearxng } from '../lib/searxng'; +import logger from '../utils/logger'; + +const router = express.Router(); + +router.get('/', async (req, res) => { + try { + const data = ( + await Promise.all([ + searchSearxng('site:businessinsider.com AI', { + engines: ['bing news'], + pageno: 1, + }), + searchSearxng('site:www.exchangewire.com AI', { + engines: ['bing news'], + pageno: 1, + }), + searchSearxng('site:yahoo.com AI', { + engines: ['bing news'], + pageno: 1, + }), + searchSearxng('site:businessinsider.com tech', { + engines: ['bing news'], + pageno: 1, + }), + searchSearxng('site:www.exchangewire.com tech', { + engines: ['bing news'], + pageno: 1, + }), + searchSearxng('site:yahoo.com tech', { + engines: ['bing news'], + pageno: 1, + }), + ]) + ) + .map((result) => result.results) + .flat() + .sort(() => Math.random() - 0.5); + + return res.json({ blogs: data }); + } catch (err: any) { + logger.error(`Error in discover route: ${err.message}`); + return res.status(500).json({ message: 'An error has occurred' }); + } +}); + +export default router; diff --git a/src/routes/index.ts b/src/routes/index.ts index 6e82e54..28c297f 100644 --- a/src/routes/index.ts +++ b/src/routes/index.ts @@ -6,6 +6,7 @@ import modelsRouter from './models'; import suggestionsRouter from './suggestions'; import chatsRouter from './chats'; import searchRouter from './search'; +import discoverRouter from './discover'; const router = express.Router(); @@ -16,5 +17,6 @@ router.use('/models', modelsRouter); router.use('/suggestions', suggestionsRouter); router.use('/chats', chatsRouter); router.use('/search', searchRouter); +router.use('/discover', discoverRouter); export default router; diff --git a/ui/app/discover/page.tsx b/ui/app/discover/page.tsx new file mode 100644 index 0000000..7788d0d --- /dev/null +++ b/ui/app/discover/page.tsx @@ -0,0 +1,112 @@ +'use client'; + +import { Search } from 'lucide-react'; +import { useEffect, useState } from 'react'; +import Link from 'next/link'; +import { toast } from 'sonner'; + +interface Discover { + title: string; + content: string; + url: string; + thumbnail: string; +} + +const Page = () => { + const [discover, setDiscover] = useState(null); + const [loading, setLoading] = useState(true); + + useEffect(() => { + const fetchData = async () => { + try { + const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/discover`, { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + }, + }); + + const data = await res.json(); + + if (!res.ok) { + throw new Error(data.message); + } + + data.blogs = data.blogs.filter((blog: Discover) => blog.thumbnail); + + setDiscover(data.blogs); + } catch (err: any) { + console.error('Error fetching data:', err.message); + toast.error('Error fetching data'); + } finally { + setLoading(false); + } + }; + + fetchData(); + }, []); + + return loading ? ( +
+ +
+ ) : ( + <> +
+
+
+ +

Discover

+
+
+
+ +
+ {discover && + discover?.map((item, i) => ( + + {item.title} +
+
+ {item.title.slice(0, 100)}... +
+

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

+
+ + ))} +
+
+ + ); +}; + +export default Page; From 19bf71cefc8e76d952add1e53c8761c591d76f18 Mon Sep 17 00:00:00 2001 From: ItzCrazyKns <95534749+ItzCrazyKns@users.noreply.github.com> Date: Tue, 15 Oct 2024 16:21:00 +0530 Subject: [PATCH 2/6] feat(chat-window): only send init msg if ready --- ui/components/ChatWindow.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ui/components/ChatWindow.tsx b/ui/components/ChatWindow.tsx index b67ca3a..6a56f7e 100644 --- a/ui/components/ChatWindow.tsx +++ b/ui/components/ChatWindow.tsx @@ -473,11 +473,11 @@ const ChatWindow = ({ id }: { id?: string }) => { }; useEffect(() => { - if (isReady && initialMessage) { + if (isReady && initialMessage && ws?.readyState === 1) { sendMessage(initialMessage); } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [isReady, initialMessage]); + }, [isReady, initialMessage, ws?.readyState]); if (hasError) { return ( From 9db847c366b88202ccb29809e06fe88fbc4dc3dd Mon Sep 17 00:00:00 2001 From: ItzCrazyKns <95534749+ItzCrazyKns@users.noreply.github.com> Date: Tue, 15 Oct 2024 16:21:15 +0530 Subject: [PATCH 3/6] feat(library): enhance UI --- ui/app/library/page.tsx | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/ui/app/library/page.tsx b/ui/app/library/page.tsx index 8294fc1..379596c 100644 --- a/ui/app/library/page.tsx +++ b/ui/app/library/page.tsx @@ -1,7 +1,7 @@ 'use client'; import DeleteChat from '@/components/DeleteChat'; -import { formatTimeDifference } from '@/lib/utils'; +import { cn, formatTimeDifference } from '@/lib/utils'; import { BookOpenText, ClockIcon, Delete, ScanEye } from 'lucide-react'; import Link from 'next/link'; import { useEffect, useState } from 'react'; @@ -58,13 +58,12 @@ const Page = () => { ) : (
-
-
+
+
-

- Library -

+

Library

+
{chats.length === 0 && (
@@ -74,10 +73,15 @@ const Page = () => {
)} {chats.length > 0 && ( -
+
{chats.map((chat, i) => (
Date: Tue, 15 Oct 2024 16:21:29 +0530 Subject: [PATCH 4/6] feat(app): lint & beautify --- src/agents/academicSearchAgent.ts | 6 +----- src/routes/models.ts | 2 +- src/routes/search.ts | 8 +++++++- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/agents/academicSearchAgent.ts b/src/agents/academicSearchAgent.ts index 4a10c98..fc95d3c 100644 --- a/src/agents/academicSearchAgent.ts +++ b/src/agents/academicSearchAgent.ts @@ -115,11 +115,7 @@ const createBasicAcademicSearchRetrieverChain = (llm: BaseChatModel) => { const res = await searchSearxng(input, { language: 'en', - engines: [ - 'arxiv', - 'google scholar', - 'pubmed', - ], + engines: ['arxiv', 'google scholar', 'pubmed'], }); const documents = res.results.map( diff --git a/src/routes/models.ts b/src/routes/models.ts index c4f5d40..b5fbe12 100644 --- a/src/routes/models.ts +++ b/src/routes/models.ts @@ -12,7 +12,7 @@ router.get('/', async (req, res) => { const [chatModelProviders, embeddingModelProviders] = await Promise.all([ getAvailableChatModelProviders(), getAvailableEmbeddingModelProviders(), - ]); + ]); Object.keys(chatModelProviders).forEach((provider) => { Object.keys(chatModelProviders[provider]).forEach((model) => { diff --git a/src/routes/search.ts b/src/routes/search.ts index 6684632..70fe228 100644 --- a/src/routes/search.ts +++ b/src/routes/search.ts @@ -121,7 +121,13 @@ router.post('/', async (req, res) => { return res.status(400).json({ message: 'Invalid focus mode' }); } - const emitter = searchHandler(body.query, history, llm, embeddings, body.optimizationMode); + const emitter = searchHandler( + body.query, + history, + llm, + embeddings, + body.optimizationMode, + ); let message = ''; let sources = []; From 7532c436db88ca1caf718048f6da1fef35ab9f0d Mon Sep 17 00:00:00 2001 From: ItzCrazyKns <95534749+ItzCrazyKns@users.noreply.github.com> Date: Tue, 15 Oct 2024 16:23:13 +0530 Subject: [PATCH 5/6] feat(package): bump version --- README.md | 2 +- package.json | 2 +- ui/package.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f66e8b1..c96e1a4 100644 --- a/README.md +++ b/README.md @@ -144,8 +144,8 @@ For more details, check out the full documentation [here](https://github.com/Itz - [x] History Saving features - [x] Introducing various Focus Modes - [x] Adding API support +- [x] Adding Discover - [ ] Finalizing Copilot Mode -- [ ] Adding Discover ## Support Us diff --git a/package.json b/package.json index ab45174..17cbe41 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "perplexica-backend", - "version": "1.9.0-rc3", + "version": "1.9.0", "license": "MIT", "author": "ItzCrazyKns", "scripts": { diff --git a/ui/package.json b/ui/package.json index e5dc677..70a144a 100644 --- a/ui/package.json +++ b/ui/package.json @@ -1,6 +1,6 @@ { "name": "perplexica-frontend", - "version": "1.9.0-rc3", + "version": "1.9.0", "license": "MIT", "author": "ItzCrazyKns", "scripts": { From 3a01eebc040f84ee28310f5129210bffb2cee5ee Mon Sep 17 00:00:00 2001 From: ItzCrazyKns <95534749+ItzCrazyKns@users.noreply.github.com> Date: Tue, 15 Oct 2024 18:04:50 +0530 Subject: [PATCH 6/6] feat(chat): prevent ws not open errors --- package.json | 1 + src/agents/academicSearchAgent.ts | 1 - src/agents/webSearchAgent.ts | 22 ++++++++++++++++++++- src/websocket/connectionManager.ts | 12 ++++++++++++ ui/components/ChatWindow.tsx | 31 +++++++++++++++++------------- yarn.lock | 7 +++++++ 6 files changed, 59 insertions(+), 15 deletions(-) diff --git a/package.json b/package.json index 17cbe41..48efd23 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ "@types/html-to-text": "^9.0.4", "@types/pdf-parse": "^1.1.4", "@types/readable-stream": "^4.0.11", + "@types/ws": "^8.5.12", "drizzle-kit": "^0.22.7", "nodemon": "^3.1.0", "prettier": "^3.2.5", diff --git a/src/agents/academicSearchAgent.ts b/src/agents/academicSearchAgent.ts index fc95d3c..bad4065 100644 --- a/src/agents/academicSearchAgent.ts +++ b/src/agents/academicSearchAgent.ts @@ -167,7 +167,6 @@ const createBasicAcademicSearchAnsweringChain = ( if (optimizationMode === 'speed') { return docsWithContent.slice(0, 15); } else if (optimizationMode === 'balanced') { - console.log('Balanced mode'); const [docEmbeddings, queryEmbedding] = await Promise.all([ embeddings.embedDocuments( docsWithContent.map((doc) => doc.pageContent), diff --git a/src/agents/webSearchAgent.ts b/src/agents/webSearchAgent.ts index 51653a0..1ff3354 100644 --- a/src/agents/webSearchAgent.ts +++ b/src/agents/webSearchAgent.ts @@ -227,7 +227,7 @@ const createBasicWebSearchRetrieverChain = (llm: BaseChatModel) => { The text will be shared inside the \`text\` XML tag, and the query inside the \`query\` XML tag. - + 1. \` Docker is a set of platform-as-a-service products that use OS-level virtualization to deliver software in packages called containers. It was first released in 2013 and is developed by Docker, Inc. Docker is designed to make it easier to create, deploy, and run applications by using containers. @@ -241,6 +241,26 @@ const createBasicWebSearchRetrieverChain = (llm: BaseChatModel) => { Docker is a revolutionary platform-as-a-service product developed by Docker, Inc., that uses container technology to make application deployment more efficient. It allows developers to package their software with all necessary dependencies, making it easier to run in any environment. Released in 2013, Docker has transformed the way applications are built, deployed, and managed. + \` + 2. \` + The theory of relativity, or simply relativity, encompasses two interrelated theories of Albert Einstein: special relativity and general + relativity. However, the word "relativity" is sometimes used in reference to Galilean invariance. The term "theory of relativity" was based + on the expression "relative theory" used by Max Planck in 1906. The theory of relativity usually encompasses two interrelated theories by + Albert Einstein: special relativity and general relativity. Special relativity applies to all physical phenomena in the absence of gravity. + General relativity explains the law of gravitation and its relation to other forces of nature. It applies to the cosmological and astrophysical + realm, including astronomy. + + + + summarize + + + Response: + The theory of relativity, developed by Albert Einstein, encompasses two main theories: special relativity and general relativity. Special + relativity applies to all physical phenomena in the absence of gravity, while general relativity explains the law of gravitation and its + relation to other forces of nature. The theory of relativity is based on the concept of "relative theory," as introduced by Max Planck in + 1906. It is a fundamental theory in physics that has revolutionized our understanding of the universe. + \` Everything below is the actual data you will be working with. Good luck! diff --git a/src/websocket/connectionManager.ts b/src/websocket/connectionManager.ts index 04797c5..d980500 100644 --- a/src/websocket/connectionManager.ts +++ b/src/websocket/connectionManager.ts @@ -78,6 +78,18 @@ export const handleConnection = async ( ws.close(); } + const interval = setInterval(() => { + if (ws.readyState === ws.OPEN) { + ws.send( + JSON.stringify({ + type: 'signal', + data: 'open', + }), + ); + clearInterval(interval); + } + }, 5); + ws.on( 'message', async (message) => diff --git a/ui/components/ChatWindow.tsx b/ui/components/ChatWindow.tsx index 6a56f7e..a80a5c9 100644 --- a/ui/components/ChatWindow.tsx +++ b/ui/components/ChatWindow.tsx @@ -171,11 +171,22 @@ const useSocket = ( } }, 10000); - ws.onopen = () => { - console.log('[DEBUG] open'); - clearTimeout(timeoutId); - setIsWSReady(true); - }; + ws.addEventListener('message', (e) => { + const data = JSON.parse(e.data); + if (data.type === 'signal' && data.data === 'open') { + const interval = setInterval(() => { + if (ws.readyState === 1) { + setIsWSReady(true); + clearInterval(interval); + } + }, 5); + clearTimeout(timeoutId); + console.log('[DEBUG] opened'); + } + if (data.type === 'error') { + toast.error(data.data); + } + }); ws.onerror = () => { clearTimeout(timeoutId); @@ -189,13 +200,6 @@ const useSocket = ( console.log('[DEBUG] closed'); }; - ws.addEventListener('message', (e) => { - const data = JSON.parse(e.data); - if (data.type === 'error') { - toast.error(data.data); - } - }); - setWs(ws); }; @@ -325,6 +329,7 @@ const ChatWindow = ({ id }: { id?: string }) => { useEffect(() => { if (isMessagesLoaded && isWSReady) { setIsReady(true); + console.log('[DEBUG] ready'); } }, [isMessagesLoaded, isWSReady]); @@ -477,7 +482,7 @@ const ChatWindow = ({ id }: { id?: string }) => { sendMessage(initialMessage); } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [isReady, initialMessage, ws?.readyState]); + }, [ws?.readyState, isReady, initialMessage, isWSReady]); if (hasError) { return ( diff --git a/yarn.lock b/yarn.lock index 1c34e1d..deb35ea 100644 --- a/yarn.lock +++ b/yarn.lock @@ -690,6 +690,13 @@ resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-9.0.8.tgz#7545ba4fc3c003d6c756f651f3bf163d8f0f29ba" integrity sha512-jg+97EGIcY9AGHJJRaaPVgetKDsrTgbRjQ5Msgjh/DQKEFl0DtyRr/VCOyD1T2R1MNeWPK/u7JoGhlDZnKBAfA== +"@types/ws@^8.5.12": + version "8.5.12" + resolved "https://registry.yarnpkg.com/@types/ws/-/ws-8.5.12.tgz#619475fe98f35ccca2a2f6c137702d85ec247b7e" + integrity sha512-3tPRkv1EtkDpzlgyKyI8pGsGZAGPEaXeu0DOj5DI25Ja91bdAYddYHbADRYVrZMRbfW+1l5YwXVDKohDJNQxkQ== + dependencies: + "@types/node" "*" + "@xenova/transformers@^2.17.1": version "2.17.1" resolved "https://registry.yarnpkg.com/@xenova/transformers/-/transformers-2.17.1.tgz#712f7a72c76c8aa2075749382f83dc7dd4e5a9a5"