-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
323 lines (277 loc) · 9.68 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
import express from "express";
import fileUpload from "express-fileupload";
import pg from "pg";
import dotenv from "dotenv";
import { createClient } from "@supabase/supabase-js";
import fs from "fs";
import { ChatOpenAI } from "langchain/chat_models/openai";
import { loadSummarizationChain } from "langchain/chains";
import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";
import { PDFLoader } from "langchain/document_loaders/fs/pdf";
import { SupabaseVectorStore } from "langchain/vectorstores/supabase";
import { OpenAIEmbeddings } from "langchain/embeddings/openai";
import { initializeAgentExecutorWithOptions } from "langchain/agents";
import { VectorDBQAChain } from "langchain/chains";
import { ChainTool } from "langchain/tools";
import { BufferMemory } from "langchain/memory";
import { PromptTemplate } from "langchain/prompts";
import { StringOutputParser } from "langchain/schema/output_parser";
import { SupabaseHybridSearch } from "langchain/retrievers/supabase";
import {
RunnableSequence,
RunnablePassthrough,
} from "langchain/schema/runnable";
const app = express();
dotenv.config();
const port = process.env.port;
const privateKeyDB = process.env.DB_URL;
const urlDB = process.env.DB_KEY;
const memory = new BufferMemory({
returnMessages: true,
inputKey: "input",
outputKey: "output",
memoryKey: "history",
});
// Create a single supabase client for interacting with your database
const supabase = createClient(privateKeyDB, urlDB);
//serve the public static files
app.use(express.static("public"));
app.use(fileUpload());
app.use(express.json());
app.post("/login", async (req, res) => {
console.log(req.body);
const { email } = req.body;
const { data, error } = await supabase
.from("Users")
.select("*")
.eq("email", email);
if (error) {
console.log(error);
res.status(500).json({ error: error.message });
} else {
if (data.length > 0) {
// If email exists in db, return a welcome back message
res.json({ message: "Welcome back 🥳 (i missed u)", userId: data[0].id });
} else {
// If email doesn't exist, return a thanks for using my tool
// If email doesn't exist, create a new row in the users table
const { error: insertError } = await supabase
.from("Users")
.insert([{ email }]);
console.log(insertError);
if (insertError) {
console.log(insertError);
res.status(500).json({ error: insertError.message });
} else {
// Get the id of the new user
const { data: user, error: selectError } = await supabase
.from("Users")
.select("id")
.eq("email", email)
.single();
if (selectError) {
console.log(selectError);
res.status(500).json({ error: selectError.message });
} else {
console.log(user);
res.json({
message: "Thanks for trying our tool, you're awesome 😎",
userId: user.id,
});
}
}
}
}
});
let summary = null;
//handles file upload and initial summarization
app.post("/upload", async (req, res) => {
try {
if (!req.files) {
return res.status(400).send({ message: "No file was uploaded." });
}
const file = req.files.pdf;
const tempFilePath = `/tmp/${file.name}`;
const userId = req.body.userId;
// Write the PDF to a temp file
file.mv(tempFilePath, async (err) => {
if (err) {
console.error(err);
res.status(500).send({ message: "Error during file upload." });
} else {
// Summarize the PDF and save to DB
const summary = await summarizePdfAndSaveToDb(
tempFilePath,
file.name.replace(".pdf", "")
);
// Add a new row to the PDFUploads table
const { error: insertError } = await supabase
.from("PDFUploads")
.insert([
{ user_id: userId, pdf_name: file.name.replace(".pdf", "") },
]);
if (insertError) {
console.error(insertError);
res.status(500).send({ message: "Error during database operation." });
return;
}
// Query the database for the ID of the newly inserted row
const { data: selectData, error: selectError } = await supabase
.from("PDFUploads")
.select("id")
.eq("user_id", userId)
.eq("pdf_name", file.name.replace(".pdf", ""))
.order("id", { ascending: false })
.limit(1);
if (selectError) {
console.error(selectError);
res.status(500).send({ message: "Error during database operation." });
return;
}
const pdfUploadId = selectData[0].id;
// Create an instance of SupabaseVectorStore and OpenAIEmbeddings
const embeddings = new OpenAIEmbeddings({
azureOpenAIApiKey: process.env.AZURE_OPENAI_API_KEY,
azureOpenAIApiInstanceName:
process.env.AZURE_OPENAI_API_INSTANCE_NAME,
azureOpenAIApiDeploymentName: "text-embedding-ada-002",
model: "text-embedding-ada-002",
});
const vectorStore = new SupabaseVectorStore(embeddings, {
client: supabase,
tableName: "documents",
});
// Add the PDF content to the vector store
// Load the PDF content
const loader = new PDFLoader(tempFilePath, { splitPages: true });
const textSplitter = new RecursiveCharacterTextSplitter({
chunkSize: 2000,
chunkOverlap: 100,
});
const docs = await loader.load();
console.log("Embedding completed.");
// Delete the PDF file
//fs.unlinkSync(tempFilePath);
res.send({
message: "File uploaded successfully.",
summary: summary,
pdfName: file.name.replace(".pdf", ""),
pdfPath: tempFilePath,
pdfID: pdfUploadId,
});
}
});
} catch (error) {
console.error(error);
res.status(500).send({ message: "Error during file upload." });
}
});
// Function to read PDF as text
async function readPdfAsText(pdfPath) {
let dataBuffer = fs.readFileSync(pdfPath);
pdf(dataBuffer).then(function (data) {
fs.writeFileSync("/tmp/pdfText.txt", data.text);
});
}
// Function to update database row
async function updateDatabaseRow(pdfName, summary) {
const { data, error } = await supabase
.from("PDFUploads")
.update({ summary: summary })
.eq("pdf_name", pdfName);
if (error) {
console.error(error);
}
}
// Function to summarize PDF and save to DB
async function summarizePdfAndSaveToDb(pdfPath, pdfName) {
// Load the PDF content
const loader = new PDFLoader(pdfPath, { splitPages: true });
const textSplitter = new RecursiveCharacterTextSplitter({
chunkSize: 2000,
chunkOverlap: 100,
});
const docs = await loader.load();
// Initialize the Langchain components
const model = new ChatOpenAI({
temperature: 0.9,
azureOpenAIApiKey: process.env.AZURE_OPENAI_API_KEY,
AZURE_OPENAI_BASE_PATH: process.env.AZURE_OPENAI_BASE_PATH,
azureOpenAIApiDeploymentName: process.env.AZURE_OPENAI_API_DEPLOYMENT_NAME,
MODEL_NAME: "gpt-35-turbo-16k",
});
// Create the summarization chain
const chain = loadSummarizationChain(model, {
type: "map_reduce",
verbose: true,
});
// Generate the summary
const result = await chain.call({ input_documents: docs });
console.log(result.text);
// Save the summary to the database
await updateDatabaseRow(pdfName, result.text);
// Return the summary
return result.text;
}
//route to handle messages from user
app.post("/message", async (req, res) => {
const userId = req.body.userId;
const pdfPath = req.body.pdfPath;
const embeddings = new OpenAIEmbeddings({
azureOpenAIApiKey: process.env.AZURE_OPENAI_API_KEY,
azureOpenAIApiInstanceName: process.env.AZURE_OPENAI_API_INSTANCE_NAME,
azureOpenAIApiDeploymentName: "text-embedding-ada-002",
model: "text-embedding-ada-002",
});
// Initialize the Langchain components
const model = new ChatOpenAI({
temperature: 0.9,
azureOpenAIApiKey: process.env.AZURE_OPENAI_API_KEY,
AZURE_OPENAI_BASE_PATH: process.env.AZURE_OPENAI_BASE_PATH,
azureOpenAIApiDeploymentName: process.env.AZURE_OPENAI_API_DEPLOYMENT_NAME,
MODEL_NAME: "gpt-35-turbo-16k",
});
const retriever = new SupabaseHybridSearch(embeddings, {
client: supabase,
similarityK: 2,
keywordK: 2,
tableName: "documents",
similarityQueryName: "match_documents",
keywordQueryName: "kw_match_documents",
});
// Create an instance of VectorDBQAChain using the SupabaseHybridSearch instance
const chain = VectorDBQAChain.fromLLM(model, retriever);
const qaTool = new ChainTool({
name: "contextual-qa",
description:
"Contextual QA - useful for when you need contextual information from a document",
chain: chain,
});
const tools = [qaTool];
const executor = await initializeAgentExecutorWithOptions(tools, model, {
agentType: "zero-shot-react-description",
memory: memory,
});
console.log("Loaded agent.");
const input = req.body.message;
console.log(`Executing with input "${input}"...`);
const result = await executor.call({ input });
console.log(`Got output ${result.output}`);
res.json({ response: { message: result.output } });
const user_uuid = req.body.uuid;
const user_msg = req.body.message;
const ai_msg = result.output;
const PDF_id = req.body.pdfID;
const { data, error } = await supabase.from("ChatHistory").insert([
{
user_id: user_uuid,
user_msg: user_msg,
AI_msg: ai_msg,
PDF_id: PDF_id,
},
]);
if (error) console.log(error);
});
app.listen(port, () => {
console.log(`hade.ai listening at http://localhost:${port}`);
});