Skip to content

Commit

Permalink
Merge pull request #290 from ItzCrazyKns/canary
Browse files Browse the repository at this point in the history
  • Loading branch information
ItzCrazyKns authored Jul 30, 2024
2 parents c62e7f0 + 61dfeb8 commit 96f67c7
Show file tree
Hide file tree
Showing 8 changed files with 398 additions and 20 deletions.
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "perplexica-backend",
"version": "1.8.1",
"version": "1.9.0-rc1",
"license": "MIT",
"author": "ItzCrazyKns",
"scripts": {
Expand All @@ -15,6 +15,8 @@
"@types/better-sqlite3": "^7.6.10",
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/html-to-text": "^9.0.4",
"@types/pdf-parse": "^1.1.4",
"@types/readable-stream": "^4.0.11",
"drizzle-kit": "^0.22.7",
"nodemon": "^3.1.0",
Expand All @@ -36,7 +38,9 @@
"dotenv": "^16.4.5",
"drizzle-orm": "^0.31.2",
"express": "^4.19.2",
"html-to-text": "^9.0.5",
"langchain": "^0.1.30",
"pdf-parse": "^1.1.1",
"winston": "^3.13.0",
"ws": "^8.17.1",
"zod": "^3.22.4"
Expand Down
146 changes: 128 additions & 18 deletions src/agents/webSearchAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,47 @@ import formatChatHistoryAsString from '../utils/formatHistory';
import eventEmitter from 'events';
import computeSimilarity from '../utils/computeSimilarity';
import logger from '../utils/logger';
import LineListOutputParser from '../lib/outputParsers/listLineOutputParser';
import { getDocumentsFromLinks } from '../lib/linkDocument';
import LineOutputParser from '../lib/outputParsers/lineOutputParser';

const basicSearchRetrieverPrompt = `
You will be given a conversation below and a follow up question. You need to rephrase the follow-up question if needed so it is a standalone question that can be used by the LLM to search the web for information.
If it is a writing task or a simple hi, hello rather than a question, you need to return \`not_needed\` as the response.
If the question contains some links and asks to answer from those links or even if they don't you need to return the links inside 'links' XML block and the question inside 'question' XML block. If there are no links then you need to return the question without any XML block.
If the user asks to summarrize the content from some links you need to return \`Summarize\` as the question inside the 'question' XML block and the links inside the 'links' XML block.
Example:
1. Follow up question: What is the capital of France?
Rephrased: Capital of france
Rephrased question: \`Capital of france\`
2. Follow up question: What is the population of New York City?
Rephrased: Population of New York City
Rephrased question: \`Population of New York City\`
3. Follow up question: What is Docker?
Rephrased: What is Docker
Rephrased question: \`What is Docker\`
4. Follow up question: Can you tell me what is X from https://example.com
Rephrased question: \`
<question>
Can you tell me what is X?
</question>
<links>
https://example.com
</links>
\`
5. Follow up question: Summarize the content from https://example.com
Rephrased question: \`
<question>
Summarize
</question>
<links>
https://example.com
</links>
\`
Conversation:
{chat_history}
Expand All @@ -42,11 +69,13 @@ Rephrased question:
`;

const basicWebSearchResponsePrompt = `
You are Perplexica, an AI model who is expert at searching the web and answering user's queries.
You are Perplexica, an AI model who is expert at searching the web and answering user's queries. You are also an expert at summarizing web pages or documents and searching for content in them.
Generate a response that is informative and relevant to the user's query based on provided context (the context consits of search results containing a brief description of the content of that page).
You must use this context to answer the user's query in the best way possible. Use an unbaised and journalistic tone in your response. Do not repeat the text.
You must not tell the user to open any link or visit any website to get the answer. You must provide the answer in the response itself. If the user asks for links you can provide them.
If the query contains some links and the user asks to answer from those links you will be provided the entire content of the page inside the \`context\` XML block. You can then use this content to answer the user's query.
If the user asks to summarize content from some links, you will be provided the entire content of the page inside the \`context\` XML block. You can then use this content to summarize the text. The content provided inside the \`context\` block will be already summarized by another model so you just need to use that content to answer the user's query.
Your responses should be medium to long in length be informative and relevant to the user's query. You can use markdowns to format your response. You should use bullet points to list the information. Make sure the answer is not short and is informative.
You have to cite the answer using [number] notation. You must cite the sentences with their relevent context number. You must cite each and every part of the answer so the user can know where the information is coming from.
Place these citations at the end of that particular sentence. You can cite the same sentence multiple times if it is relevant to the user's query like [number1][number2].
Expand All @@ -59,7 +88,7 @@ const basicWebSearchResponsePrompt = `
{context}
</context>
If you think there's nothing relevant in the search results, you can say that 'Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?'.
If you think there's nothing relevant in the search results, you can say that 'Hmm, sorry I could not find any relevant information on this topic. Would you like me to search again or ask something else?'. You do not need to do this for summarization tasks.
Anything between the \`context\` is retrieved from a search engine and is not a part of the conversation with the user. Today's date is ${new Date().toISOString()}
`;

Expand Down Expand Up @@ -112,23 +141,100 @@ const createBasicWebSearchRetrieverChain = (llm: BaseChatModel) => {
return { query: '', docs: [] };
}

const res = await searchSearxng(input, {
language: 'en',
const linksOutputParser = new LineListOutputParser({
key: 'links',
});

const documents = res.results.map(
(result) =>
new Document({
pageContent: result.content,
const questionOutputParser = new LineOutputParser({
key: 'question',
});

const links = await linksOutputParser.parse(input);
let question = await questionOutputParser.parse(input);

if (links.length > 0) {
if (question.length === 0) {
question = 'Summarize';
}

let docs = []

const linkDocs = await getDocumentsFromLinks({ links });

const docGroups: Document[] = [];

linkDocs.map((doc) => {
const URLDocExists = docGroups.find((d) => d.metadata.url === doc.metadata.url && d.metadata.totalDocs < 10);

if (!URLDocExists) {
docGroups.push({
...doc,
metadata: {
...doc.metadata,
totalDocs: 1
}
});
}

const docIndex = docGroups.findIndex((d) => d.metadata.url === doc.metadata.url && d.metadata.totalDocs < 10);

if (docIndex !== -1) {
docGroups[docIndex].pageContent = docGroups[docIndex].pageContent + `\n\n` + doc.pageContent;
docGroups[docIndex].metadata.totalDocs += 1;
}
})

await Promise.all(docGroups.map(async (doc) => {
const res = await llm.invoke(`
You are a text summarizer. You need to summarize the text provided inside the \`text\` XML block.
You need to summarize the text into 1 or 2 sentences capturing the main idea of the text.
You need to make sure that you don't miss any point while summarizing the text.
You will also be given a \`query\` XML block which will contain the query of the user. Try to answer the query in the summary from the text provided.
If the query says Summarize then you just need to summarize the text without answering the query.
Only return the summarized text without any other messages, text or XML block.
<query>
${question}
</query>
<text>
${doc.pageContent}
</text>
Make sure to answer the query in the summary.
`);

const document = new Document({
pageContent: res.content as string,
metadata: {
title: result.title,
url: result.url,
...(result.img_src && { img_src: result.img_src }),
title: doc.metadata.title,
url: doc.metadata.url,
},
}),
);

return { query: input, docs: documents };
})

docs.push(document)
}))

return { query: question, docs: docs };
} else {
const res = await searchSearxng(input, {
language: 'en',
});

const documents = res.results.map(
(result) =>
new Document({
pageContent: result.content,
metadata: {
title: result.title,
url: result.url,
...(result.img_src && { img_src: result.img_src }),
},
}),
);

return { query: input, docs: documents };
}
}),
]);
};
Expand Down Expand Up @@ -156,6 +262,10 @@ const createBasicWebSearchAnsweringChain = (
return docs;
}

