Elffuss BraidHub

kikocis/lancedb public

main · 4.9 KiBRenderedRawPermalink
1# YouTube transcript QA bot with NodeJS
2
3## use LanceDB's Javascript API and OpenAI to build a QA bot for YouTube transcripts
4
5<img id="splash" width="400" alt="nodejs" src="https://github.com/lancedb/lancedb/assets/917119/3a140e75-bf8e-438a-a1e4-af14a72bcf98">
6
7This Q&A bot will allow you to search through youtube transcripts using natural language! We'll introduce how to use LanceDB's Javascript API to store and manage your data easily.
8
9```bash
10npm install vectordb
11```
12
13## Download the data
14
15For this example, we're using a sample of a HuggingFace dataset that contains YouTube transcriptions: `jamescalam/youtube-transcriptions`. Download and extract this file under the `data` folder:
16
17```bash
18wget -c https://eto-public.s3.us-west-2.amazonaws.com/datasets/youtube_transcript/youtube-transcriptions_sample.jsonl
19```
20
21## Prepare Context
22
23Each item in the dataset contains just a short chunk of text. We'll need to merge a bunch of these chunks together on a rolling basis. For this demo, we'll look back 20 records to create a more complete context for each sentence.
24
25First, we need to read and parse the input file.
26
27```javascript
28const lines = (await fs.readFile(INPUT_FILE_NAME, 'utf-8'))
29 .toString()
30 .split('\n')
31 .filter(line => line.length > 0)
32 .map(line => JSON.parse(line))
33
34const data = contextualize(lines, 20, 'video_id')
35```
36
37The contextualize function groups the transcripts by video_id and then creates the expanded context for each item.
38
39```javascript
40function contextualize (rows, contextSize, groupColumn) {
41 const grouped = []
42 rows.forEach(row => {
43 if (!grouped[row[groupColumn]]) {
44 grouped[row[groupColumn]] = []
45 }
46 grouped[row[groupColumn]].push(row)
47 })
48
49 const data = []
50 Object.keys(grouped).forEach(key => {
51 for (let i = 0; i < grouped[key].length; i++) {
52 const start = i - contextSize > 0 ? i - contextSize : 0
53 grouped[key][i].context = grouped[key].slice(start, i + 1).map(r => r.text).join(' ')
54 }
55 data.push(...grouped[key])
56 })
57 return data
58}
59```
60
61## Create the LanceDB Table
62
63To load our data into LanceDB, we need to create embedding (vectors) for each item. For this example, we will use the OpenAI embedding functions, which have a native integration with LanceDB.
64
65```javascript
66// You need to provide an OpenAI API key, here we read it from the OPENAI_API_KEY environment variable
67const apiKey = process.env.OPENAI_API_KEY
68// The embedding function will create embeddings for the 'context' column
69const embedFunction = new lancedb.OpenAIEmbeddingFunction('context', apiKey)
70// Connects to LanceDB
71const db = await lancedb.connect('data/youtube-lancedb')
72const tbl = await db.createTable('vectors', data, embedFunction)
73```
74
75## Create and answer the prompt
76
77We will accept questions in natural language and use our corpus stored in LanceDB to answer them. First, we need to set up the OpenAI client:
78
79```javascript
80const configuration = new Configuration({ apiKey })
81const openai = new OpenAIApi(configuration)
82```
83
84Then we can prompt questions and use LanceDB to retrieve the three most relevant transcripts for this prompt.
85
86```javascript
87const query = await rl.question('Prompt: ')
88const results = await tbl
89 .search(query)
90 .select(['title', 'text', 'context'])
91 .limit(3)
92 .execute()
93```
94
95The query and the transcripts' context are appended together in a single prompt:
96
97```javascript
98function createPrompt (query, context) {
99 let prompt =
100 'Answer the question based on the context below.\n\n' +
101 'Context:\n'
102
103 // need to make sure our prompt is not larger than max size
104 prompt = prompt + context.map(c => c.context).join('\n\n---\n\n').substring(0, 3750)
105 prompt = prompt + `\n\nQuestion: ${query}\nAnswer:`
106 return prompt
107}
108```
109
110We can now use the OpenAI Completion API to process our custom prompt and give us an answer.
111
112```javascript
113const response = await openai.createCompletion({
114 model: 'text-davinci-003',
115 prompt: createPrompt(query, results),
116 max_tokens: 400,
117 temperature: 0,
118 top_p: 1,
119 frequency_penalty: 0,
120 presence_penalty: 0
121})
122console.log(response.data.choices[0].text)
123```
124
125## Let's put it all together now
126
127Now we can provide queries and have them answered based on your local LanceDB data.
128
129```bash
130Prompt: who was the 12th person on the moon and when did they land?
131 The 12th person on the moon was Harrison Schmitt and he landed on December 11, 1972.
132Prompt: Which training method should I use for sentence transformers when I only have pairs of related sentences?
133 NLI with multiple negative ranking loss.
134```
135
136## That's a wrap
137
138In this example, you learned how to use LanceDB to store and query embedding representations of your local data. The complete example code is on [GitHub](https://github.com/lancedb/lancedb/tree/main/node/examples), and you can also download the LanceDB dataset using [this link](https://eto-public.s3.us-west-2.amazonaws.com/datasets/youtube_transcript/youtube-lancedb.zip).
139