-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
405 lines (349 loc) · 13.6 KB
/
server.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import express from 'express'
import dotenv from 'dotenv'
import cors from 'cors'
import OpenAI from 'openai'
import crypto from 'crypto'
import { YoutubeLoader } from 'langchain/document_loaders/web/youtube'
import { YoutubeTranscript } from 'youtube-transcript'
import { ChatOpenAI } from '@langchain/openai'
import { RecursiveCharacterTextSplitter } from 'langchain/text_splitter'
import { loadSummarizationChain } from 'langchain/chains'
import { HNSWLib } from '@langchain/community/vectorstores/hnswlib'
import { OpenAIEmbeddings } from '@langchain/openai'
import { PromptTemplate } from '@langchain/core/prompts'
import { RunnableSequence } from '@langchain/core/runnables'
import { StringOutputParser } from '@langchain/core/output_parsers'
import { formatDocumentsAsString } from 'langchain/util/document'
import { z } from 'zod'
import { zodToJsonSchema } from 'zod-to-json-schema'
import { ChatPromptTemplate } from '@langchain/core/prompts'
import { JsonOutputToolsParser } from 'langchain/output_parsers'
import { ChatGoogleGenerativeAI } from '@langchain/google-genai'
dotenv.config()
const app = express()
app.use(cors())
app.use(express.json())
const PORT = 3000
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`)
})
const openAIApiKey = process.env.OPENAI_KEY
const googleGeminiApiKey = process.env.GEMINI_API_KEY
app.post('/getyoutubetranscript', async (req, res) => {
try {
const youtubeUrl = req.body.youtubeUrl ?? null
if (!youtubeUrl.includes('youtube')) {
res.status(403).send('Not a youtube url link')
}
const loader = YoutubeLoader.createFromUrl(
'https://www.youtube.com/watch?v=cvWPlQLH-bg&ab_channel=PiersMorganUncensored',
{
language: 'en',
addVideoInfo: true,
}
)
const docs = await loader.load()
res.status(200).send({ docs })
} catch (error) {
console.error('Error:', error)
res.status(500).send('An error occurred')
}
})
app.post('/gettimestamptranscript', async (req, res) => {
try {
const youtubeUrl = req.body.youtubeUrl ?? null
YoutubeTranscript.fetchTranscript(youtubeUrl)
.then(result => {
res.status(200).send({ result })
})
.catch(error => {
res.status(500).send('Internal Server Error: ' + error)
})
} catch (error) {
console.error('Error:', error)
res.status(500).send('An error occurred')
}
})
app.post('/chatwithytvideo', async (req, res) => {
const transcript = req.body.transcript ?? ''
//add var for title
const modelName = req.body.model ?? 'gpt-3.5-turbo-0125'
const chatHistory = req.body.chatHistory ?? []
const userPrompt = req.body.userPrompt ?? []
try {
//Uncomment this if you want to use openAI instead of Google
const langChainModelOpenAI = new ChatOpenAI({
openAIApiKey,
modelName,
maxTokens: 125,
temperature: 0.2,
})
// const langChainModelGoogle = new ChatGoogleGenerativeAI({
// apiKey: googleGeminiApiKey,
// modelName: 'gemini-pro',
// maxOutputTokens: 125,
// temperature: 0.2,
// })
const textSplitter = new RecursiveCharacterTextSplitter({
chunkSize: 1000,
})
const docs = await textSplitter.createDocuments([transcript])
const vectorStore = await HNSWLib.fromDocuments(
docs,
new OpenAIEmbeddings({ openAIApiKey })
)
const retriever = vectorStore.asRetriever()
const formatChatHistoryAsString = chatHistory => {
return chatHistory
.map(
interaction => `Human: ${interaction.human}\nAI: ${interaction.ai}`
)
.join('\n\n')
}
const questionPrompt = PromptTemplate.fromTemplate(
`You are a Youtube Video AI Assistant. The context you are given is the transcript of the video
you are answering questions about. Use the transcript information to answer the question with relevant
information, if you dont know the answer just say "I am not sure".
----------------
CONTEXT: {context}
----------------
CHAT HISTORY: {chatHistory}
----------------
QUESTION: {question}
----------------
Helpful Answer:`
)
// Create a sequence of operations to be performed in order to generate the answer
const chain = RunnableSequence.from([
{
// The first operation is to extract the question from the input
question: input => input.question,
// The second operation is to format the chat history as a string
chatHistory: input =>
formatChatHistoryAsString(input.chatHistory || []) ?? '',
// The third operation is to retrieve relevant documents based on the question and format them as a string
context: async input => {
const relevantDocs = await retriever.getRelevantDocuments(
input.question
)
const serialized = formatDocumentsAsString(relevantDocs)
return serialized
},
},
// The fourth operation is to generate the question prompt
questionPrompt,
// The fifth operation is to use the model to generate the answer
langChainModelOpenAI,
// The final operation is to parse the output into a string
new StringOutputParser(),
])
const answer = await chain.invoke({
chatHistory: chatHistory,
question: userPrompt,
})
res.status(200).send({ summary: answer })
} catch (error) {
console.error('Error:', error)
res.status(500).send('An error occurred')
}
})
app.post('/getKeyWords', async (req, res) => {
const transcript = req.body.transcript ?? ''
const EXTRACTION_TEMPLATE = `Given the importance of focusing on the most relevant and impactful keywords for a YouTube video description, your task is to extract these keywords with an emphasis on precision and relevance. It's essential to identify keywords that truly resonate with the video's content, avoiding generic or overly broad terms. The goal is to select keywords that are directly tied to the video's main themes and messages, ensuring they are not only accurate but also significantly enhance the video's discoverability and alignment with the intended audience's interests.`
const prompt = ChatPromptTemplate.fromMessages([
['system', EXTRACTION_TEMPLATE],
['human', '{input}'],
])
const getKeyWordsSchema = z.object({
keyWords: z
.array(
z
.string()
.max(3, 'Each keyword should be a concise term, up to 3 words')
.nonempty('Keywords must be meaningful and cannot be empty')
)
.min(
3,
'A minimum of 3 keywords is required to capture the essence of the video'
)
.max(5, 'Limit to 5 keywords to maintain focus and relevance')
.describe(
"Select keywords that are closely related to the video's content, ensuring they are specific and relevant"
),
})
try {
const model = new ChatOpenAI({
openAIApiKey,
modelName: 'gpt-3.5-turbo-0125',
temperature: 0.7,
}).bind({
tools: [
{
type: 'function',
function: {
name: 'getKeyWordsSchema',
description:
'Extract highly relevant keywords from a transcript for generating a YouTube video description',
parameters: zodToJsonSchema(getKeyWordsSchema),
},
},
],
})
const parser = new JsonOutputToolsParser()
const chain = prompt.pipe(model).pipe(parser)
const response = await chain.invoke({
input: `Transcript: ${transcript}. Identify the most specific and relevant keywords that accurately reflect the video's main themes and messages, focusing on precision and relevance.`,
})
res.status(200).send(response[0].args.keyWords)
} catch (error) {
console.error('Error:', error)
res.status(500).send('An error occurred')
}
})
app.post('/custominstructions', async (req, res) => {
const transcript = req.body.transcript ?? ''
const category = req.body.category ?? ''
const tones = req.body.tones ?? []
const keyTerms = req.body.keyTerms ?? []
const EXTRACTION_TEMPLATE = `Your task is to create custom instructions for generating a YouTube video description. These instructions should guide the language model to focus on precision and relevance, ensuring the inclusion of keywords that are most impactful and directly tied to the video's main themes and messages. The aim is to craft a description that enhances the video's discoverability while accurately reflecting its content and resonating with the intended audience. Avoid generic or overly broad terms to maintain specificity and relevance.`
const prompt = ChatPromptTemplate.fromMessages([
['system', EXTRACTION_TEMPLATE],
['human', '{input}'],
])
const createCustomInstructionsSchema = z.object({
customInstructions: z
.array(
z.object({
instructionNumber: z.number(),
instruction: z.string().nonempty('Instruction cannot be empty'),
})
)
.min(1, 'At least one instruction is required'),
})
try {
const model = new ChatOpenAI({
openAIApiKey,
modelName: 'gpt-3.5-turbo-0125',
temperature: 0.7,
}).bind({
tools: [
{
type: 'function',
function: {
name: 'createCustomInstructions',
description:
'Generate concise and detailed instructions for creating a YouTube video description based on the transcript, tone, category, and key terms',
parameters: zodToJsonSchema(createCustomInstructionsSchema),
},
},
],
})
const parser = new JsonOutputToolsParser()
const chain = prompt.pipe(model).pipe(parser)
const response = await chain.invoke({
input: `Transcript: ${transcript}. Tone: ${tones.join(
', '
)}. Category: ${category}. Key Terms: ${keyTerms.join(
', '
)}. Create concise and detailed instructions for a YouTube video description.`,
})
const formattedResponse = response
.map(item =>
item.args.customInstructions
.map(
instruction =>
`${instruction.instructionNumber}. ${instruction.instruction}`
)
.join('\n')
)
.join('\n')
res.status(200).send(formattedResponse)
} catch (error) {
console.error('Error:', error)
res.status(500).send('An error occurred')
}
})
const parametersStore = {}
app.post('/api/getYTDescription', (req, res) => {
const parameters = req.body
const token = crypto.randomBytes(20).toString('hex')
parametersStore[token] = parameters
res.json({ token })
})
app.get('/getCustomDescription', async (req, res) => {
const token = req.query.token
const parameters = parametersStore[token]
if (!parameters) {
res.status(404).send('Session not found')
return
}
let result
res.setHeader('Content-Type', 'text/event-stream')
res.setHeader('Cache-Control', 'no-cache')
res.setHeader('Connection', 'keep-alive')
try {
let transcriptSummary
if (!parameters.fullTranscript) {
transcriptSummary = await summarizeTranscript(parameters.transcript)
}
const SYSTEM_TEMPLATE = `You are specialized in crafting YouTube video descriptions. Your task is to create a compelling and informative description for a YouTube video, guided by the details the user specifies. Ensure that the description reflects the video's content accurately, incorporates the specified keywords naturally, adheres to the user's custom instructions, and matches the desired tone and word count. This tailored approach aims to meet the specific needs and preferences of the user for their YouTube video description.`
const HUMAN_TEMPLATE = `Create a YouTube video description,
the category of the video is ${parameters.category}.
You should use the following keywords in the generated description naturally: ${parameters.keyWords.join(
', and '
)}.
The desired Word Count is approximately ${parameters.wordCount} words.
Your tone of voice for the description should be ${parameters.tones.join(
', and '
)}.
This is the custom instructions on what to add to the description: ${
parameters.instructions
}. And the following is a summary description of the video that you are to make the description for, use this summary of the transcript for your knowledge to fill out the description: ${
parameters.fullTranscript ? parameters.transcript : transcriptSummary.text
}`
const prompt = ChatPromptTemplate.fromMessages([
['system', SYSTEM_TEMPLATE],
['human', HUMAN_TEMPLATE],
])
const model = new ChatOpenAI({
openAIApiKey,
modelName: 'gpt-3.5-turbo-0125',
temperature: 0.7,
streaming: true,
})
const chain = prompt.pipe(model)
result = await chain.stream()
for await (const chunk of result) {
res.write(`data: ${JSON.stringify(chunk.content)}\n\n`)
}
res.end()
} catch (err) {
console.error(err)
res.end()
}
req.on('close', () => {
if (result && result.controller) {
result.controller.abort()
}
delete parametersStore[token]
res.end()
})
})
async function summarizeTranscript(transcript) {
const modelName = 'gpt-3.5-turbo-0125'
const langChainModel = new ChatOpenAI({
openAIApiKey,
modelName,
temperature: 1.0,
})
const textSplitter = new RecursiveCharacterTextSplitter({
chunkSize: 1000,
})
const docs = await textSplitter.createDocuments(transcript)
const chain = loadSummarizationChain(langChainModel, {
type: 'stuff',
})
return await chain.invoke({
input_documents: docs,
})
}