-
Notifications
You must be signed in to change notification settings - Fork 0
/
qa.js
73 lines (64 loc) · 2.51 KB
/
qa.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { openai } from "./openai.js";
import 'dotenv/config';
import { Document } from 'langchain/document';
import { MemoryVectorStore } from 'langchain/vectorstores/memory';
import { OpenAIEmbeddings } from '@langchain/openai';
import { CharacterTextSplitter } from 'langchain/text_splitter';
import { PDFLoader } from '@langchain/community/document_loaders/fs/pdf';
import { YoutubeLoader } from '@langchain/community/document_loaders/web/youtube';
const question = process.argv[2] || "hi";
const video = `https://www.youtube.com/watch?v=UA3HxaaTC8w`;
const createStore = (docs) => MemoryVectorStore.fromDocuments(docs, new OpenAIEmbeddings());
const docsFromYTVideo = (video) => {
const loader = YoutubeLoader.createFromUrl(video, {
language: 'en',
addVideoInfo: true,
});
return loader.loadAndSplit(
new CharacterTextSplitter({
separator: ' ',
chunkSize: 2500,
chunkOverlap: 100,
})
);
};
const docsFromPDF = () => {
const loader = new PDFLoader('/Users/monicagullapalli/Documents/Frontend Masters/xbox.pdf');
return loader.loadAndSplit(
new CharacterTextSplitter({
separator: '. ',
chunkSize: 2500,
chunkOverlap: 200,
})
);
};
const loadStore = async () => {
const videoDocs = await docsFromYTVideo(video);
const pdfDocs = await docsFromPDF();
return createStore([...videoDocs, ...pdfDocs]);
};
export const query = async (inputQuestion) => {
const store = await loadStore();
const results = await store.similaritySearch(inputQuestion, 2);
const response = await openai.chat.completions.create({
model: 'gpt-4',
temperature: 0,
messages: [
{
role: 'system',
content: 'You are an AI assistant. Answer questions to your best ability.',
},
{
role: 'user',
content: `Answer the following question using the provided context. If you cannot answer the question with the context, don't lie and make up stuff. Just say you need more context.
Question: ${inputQuestion}
Context: ${results.map((r) => r.pageContent).join('\n')}`,
}
]
});
return `Answer: ${response.choices[0].message.content}\n\nSources: ${results.map((r) => r.metadata.source).join(', ')}`;
};
// For testing purposes, you can use the following code block
if (import.meta.url === `file://${process.argv[1]}`) {
query(question).then(console.log);
}