-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
359 lines (323 loc) · 10.9 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
import express from "express";
import { JSDOM } from "jsdom";
import { marked } from "marked";
import { TiktokenModel, encoding_for_model } from "tiktoken";
import { customsearch } from "@googleapis/customsearch";
import { config } from "dotenv";
import { readFileSync } from "fs";
const PORT = 8181;
let searched_links: string[] = [];
const custom_search = customsearch({
version: "v1",
auth: process.env.GOOGLEKEY,
params: {
cx: process.env.GOOGLECX
}
});
try {
config();
} catch (e) {
console.log("No .env file found, using environment variables");
console.log(e);
}
const OpenAIModel = process.env.QUICKMODEL as TiktokenModel || "gpt-3.5-turbo-16k";
const enc = encoding_for_model(OpenAIModel);
const app = express();
app.use(express.json());
app.use(express.static("static"));
app.use((req, res, next) => {
console.log([
new Date().toLocaleString().replace(",", ""),
req.method,
// fancy path
req.path.concat((req.path.length > 8) ? "" : "\t").slice(0, 15),
req.ip,
req.headers.host
].join("\t"));
next();
});
//const client = new OpenAI({
// apiKey: process.env.OPENAIKEY,
// organization: process.env.OPENAIORG
//});
/**
* Returns an array of paragraphs and the pageIDs. To be sent to the embedder.
*/
const wikiSearch = async (query: string) => {
const params = new URLSearchParams({
action: "query",
// Feed search results into...
generator: "search",
gsrlimit: "1",
gsrsearch: query,
format: "json",
//...the extracts module
prop: "extracts",
exlimit: "1",
explaintext: "true"
});
const baseURL = "https://en.wikipedia.org/w/api.php";
let results: {
[key: string]: {
extract: string;
}
}
try {
let temp = (await (await fetch(
`${baseURL}?${params}`,
{
method: "GET",
headers: {
"Accept": "application/json",
// Tell them who we are in case they want to contact us
"User-Agent": `GPTSearch (${process.env.GHCONTACT})`,
}
}
)).json());
console.log(JSON.stringify(temp));
results = temp.query.pages;
} catch (e) {
console.log(e);
return { paragraphs: [`Error: ${JSON.stringify(e)}`] };
}
let paragraphs: string[] = [];
const pageID = Object.keys(results)[0];
for (const p of results[pageID].extract.split("\n\n\n")) {
if (p.includes("== See also ==\n")) break;
paragraphs.push(p);
};
return { paragraphs };
}
const googleSearch = async (query: string) => {
const results = await custom_search.cse.list({
cx: process.env.GOOGLECX,
q: query,
auth: process.env.GOOGLEKEY,
num: 5
});
let snippets: string[] = [];
let links: string[] = [];
if (!results.data.items) return { snippets, links };
for (const item of results.data.items) {
snippets.push(item.snippet || "");
links.push(item.link || "");
}
return {
snippets,
links
};
}
class EmbedAPI {
// Automatically determine if we're running locally or in a container
baseURL = `http://${process.env.WSL_DISTRO_NAME != null ? "localhost" : "db"}:4211`;
// TODO: add as batch
add = async (texts: string[]) => {
const response: {
success: false;
error: string;
} | {
success: true;
items: number;
} = await (await fetch(
`${this.baseURL}/add`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Request-Timeout": "50"
},
body: JSON.stringify({ texts })
}
)).json();
return response;
}
queryV2 = async (text: string) => {
let links = await Promise.all([wikiSearch(text), googleSearch(text)]).then(async ([wiki, google]) => {
await this.add([...wiki.paragraphs.slice(0, 12), ...google.snippets.slice(0, 12)]);
return google.links;
});
return {
query: await this.query(text),
links: links
};
}
/**
* 3 most relevant items
*/
query = async (text: string) => {
const response: {
success: boolean;
items: string[] | undefined;
error: string | undefined;
} = await (await fetch(
`${this.baseURL}/query`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Request-Timeout": "50"
},
body: JSON.stringify({ text })
}
)).json();
return response;
}
}
const embedAPI = new EmbedAPI();
app.post("/browse", async (req, res) => {
/**
* Remove if you aren't deploying your own instance to OpenAI.
* Otherwise, you should set the environment variable CHATGPTSECRET
* to some randomly generated key.
*/
if (req.headers.authorization !== `Bearer ${process.env.CHATGPTSECRET}`) {
console.log(`Unauthorized request from ${req.ip}, ${req.headers.authorization}`);
res.status(401).send("Unauthorized");
return;
}
const url: string = req.body.url;
if (url.match(/https:\/\/.*\.wikipedia\.org\/.*/g))
return res.json({
results: {
items: (await wikiSearch(req.body.topic)).paragraphs
}
});
const topic: string = req.body.topic;
if (searched_links.includes(url)) {
const out = (await embedAPI.query(topic)).items || [];
console.log(JSON.stringify(out));
res.json(out);
return;
}
await fetch(url).then(r => {
searched_links.push(url);
return r.text();
}).then(async (response) => {
const window = new JSDOM(response, { runScripts: "outside-only" }).window;
window.onload = async () => {
const document = window.document;
let paragraphs: string[] = [];
for (const element of Array.from(
document.querySelectorAll("p"))
.sort((a, b) => a.textContent!.length - b.textContent!.length)
) {
if (element.textContent)
paragraphs.push(element.textContent
.replace(/\n/g, " ")
.replace(/\t/g, " ")
.replace(" ", " ")
.replace("’", "'")
.replace("“", "\"")
.replace("”", "\"")
.trim()
);
}
let newParagraphs: string[] = [];
for (const p of paragraphs) {
let encoded = enc.encode(p);
newParagraphs.push(
new TextDecoder().decode(
enc.decode(encoded.slice(0, 8190))
)
);
}
await embedAPI.add(newParagraphs);
const out = (await embedAPI.query(topic)).items || [];
console.log(JSON.stringify(out));
res.json(out);
};
});
});
app.get("/search", async (req, res) => {
/**
* Remove if you aren't deploying your own instance to OpenAI.
* Otherwise, you should set the environment variable CHATGPTSECRET
* to some randomly generated key.
*/
if (req.headers.authorization !== `Bearer ${process.env.CHATGPTSECRET}`) {
console.log(`Unauthorized request from ${req.ip}, ${req.headers.authorization}`);
res.status(401).send("Unauthorized");
return;
}
let result: {
items?: string[] | undefined;
links?: string[];
} = {
//items: (
// await embedAPI.query(req.query.q as string)
//).items,
links: []
};
let temp = await embedAPI.queryV2(req.query.q as string);
result = {
links: temp.links,
//items: temp.query.items
};
const mapped = result.links?.map(async (link) => {
if (searched_links.includes(link)) {
return;
}
return fetch(link)
.then(r => {
searched_links.push(link);
return r.text();
})
.then(async text => {
const window = new JSDOM(text, { runScripts: "outside-only" }).window;
const document = window.document;
let paragraphs: string[] = [];
for (const element of Array.from(document.querySelectorAll("p")).sort((a, b) => a.textContent!.length - b.textContent!.length)) {
if (element.textContent)
paragraphs.push(element.textContent
.replace(/\n/g, " ")
.replace(/\t/g, " ")
.replace(" ", " ")
.replace("’", "'")
.replace("“", "\"")
.replace("”", "\"")
.trim()
);
}
let newParagraphs: string[] = [];
for (const p of paragraphs) {
let encoded = enc.encode(p);
newParagraphs.push(
new TextDecoder().decode(
enc.decode(encoded.slice(0, 8190))
)
);
}
await embedAPI.add(newParagraphs);
});
});
if (mapped) {
await Promise.all(mapped);
result.items = (await embedAPI.query(req.query.q as string)).items;
}
const out = {
links: result.links,
results: result.items,
date: new Date().toUTCString().replace(",", "").replace(" GMT", "")
};
console.log(JSON.stringify(out));
res.json(out);
});
// TODO: subclass marked.Renderer to make header tags have ids
const renderer = new marked.Renderer();
renderer.heading = (text, level) => {
const escapedText = text.toLowerCase().replace(/[^\w]+/g, "-");
return `<h${level} id="${escapedText}"><a href="#${escapedText}">${text}</a><span>🔗</span></h${level}>`;
};
app.get("/privacy", async (_, res) => {
const md = await marked(readFileSync("./static/privacy.md").toString(), { renderer });
const head = `<head><title>Privacy Policy</title><link rel="stylesheet" href="/style.css"></head>`;
res.send(`<!DOCTYPE html><html>${head}<body><main>${md}</main><center>© 2023-2024 CyberThing all rights reserved</center></body></html>`);
});
app.listen(PORT, () => {
try {
console.log(new Date().toLocaleString());
console.log(`Now listening on http://localhost:${PORT}`);
} catch (e) {
console.log(e);
}
});