Repository navigation
Expand file tree
/
Copy pathhttp.js
More file actions
507 lines (476 loc) · 20.8 KB
/
Copy pathhttp.js
File metadata and controls
507 lines (476 loc) · 20.8 KB
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
const http = require("http");
const fs = require("fs");
const path = require("path");
const { createBotEngine } = require("./bot/engine");
const apic = require('./apic');
const scrape = require('./scrapers');
const llm = require('./llm');
const dbquery = require('./dbquery');
const SERVER_PORT = 9001;
const botEngine = createBotEngine({ baseDir: __dirname });
const getPreprompt = () => {
const prepromptPath = path.join(__dirname, "preprompt.md");
if (fs.existsSync(prepromptPath)) {
return fs.readFileSync(prepromptPath, "utf8");
}
return "";
};
const getEnvData = () => {
const envPath = path.join(__dirname, ".env");
if (fs.existsSync(envPath)) {
return fs.readFileSync(envPath, "utf8");
}
return "";
};
const updateEnvFile = (key, value) => {
const envPath = path.join(__dirname, ".env");
let content = "";
if (fs.existsSync(envPath)) {
content = fs.readFileSync(envPath, "utf8");
}
const lines = content.split(/\r?\n/);
let found = false;
const newLines = lines.map(line => {
if (line.startsWith(`${key}=`)) {
found = true;
return `${key}=${value}`;
}
return line;
});
if (!found) {
newLines.push(`${key}=${value}`);
}
fs.writeFileSync(envPath, newLines.join("\n"));
};
const writePage = (title = "", content = "", scripts = "") => {
return `<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>${title}</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.chat-container { max-height: 500px; overflow-y: auto; background: #f8f9fa; border-radius: 8px; }
.message { margin-bottom: 12px; padding: 12px; border-radius: 8px; max-width: 80%; }
.user-message { background-color: #0d6efd; color: white; margin-left: auto; }
.bot-message { background-color: #e9ecef; color: #212529; }
pre { white-space: pre-wrap; word-wrap: break-word; }
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<span class="navbar-brand h1 mb-0">LiteBot</span>
<div class="navbar-nav">
<a class="nav-link" href="/">Chat</a>
<a class="nav-link" href="/apic">API-C</a>
<a class="nav-link" href="/scrape">Scrapers</a>
<a class="nav-link" href="/llm">LLM</a>
<a class="nav-link" href="/sqlite">SQLite</a>
<a class="nav-link" href="/env">Env</a>
</div>
</div>
</nav>
<div class="container mt-4">
${content}
</div>
${scripts}
</body>
</html>`;
};
const server = http.createServer((req, res) => {
const pgurl = new URL('http://localhost' + req.url);
const reqUrl = pgurl.pathname;
const params = pgurl.searchParams;
if (req.method === "GET") {
if (reqUrl === "/") {
// ... (chat page remains the same)
res.write(writePage("LiteBot", `
<div class="row">
<div class="col-md-8 offset-md-2">
<div class="card shadow">
<div class="card-header bg-primary text-white">Chat with LiteBot</div>
<div class="card-body">
<div id="chat-box" class="chat-container border p-3 mb-3"></div>
<div class="input-group">
<input type="text" id="user-input" class="form-control" placeholder="Ask something...">
<button id="send-btn" class="btn btn-primary">Send</button>
</div>
</div>
<div class="card-footer text-muted">
<button id="reset-btn" class="btn btn-sm btn-outline-danger">Reset State</button>
</div>
</div>
</div>
</div>
`, `
<script>
const chatBox = document.getElementById('chat-box');
const userInput = document.getElementById('user-input');
const sendBtn = document.getElementById('send-btn');
const resetBtn = document.getElementById('reset-btn');
function addMessage(text, isUser) {
const div = document.createElement('div');
div.className = 'message ' + (isUser ? 'user-message' : 'bot-message');
div.innerHTML = '<strong>' + (isUser ? 'You' : 'LiteBot') + ': </strong>' + text.replace(/\\n/g, '<br>');
chatBox.appendChild(div);
chatBox.scrollTop = chatBox.scrollHeight;
}
async function sendMessage(text) {
if (text.toLowerCase() === 'reset') chatBox.innerHTML = '';
addMessage(text, true);
const response = await fetch('/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: text })
});
const data = await response.json();
addMessage(data.response, false);
}
sendBtn.onclick = () => {
const text = userInput.value.trim();
if (text) {
sendMessage(text);
userInput.value = '';
}
};
userInput.onkeypress = (e) => {
if (e.key === 'Enter') sendBtn.click();
};
resetBtn.onclick = () => {
sendMessage('reset');
};
</script>
`));
res.end();
} else if (reqUrl === "/env") {
const envData = getEnvData();
res.write(writePage("Environment Variables", `
<div class="row">
<div class="col-md-8 offset-md-2">
<div class="card shadow">
<div class="card-header bg-danger text-white">Manage .env File</div>
<div class="card-body">
<h5>Current Content:</h5>
<pre class="bg-light p-3 border rounded">${envData || "(Empty)"}</pre>
<hr>
<h5>Add/Update Key:</h5>
<div class="input-group mb-3">
<input type="text" id="env-key" class="form-control" placeholder="KEY">
<input type="text" id="env-value" class="form-control" placeholder="VALUE">
<button id="save-env-btn" class="btn btn-success">Save</button>
</div>
<div id="env-status" class="mt-2"></div>
</div>
</div>
</div>
</div>
`, `
<script>
const saveBtn = document.getElementById('save-env-btn');
const keyInput = document.getElementById('env-key');
const valInput = document.getElementById('env-value');
const statusDiv = document.getElementById('env-status');
saveBtn.onclick = async () => {
const key = keyInput.value.trim();
const value = valInput.value.trim();
if (!key) return alert('Key is required');
const response = await fetch('/env', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key, value })
});
const data = await response.json();
if (data.success) {
statusDiv.innerHTML = '<div class="alert alert-success">Saved! Reloading...</div>';
setTimeout(() => location.reload(), 1000);
} else {
statusDiv.innerHTML = '<div class="alert alert-danger">Error saving</div>';
}
};
</script>
`));
res.end();
} else if (reqUrl === "/apic") {
res.write(writePage("Test API-C", `
<div class="row">
<div class="col-md-8 offset-md-2">
<div class="card shadow">
<div class="card-header bg-dark text-white">Test apic.js</div>
<div class="card-body">
<form action="/run-apic" method="get">
<div class="mb-3">
<label class="form-label">API Target</label>
<input type="text" name="target" class="form-control" placeholder="e.g. ipify, verifalia, wikipedia, opensky, sendmail">
</div>
<div class="mb-3">
<label class="form-label">Data (JSON format)</label>
<textarea name="dyd" class="form-control" rows="4">{"ip": "8.8.8.8", "flightCode": "AF1234", "sendto": "test@example.com", "subject": "Test", "content": "Hello world"}</textarea>
</div>
<button type="submit" class="btn btn-success w-100">Execute API Call</button>
</form>
</div>
</div>
</div>
<div class="col-md-8 offset-md-2 mt-4">
<div><strong>ipfy</strong>: <pre>{"ip":""}</pre></div>
<div><strong>tavily</strong>: <pre>{"search":""}</pre></div>
</div>
</div>
`));
res.end();
} else if (reqUrl === "/run-apic") {
const target = params.get("target");
let dyd = {};
try { dyd = JSON.parse(params.get("dyd")); } catch(e) {}
apic(target, dyd).then(result => {
res.write(writePage("API-C Result", `
<div class="col-md-8 offset-md-2">
<h3>Result for ${target}</h3>
<div class="alert alert-success">Call successful</div>
<pre class="bg-light p-4 border rounded shadow-sm">${JSON.stringify(result, null, 2)}</pre>
<a href="/apic" class="btn btn-primary mt-3">Back to Tester</a>
</div>
`));
res.end();
}).catch(err => {
res.write(writePage("API-C Error", `
<div class="col-md-8 offset-md-2">
<div class="alert alert-danger">
<h4>API Error</h4>
<p>${err}</p>
</div>
<a href="/apic" class="btn btn-secondary">Back</a>
</div>
`));
res.end();
});
} else if (reqUrl === "/scrape") {
res.write(writePage("Test Scrapers", `
<div class="row">
<div class="col-md-8 offset-md-2">
<div class="card shadow">
<div class="card-header bg-dark text-white">Test scrapers.js</div>
<div class="card-body">
<form action="/run-scrape" method="get">
<div class="mb-3">
<label class="form-label">Scraper Target</label>
<input type="text" name="target" class="form-control" placeholder="e.g. wikipedia, textonly">
</div>
<div class="mb-3">
<label class="form-label">Article Search Term</label>
<textarea name="dyd" class="form-control" rows="2">{"article": "Node.js"}</textarea>
</div>
<button type="submit" class="btn btn-success w-100">Scrape</button>
</form>
</div>
</div>
</div>
<div class="col-md-8 offset-md-2 mt-4">
<div><strong>wikipedia</strong>: <pre>{"article":""}</pre></div>
<div><strong>textonly</strong>: <pre>{"url":"https://"}</pre></div>
</div>
</div>
`));
res.end();
} else if (reqUrl === "/run-scrape") {
const target = params.get("target");
const dyd = params.get("dyd") ? JSON.parse(params.get("dyd")) : {};
scrape(target, dyd).then(result => {
res.write(writePage("Scrape Result", `
<div class="col-md-8 offset-md-2">
<h3>Scrape Result: ${target}</h3>
<div class="alert alert-success">Scraping successful</div>
<pre class="bg-light p-4 border rounded shadow-sm">${JSON.stringify(result, null, 2)}</pre>
<a href="/scrape" class="btn btn-primary mt-3">Back to Tester</a>
</div>
`));
res.end();
}).catch(err => {
res.write(writePage("Scrape Error", `
<div class="col-md-8 offset-md-2">
<div class="alert alert-danger">
<h4>Scraper Error</h4>
<p>${err}</p>
</div>
<a href="/scrape" class="btn btn-secondary">Back</a>
</div>
`));
res.end();
});
} else if (reqUrl === "/llm") {
res.write(writePage("Chat with LLM", `
<div class="row">
<div class="col-md-8 offset-md-2">
<div class="card shadow">
<div class="card-header bg-dark text-white">Direct LLM Interface</div>
<div class="card-body">
<div id="llm-chat-box" class="chat-container border p-3 mb-3"></div>
<div class="input-group">
<input type="text" id="llm-input" class="form-control" placeholder="Ask LLM anything...">
<button id="llm-send-btn" class="btn btn-dark">Send to LLM</button>
</div>
</div>
</div>
</div>
</div>
`, `
<script>
const chatBox = document.getElementById('llm-chat-box');
const userInput = document.getElementById('llm-input');
const sendBtn = document.getElementById('llm-send-btn');
function addMessage(text, isUser) {
const div = document.createElement('div');
div.className = 'message ' + (isUser ? 'user-message' : 'bot-message');
div.innerHTML = '<strong>' + (isUser ? 'You' : 'LLM') + ': </strong>' + text.replace(/\\n/g, '<br>');
chatBox.appendChild(div);
chatBox.scrollTop = chatBox.scrollHeight;
}
async function sendMessage(text) {
addMessage(text, true);
const response = await fetch('/llm', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: text })
});
const data = await response.json();
addMessage(data.response, false);
}
sendBtn.onclick = () => {
const text = userInput.value.trim();
if (text) {
sendMessage(text);
userInput.value = '';
}
};
userInput.onkeypress = (e) => {
if (e.key === 'Enter') sendBtn.click();
};
</script>
`));
res.end();
} else if (reqUrl === "/sqlite") {
res.write(writePage("SQLite / dbquery Tester", `
<div class="row">
<div class="col-md-8 offset-md-2">
<div class="card shadow">
<div class="card-header bg-dark text-white">Test dbquery.js</div>
<div class="card-body">
<form action="/run-sqlite" method="get">
<div class="mb-3">
<label class="form-label">Target (Function Name)</label>
<input type="text" name="target" class="form-control" placeholder="e.g. execute-query, set-reminder, list-reminders" value="execute-query">
</div>
<div class="mb-3">
<label class="form-label">Data (JSON format)</label>
<textarea name="dyd" class="form-control" rows="4" placeholder='{"query": "SELECT * FROM calendar"}'>{"query": "SELECT * FROM calendar"}</textarea>
</div>
<button type="submit" class="btn btn-success w-100">Execute dbquery Call</button>
</form>
</div>
</div>
</div>
<div class="col-md-8 offset-md-2 mt-4">
<h5>Examples:</h5>
<div class="mb-2">
<strong>Raw SQL (execute-query):</strong>
<pre class="bg-light p-2 border">Target: execute-query\nData: {"query": "SELECT * FROM calendar"}</pre>
</div>
<div class="mb-2">
<strong>Set Reminder:</strong>
<pre class="bg-light p-2 border">Target: set-reminder\nData: {"rdate": "2024-12-25", "message": "Merry Christmas"}</pre>
</div>
<div class="mb-2">
<strong>List Reminders:</strong>
<pre class="bg-light p-2 border">Target: list-reminders\nData: {}</pre>
</div>
</div>
</div>
`));
res.end();
} else if (reqUrl === "/run-sqlite") {
const target = params.get("target");
let dyd = {};
try { dyd = JSON.parse(params.get("dyd") || "{}"); } catch(e) { dyd = { error: "Invalid JSON" }; }
dbquery(target, dyd).then(result => {
res.write(writePage("dbquery Result", `
<div class="col-md-8 offset-md-2">
<h3>Result for ${target}</h3>
<div class="alert alert-success">Call successful</div>
<pre class="bg-light p-4 border rounded shadow-sm">${JSON.stringify(result, null, 2)}</pre>
<a href="/sqlite" class="btn btn-primary mt-3">Back to Tester</a>
</div>
`));
res.end();
}).catch(err => {
res.write(writePage("dbquery Error", `
<div class="col-md-8 offset-md-2">
<div class="alert alert-danger">
<h4>dbquery Error</h4>
<p>${err.message || err}</p>
</div>
<a href="/sqlite" class="btn btn-secondary">Back</a>
</div>
`));
res.end();
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end("Error 404: Not found");
}
} else if (req.method === "POST") {
if (reqUrl === "/chat") {
let body = "";
req.on("data", chunk => { body += chunk.toString(); });
req.on("end", async () => {
try {
const parsedBody = JSON.parse(body);
const response = await botEngine.processInput(parsedBody.message);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ response }));
} catch (err) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: "Invalid JSON" }));
}
});
} else if (reqUrl === "/env") {
let body = "";
req.on("data", chunk => { body += chunk.toString(); });
req.on("end", async () => {
try {
const parsedBody = JSON.parse(body);
if (parsedBody.key) {
updateEnvFile(parsedBody.key, parsedBody.value || "");
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ success: true }));
} else {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: "Key is required" }));
}
} catch (err) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: err.message }));
}
});
} else if (reqUrl === "/llm") {
let body = "";
req.on("data", chunk => { body += chunk.toString(); });
req.on("end", async () => {
try {
const parsedBody = JSON.parse(body);
console.log(parsedBody.message)
const result = await llm(parsedBody.message, [], getPreprompt());
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ response: result.content }));
} catch (err) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: err.message }));
}
});
}
}
});
server.listen(SERVER_PORT, () => {
console.log(`LiteBot WebApp started at: http://localhost:${SERVER_PORT}`);
});