-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.ts
362 lines (299 loc) · 9.95 KB
/
index.ts
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
import express, { Express, Request, Response, Application, request } from "express";
import dotenv from "dotenv";
import neo4j, { Driver, Session } from "neo4j-driver";
import {
conversationResponse,
conversation,
createdResponse,
docs,
} from "../types/conversation";
dotenv.config();
const app: Application = express();
app.use(express.json());
const port = process.env.PORT || 8000;
export const createDriver = async () => {
const driver = neo4j.driver(
String(process.env.NEO4J_URI),
neo4j.auth.basic(
String(process.env.NEO4J_USER),
String(process.env.NEO4J_PASSWORD)
)
);
return driver;
};
app.get("/", async (req: Request, res: Response) => {
const driver = await createDriver();
const session = driver.session();
const { records } = await session.run("MATCH (p:User) return p");
const result = records.map((record) => record.get("p"));
closeConnection(driver, session);
res.json(result);
});
app.get("/login", async (req: Request, res: Response) => {
const { username, password } = req.query;
const driver = await createDriver();
const session = driver.session();
const { records } = await session.run(
"MATCH (p:User {surname: $propertyValue, name: $password }) RETURN ID(p) AS userId, p",
{ propertyValue: username, password: password }
);
if (records.length <= 0) {
res.status(401).json({
response: "Login Failed!",
});
closeConnection(driver, session);
return;
}
closeConnection(driver, session);
res.status(200).json({
response: "Successfully logged in!",
userID: records[0].get("userId").toInt(),
});
});
app.delete("/history", async (req: Request, res: Response) => {
const { historyID, userID } = req.query;
const driver = await createDriver();
const session = driver.session();
const result = await session.run(
"MATCH (h:History WHERE ID(h) = $history)-[:HAS_CONVERSATION]->(c:Conversation) detach delete h, c",
{ history: Number(historyID) }
);
closeConnection(driver, session);
res.status(200).json(await getHistoryByUser(Number(userID)));
});
app.post("/search", async (req: Request, res: Response) => {
const { userID, historyID } = req.query;
const data = req.body;
const convo = req.body;
const prompt = "Prompt from MML";
const results: docs[] = [];
const convoObj: conversation = {
prompt: prompt,
request: req.body,
docs: results,
};
const driver = await createDriver();
const session = driver.session();
const createdUserHistoryRel = await session.run(
"MATCH (u:User where ID(u) = $userID) CREATE (h:History {createdAt: localdatetime()}) SET h += $history CREATE (u)-[:HAS_HISTORY]->(h)",
{ history: data, userID: Number(userID) }
);
if (!historyID) {
const returnedVal = createHistory(Number(userID), data)
const response = Number((await returnedVal).response.statusCode)
if (response == 200) {
const hID = Number((await returnedVal).hID)
console.log(hID)
const createdHistoryConversationRel = await session.run(
"MATCH (h:History) WHERE ID(h) = $hID CREATE (c:Conversation {createdAt: localdatetime()}) SET c += $conversation CREATE (h)-[:HAS_CONVERSATION]->(c)",
{ conversation: data, hID: Number(hID) }
);
return res.json(createdHistoryConversationRel)
}
} else {
const appendHistoryConversationRel = await session.run(
"MATCH (h:History) WHERE ID(h) = $history CREATE (c:Conversation {createdAt: localdatetime()}) SET c += $conversation CREATE (h)-[:HAS_CONVERSATION]->(c)",
{ conversation: data, history: Number(historyID) }
);
return res.json(appendHistoryConversationRel)
}
});
async function createHistory(userID: number, retrievedData: string) {
const data = retrievedData;
const driver = await createDriver();
const session = driver.session();
try {
const createdUserHistoryRel = await session.run(
"MATCH (u:User) WHERE ID(u) = $uID CREATE (h:History {createdAt: localdatetime()}) SET h += $history CREATE (u)-[:HAS_HISTORY]->(h) return ID(h) as nodeId",
{ history: data, uID: userID }
);
const historyID: number = createdUserHistoryRel.records[0].get("nodeId");
const response: createdResponse = {
statusCode: 200,
response: {
response: "Successfully created conversation",
}
}
const returnData = { "response": response, "hID": historyID }
return returnData
} catch (error) {
const response: createdResponse = {
statusCode: 500,
response: {
response: "Successfully created conversation",
}
}
const returnData = { "response": response, "hID": null}
return returnData
}
}
// app.post("/history", async (req: Request, res: Response) => {
// const { userID } = req.query;
// const data = req.body;
// const driver = await createDriver();
// const session = driver.session();
// const createdUserHistoryRel = await session.run(
// "MATCH (u:User {surname : 'Doe'}) CREATE (h:History {createdAt: localdatetime()}) SET h += $history CREATE (u)-[:HAS_HISTORY]->(h)",
// { history: data }
// );
// return res.json(createdUserHistoryRel)
// });
app.get("/history", async (req: Request, res: Response) => {
const { userID } = req.query;
/* const driver = await createDriver();
const session = driver.session();
const { records } = await session.run(
"MATCH (p:User where ID(p) = $userIDDB)-[r:HAS_HISTORY]->(h:History) return h, ID(h) as historyID",
{ userIDDB: Number(userID) }
);
if (records.length <= 0) {
return res.status(200).json([]);
}
const attributes = records.map((record) => {
const data = record.get("h");
return {
historyID: record.get("historyID").toInt(),
title: data.properties.title,
language: data.properties.language,
};
}); */
res.status(200).json(await getHistoryByUser(Number(userID)));
});
app.get("/conversation", async (req: Request, res: Response) => {
const { historyID } = req.query;
if (!historyID) {
return res.status(404).json({
response: "historyID is required!",
});
}
const driver = await createDriver();
const session = driver.session();
const { records } = await session.run(
"MATCH (h:History where ID(h) = $historyID)-[r:HAS_CONVERSATION]->(c:Conversation) return c, h ORDER BY c.createdAt ASC",
{ historyID: Number(historyID) }
);
closeConnection(driver, session);
if (records.length <= 0) {
return res.status(404).json({
response: "No Conversation found!",
});
}
const historyRecord = records[0].get("h");
const historyTitle = historyRecord.properties.title;
const allConversations: conversation[] = records.map((record) => {
const singleRecord = record.get("c");
const createdAt = singleRecord.properties.createdAt;
return {
prompt: singleRecord.properties.prompt,
request: singleRecord.properties.request,
docs: singleRecord.properties.docs,
createdAt: new Date(
createdAt.year.low,
createdAt.month.low - 1,
createdAt.day.low,
createdAt.hour.low,
createdAt.minute.low,
createdAt.second.low,
createdAt.nanosecond.low / 1000000
),
};
});
const conversationResponse: conversationResponse = {
historyID: Number(historyID),
title: historyTitle,
conversations: allConversations,
};
return res.status(200).json(conversationResponse);
});
app.post("/conversation", async (req: Request, res: Response) => {
const { historyID } = req.query;
//Search search from frontend
const convo = req.body;
const prompt = "Prompt from MML";
const results: docs[] = [];
const convoObj: conversation = {
prompt: prompt,
request: req.body,
docs: results,
};
const addConvoResponse: createdResponse = await addConversation(
convo,
Number(historyID)
);
return res
.status(addConvoResponse.statusCode)
.json(addConvoResponse.response);
});
const getLLMData = async (request: string) => {
const requestURL: string = (process.env.LLM_URI as string) + "/search";
const response = await fetch(requestURL, {
method: "GET",
mode: "cors",
cache: "no-cache",
headers: {
"Content-Type": "application/json",
},
});
if (!response.ok) {
//TODO Error Handling
}
return await response.json();
};
const addConversation = async (
conversationData: conversation,
historyID: number
) => {
const driver = await createDriver();
const session = driver.session();
try {
const createdConvo = await session.run(
"MATCH (h:History where ID(h) = $historyID) CREATE (c:Conversation {createdAt: localdatetime()}) SET c += $convo CREATE (h)-[:HAS_CONVERSATION]->(c)",
{ historyID: Number(historyID), convo: conversationData }
);
closeConnection(driver, session);
const response: createdResponse = {
statusCode: 200,
response: {
response: "Successfully created conversation",
},
};
return response;
} catch (error) {
closeConnection(driver, session);
const response: createdResponse = {
statusCode: 500,
response: {
response: "Failed to create conversation!",
},
};
return response;
}
};
const getHistoryByUser = async (userID: Number) => {
const driver = await createDriver();
const session = driver.session();
const { records } = await session.run(
"MATCH (p:User where ID(p) = $userIDDB)-[r:HAS_HISTORY]->(h:History) return h, ID(h) as historyID",
{ userIDDB: Number(userID) }
);
closeConnection(driver, session);
if (records.length <= 0) {
return [];
}
const attributes = records.map((record) => {
const data = record.get("h");
return {
historyID: record.get("historyID").toInt(),
title: data.properties.title,
language: data.properties.language,
};
});
return attributes;
};
const closeConnection = (driver: Driver, session: Session) => {
session.close();
driver.close();
};
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});