if (query === 'Summarize') {
return docs;
}

const docsWithContent = docs.filter(
(doc) => doc.pageContent && doc.pageContent.length > 0,
);
Expand Down
8 changes: 8 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,11 @@ server.listen(port, () => {
});

startWebSocketServer(server);

process.on('uncaughtException', (err, origin) => {
logger.error(`Uncaught Exception at ${origin}: ${err}`)
})

process.on('unhandledRejection', (reason, promise) => {
logger.error(`Unhandled Rejection at: ${promise}, reason: ${reason}`)
})
81 changes: 81 additions & 0 deletions src/lib/linkDocument.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import axios from 'axios';
import { htmlToText } from 'html-to-text'
import { RecursiveCharacterTextSplitter } from 'langchain/text_splitter';
import { Document } from '@langchain/core/documents';
import pdfParse from 'pdf-parse'

export const getDocumentsFromLinks = async ({ links }: { links: string[] }) => {
const splitter = new RecursiveCharacterTextSplitter();

let docs: Document[] = [];

await Promise.all(
links.map(async (link) => {
link =
link.startsWith('http://') || link.startsWith('https://')
? link
: `https://${link}`;

const res = await axios.get(link, {
responseType: 'arraybuffer',
});

const isPdf = res.headers['content-type'] === 'application/pdf';

if (isPdf) {
const pdfText = await pdfParse(res.data)
const parsedText = pdfText.text
.replace(/(\r\n|\n|\r)/gm, ' ')
.replace(/\s+/g, ' ')
.trim();

const splittedText = await splitter.splitText(parsedText);
const title = 'PDF Document'

const linkDocs = splittedText.map((text) => {
return new Document({
pageContent: text,
metadata: {
title: title,
url: link,
},
});
});

docs.push(...linkDocs);
return;
}

const parsedText = htmlToText(res.data.toString('utf8'), {
selectors: [
{
selector: 'a',
options: {
ignoreHref: true,
}
},
]
})
.replace(/(\r\n|\n|\r)/gm, ' ')
.replace(/\s+/g, ' ')
.trim();

const splittedText = await splitter.splitText(parsedText);
const title = res.data.toString('utf8').match(/<title>(.*?)<\/title>/)?.[1];

const linkDocs = splittedText.map((text) => {
return new Document({
pageContent: text,
metadata: {
title: title || link,
url: link,
},
});
});

docs.push(...linkDocs);
}),
);

return docs;
};
46 changes: 46 additions & 0 deletions src/lib/outputParsers/lineOutputParser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { BaseOutputParser } from '@langchain/core/output_parsers';

