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 1e5fc92..12727ec 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": { @@ -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 4a10c98..bad4065 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( @@ -171,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/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 a16cb1e..0713eb6 100644 --- a/src/routes/index.ts +++ b/src/routes/index.ts @@ -7,6 +7,7 @@ import suggestionsRouter from './suggestions'; import chatsRouter from './chats'; import settingsRouter from './settings'; import searchRouter from './search'; +import discoverRouter from './discover'; const router = express.Router(); @@ -18,5 +19,6 @@ router.use('/suggestions', suggestionsRouter); router.use('/chats', chatsRouter); router.use('/settings', settingsRouter); router.use('/search', searchRouter); +router.use('/discover', discoverRouter); export default router; 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 = []; 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/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; 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) => (
{ - console.log('[DEBUG] open'); - reconnectTimeout.current = 0; - reconnectAttempts.current = 0; - 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) { + reconnectTimeout.current = 0;setIsWSReady(true); + clearInterval(interval); + } + }, 5); + clearTimeout(timeoutId); + reconnectTimeout.current = 0; + reconnectAttempts.current = 0; + console.log('[DEBUG] opened'); + } + if (data.type === 'error') { + toast.error(data.data); + } + }); ws.onerror = () => { clearTimeout(timeoutId); @@ -217,13 +228,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); }; @@ -365,6 +369,7 @@ const ChatWindow = ({ id }: { id?: string }) => { useEffect(() => { if (isMessagesLoaded && isWSReady) { setIsReady(true); + console.log('[DEBUG] ready'); } }, [isMessagesLoaded, isWSReady]); @@ -513,11 +518,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]); + }, [ws?.readyState, isReady, initialMessage, isWSReady]); if (hasError) { return ( 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": { 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"