Elffuss BraidHub

kikocis/lancedb public

main · 4.0 KiBRawPermalink
1// Copyright 2023 Lance Developers.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15'use strict'
16
17const lancedb = require('vectordb')
18const fs = require('fs/promises')
19const readline = require('readline/promises')
20const { stdin: input, stdout: output } = require('process')
21const { Configuration, OpenAIApi } = require('openai')
22
23// Download file from XYZ
24const INPUT_FILE_NAME = 'data/youtube-transcriptions_sample.jsonl';
25
26(async () => {
27 // You need to provide an OpenAI API key, here we read it from the OPENAI_API_KEY environment variable
28 const apiKey = process.env.OPENAI_API_KEY
29 // The embedding function will create embeddings for the 'context' column
30 const embedFunction = new lancedb.OpenAIEmbeddingFunction('context', apiKey)
31
32 // Connects to LanceDB
33 const db = await lancedb.connect('data/youtube-lancedb')
34
35 // Open the vectors table or create one if it does not exist
36 let tbl
37 if ((await db.tableNames()).includes('vectors')) {
38 tbl = await db.openTable('vectors', embedFunction)
39 } else {
40 tbl = await createEmbeddingsTable(db, embedFunction)
41 }
42
43 // Use OpenAI Completion API to generate and answer based on the context that LanceDB provides
44 const configuration = new Configuration({ apiKey })
45 const openai = new OpenAIApi(configuration)
46 const rl = readline.createInterface({ input, output })
47 try {
48 while (true) {
49 const query = await rl.question('Prompt: ')
50 const results = await tbl
51 .search(query)
52 .select(['title', 'text', 'context'])
53 .limit(3)
54 .execute()
55
56 // console.table(results)
57
58 const response = await openai.createCompletion({
59 model: 'text-davinci-003',
60 prompt: createPrompt(query, results),
61 max_tokens: 400,
62 temperature: 0,
63 top_p: 1,
64 frequency_penalty: 0,
65 presence_penalty: 0
66 })
67 console.log(response.data.choices[0].text)
68 }
69 } catch (err) {
70 console.log('Error: ', err)
71 } finally {
72 rl.close()
73 }
74 process.exit(1)
75})()
76
77async function createEmbeddingsTable (db, embedFunction) {
78 console.log(`Creating embeddings from ${INPUT_FILE_NAME}`)
79 // read the input file into a JSON array, skipping empty lines
80 const lines = (await fs.readFile(INPUT_FILE_NAME, 'utf-8'))
81 .toString()
82 .split('\n')
83 .filter(line => line.length > 0)
84 .map(line => JSON.parse(line))
85
86 const data = contextualize(lines, 20, 'video_id')
87 return await db.createTable('vectors', data, embedFunction)
88}
89
90// Each transcript has a small text column, we include previous transcripts in order to
91// have more context information when creating embeddings
92function contextualize (rows, contextSize, groupColumn) {
93 const grouped = []
94 rows.forEach(row => {
95 if (!grouped[row[groupColumn]]) {
96 grouped[row[groupColumn]] = []
97 }
98 grouped[row[groupColumn]].push(row)
99 })
100
101 const data = []
102 Object.keys(grouped).forEach(key => {
103 for (let i = 0; i < grouped[key].length; i++) {
104 const start = i - contextSize > 0 ? i - contextSize : 0
105 grouped[key][i].context = grouped[key].slice(start, i + 1).map(r => r.text).join(' ')
106 }
107 data.push(...grouped[key])
108 })
109 return data
110}
111
112// Creates a prompt by aggregating all relevant contexts
113function createPrompt (query, context) {
114 let prompt =
115 'Answer the question based on the context below.\n\n' +
116 'Context:\n'
117
118 // need to make sure our prompt is not larger than max size
119 prompt = prompt + context.map(c => c.context).join('\n\n---\n\n').substring(0, 3750)
120 prompt = prompt + `\n\nQuestion: ${query}\nAnswer:`
121 return prompt
122}