interface LineOutputParserArgs {
key?: string;
}

class LineOutputParser extends BaseOutputParser<string> {
private key = 'questions';

constructor(args?: LineOutputParserArgs) {
super();
this.key = args.key ?? this.key;
}

static lc_name() {
return 'LineOutputParser';
}

lc_namespace = ['langchain', 'output_parsers', 'line_output_parser'];

async parse(text: string): Promise<string> {
const regex = /^(\s*(-|\*|\d+\.\s|\d+\)\s|\u2022)\s*)+/;
const startKeyIndex = text.indexOf(`<${this.key}>`);
const endKeyIndex = text.indexOf(`</${this.key}>`);

if (startKeyIndex === -1 || endKeyIndex === -1) {
return '';
}

const questionsStartIndex =
startKeyIndex === -1 ? 0 : startKeyIndex + `<${this.key}>`.length;
const questionsEndIndex = endKeyIndex === -1 ? text.length : endKeyIndex;
const line = text
.slice(questionsStartIndex, questionsEndIndex)
.trim()
.replace(regex, '');

return line;
}

getFormatInstructions(): string {
throw new Error('Not implemented.');
}
}

export default LineOutputParser;
5 changes: 5 additions & 0 deletions src/lib/outputParsers/listLineOutputParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ class LineListOutputParser extends BaseOutputParser<string[]> {
const regex = /^(\s*(-|\*|\d+\.\s|\d+\)\s|\u2022)\s*)+/;
const startKeyIndex = text.indexOf(`<${this.key}>`);
const endKeyIndex = text.indexOf(`</${this.key}>`);

if (startKeyIndex === -1 || endKeyIndex === -1) {
return [];
}

const questionsStartIndex =
startKeyIndex === -1 ? 0 : startKeyIndex + `<${this.key}>`.length;
const questionsEndIndex = endKeyIndex === -1 ? text.length : endKeyIndex;
Expand Down
2 changes: 1 addition & 1 deletion ui/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "perplexica-frontend",
"version": "1.8.1",
"version": "1.9.0-rc1",
"license": "MIT",
"author": "ItzCrazyKns",
"scripts": {
Expand Down
Loading

0 comments on commit 96f67c7

Please sign in to comment.