forked from abeuscher/vue-ai-example
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
1712 lines (1437 loc) · 59.6 KB
/
Copy pathserver.js
File metadata and controls
1712 lines (1437 loc) · 59.6 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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import dotenv from 'dotenv'
dotenv.config()
// Global error handling to prevent server crashes
process.on('uncaughtException', (error) => {
console.error('❌ Uncaught Exception:', error);
// Don't exit the process, just log the error
});
process.on('unhandledRejection', (reason, promise) => {
console.error('❌ Unhandled Rejection at:', promise, 'reason:', reason);
// Don't exit the process, just log the error
});
// Debug environment variables
console.log('🔍 Environment Debug:');
console.log('Current working directory:', process.cwd());
console.log('DIGITALOCEAN_PERSONAL_API_KEY exists:', !!process.env.DIGITALOCEAN_PERSONAL_API_KEY);
console.log('DIGITALOCEAN_PERSONAL_API_KEY length:', process.env.DIGITALOCEAN_PERSONAL_API_KEY?.length || 0);
import express from 'express';
import cors from 'cors';
import path from 'path';
import { fileURLToPath } from 'url';
import helmet from 'helmet';
import rateLimit from 'express-rate-limit';
import fetch from 'node-fetch';
import pdf from 'pdf-parse';
import multer from 'multer';
import session from 'express-session';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const app = express();
// Unified Cloudant/CouchDB setup
import { createCouchDBClient } from './src/utils/couchdb-client.js';
const couchDBClient = createCouchDBClient();
const initializeDatabase = async () => {
try {
// Test the connection
const connected = await couchDBClient.testConnection();
if (connected) {
// Initialize database
await couchDBClient.initializeDatabase();
// Get service info
const serviceInfo = couchDBClient.getServiceInfo();
console.log(`✅ Connected to ${serviceInfo.isCloudant ? 'Cloudant' : 'CouchDB'}`);
console.log(`✅ Using database '${serviceInfo.databaseName}'`);
} else {
throw new Error('Database connection failed');
}
} catch (error) {
console.error('❌ Database initialization failed:', error);
}
};
// Initialize database
initializeDatabase();
// Security middleware
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
scriptSrc: ["'self'"],
imgSrc: ["'self'", "data:", "https:"],
},
},
hsts: {
maxAge: 31536000,
includeSubDomains: true,
preload: true
},
noSniff: true,
xssFilter: true,
frameguard: { action: 'deny' },
referrerPolicy: { policy: 'strict-origin-when-cross-origin' }
}));
// Additional security headers
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('X-XSS-Protection', '1; mode=block');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
res.setHeader('Permissions-Policy', 'geolocation=(), microphone=(), camera=()');
next();
});
// Rate limiting for API endpoints
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP, please try again later.',
standardHeaders: true,
legacyHeaders: false,
});
// Stricter rate limiting for file uploads
const uploadLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 10, // limit each IP to 10 uploads per windowMs
message: 'Too many file uploads from this IP, please try again later.',
standardHeaders: true,
legacyHeaders: false,
});
// Apply rate limiting to API routes
app.use('/api/', apiLimiter);
app.use('/api/parse-pdf', uploadLimiter);
// CORS configuration for local development
const corsOptions = {
origin: process.env.ALLOWED_ORIGINS?.split(',') || ['http://localhost:3001'],
credentials: true,
optionsSuccessStatus: 200
};
app.use(cors(corsOptions));
app.use(express.json({ limit: '10mb' }));
// Cache-busting headers for development
app.use((req, res, next) => {
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
next();
});
// Serve static files with cache busting
app.use(express.static(path.join(__dirname, 'dist'), {
etag: false,
lastModified: false,
setHeaders: (res, path) => {
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
}
}));
// Input validation middleware
app.use((req, res, next) => {
// Sanitize JSON payloads
if (req.body && typeof req.body === 'object') {
const sanitized = {};
for (const [key, value] of Object.entries(req.body)) {
if (typeof value === 'string') {
// Remove potential script tags and dangerous content
sanitized[key] = value.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');
} else {
sanitized[key] = value;
}
}
req.body = sanitized;
}
next();
});
// Request logging middleware
if (process.env.ENABLE_REQUEST_LOGGING === 'true') {
app.use((req, res, next) => {
console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
next();
});
}
// Health check endpoint
app.get('/health', (req, res) => {
res.json({
status: 'healthy',
environment: process.env.NODE_ENV,
singlePatientMode: process.env.SINGLE_PATIENT_MODE === 'true'
});
});
// Configure multer for file uploads
const upload = multer({
storage: multer.memoryStorage(),
limits: {
fileSize: 50 * 1024 * 1024, // 50MB limit
},
fileFilter: (req, file, cb) => {
// Enhanced file type validation
const allowedMimeTypes = ['application/pdf'];
const allowedExtensions = ['.pdf'];
// Check MIME type
if (!allowedMimeTypes.includes(file.mimetype)) {
return cb(new Error('Only PDF files are allowed'));
}
// Check file extension
const fileExtension = path.extname(file.originalname).toLowerCase();
if (!allowedExtensions.includes(fileExtension)) {
return cb(new Error('Only PDF files are allowed'));
}
// Check for suspicious file names
const suspiciousPatterns = /[<>:"|?*]/;
if (suspiciousPatterns.test(file.originalname)) {
return cb(new Error('Invalid file name'));
}
cb(null, true);
}
});
// PDF parsing endpoint with enhanced security
app.post('/api/parse-pdf', upload.single('pdfFile'), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ error: 'No PDF file provided' });
}
// Additional security checks
if (req.file.size === 0) {
return res.status(400).json({ error: 'Empty file provided' });
}
// Check for potential zip bombs or oversized content
if (req.file.size > 50 * 1024 * 1024) {
return res.status(400).json({ error: 'File too large' });
}
// Parse PDF from buffer
const data = await pdf(req.file.buffer);
// Validate parsed content
if (!data.text || data.text.length === 0) {
return res.status(400).json({ error: 'Could not extract text from PDF' });
}
// Convert to markdown format
const markdown = convertPdfToMarkdown(data);
console.log(`📄 PDF parsed: ${data.numpages} pages, ${data.text.length} characters`);
res.json({
success: true,
markdown,
pages: data.numpages,
characters: data.text.length
});
} catch (error) {
console.error('❌ PDF parsing error:', error);
res.status(500).json({ error: `Failed to parse PDF: ${error.message}` });
}
});
// Import API clients
import OpenAI from 'openai';
import Anthropic from '@anthropic-ai/sdk';
// Initialize clients only if API keys are available
let personalChatClient, anthropic, openai, deepseek;
// DigitalOcean GenAI setup (Personal Chat) - KEEP IN CLOUD
if (process.env.DIGITALOCEAN_PERSONAL_API_KEY) {
personalChatClient = new OpenAI({
baseURL: process.env.DIGITALOCEAN_GENAI_ENDPOINT || 'https://vzfujeetn2dkj4d5awhvvibo.agents.do-ai.run/api/v1',
apiKey: process.env.DIGITALOCEAN_PERSONAL_API_KEY
});
console.log('✅ DigitalOcean Personal AI Agent connected');
} else {
console.log('⚠️ DigitalOcean Personal API key not configured - using mock responses');
}
// Anthropic setup (fallback)
if (process.env.ANTHROPIC_API_KEY) {
anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY
});
console.log('✅ Anthropic Claude connected');
}
// OpenAI setup (fallback)
if (process.env.OPENAI_API_KEY) {
openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
console.log('✅ OpenAI connected');
}
// DeepSeek setup (fallback)
if (process.env.DEEPSEEK_API_KEY) {
deepseek = new OpenAI({
baseURL: 'https://api.deepseek.com/v1',
apiKey: process.env.DEEPSEEK_API_KEY
});
console.log('✅ DeepSeek connected');
}
// Utility function
const estimateTokenCount = (text) => {
const averageTokenLength = 4;
return Math.ceil(text.length / averageTokenLength);
};
// PDF to Markdown conversion function
const convertPdfToMarkdown = (pdfData) => {
let markdown = `# PDF Document\n\n`;
markdown += `**Pages:** ${pdfData.numpages}\n`;
markdown += `**Characters:** ${pdfData.text.length}\n\n`;
// Split text into paragraphs and format
const paragraphs = pdfData.text
.split('\n')
.map(line => line.trim())
.filter(line => line.length > 0);
// Group lines into logical sections
let currentSection = '';
let sections = [];
for (const paragraph of paragraphs) {
// Check if this looks like a heading (all caps, shorter than 100 chars)
if (paragraph.length < 100 && paragraph === paragraph.toUpperCase() && paragraph.length > 3) {
if (currentSection) {
sections.push(currentSection.trim());
}
currentSection = `## ${paragraph}\n\n`;
} else {
currentSection += `${paragraph}\n\n`;
}
}
if (currentSection) {
sections.push(currentSection.trim());
}
// If no sections were created, just use the raw text
if (sections.length === 0) {
markdown += pdfData.text.replace(/\n\n+/g, '\n\n');
} else {
markdown += sections.join('\n\n');
}
return markdown;
};
// Mock responses for local testing when cloud services unavailable
const mockAIResponses = {
'personal-chat': (message) => `[Personal AI] I understand you're asking about: "${message}". This is a mock response for local testing. In production, this would connect to your personal AI agent.`,
'anthropic-chat': (message) => `[Anthropic Claude] Here's my response to: "${message}". This is a mock response for local testing.`,
'gemini-chat': (message) => `[Google Gemini] I can help with: "${message}". This is a mock response for local testing.`,
'deepseek-r1-chat': (message) => `[DeepSeek R1] My analysis of: "${message}". This is a mock response for local testing.`
};
// Personal Chat endpoint (DigitalOcean Agent Platform)
app.post('/api/personal-chat', async (req, res) => {
const startTime = Date.now();
try {
if (!personalChatClient) {
return res.status(500).json({ message: 'DigitalOcean Personal API key not configured' });
}
let { chatHistory, newValue, timeline, uploadedFiles } = req.body;
// Filter out any existing system messages since the GenAI agent has its own system prompt
chatHistory = chatHistory.filter(msg => msg.role !== 'system');
// Keep the original user message clean for chat history
const cleanUserMessage = newValue;
// Prepare context for the AI (not for chat history)
let aiContext = '';
if (timeline && chatHistory.length === 0) {
aiContext += `Timeline context: ${timeline}\n\n`;
}
if (uploadedFiles && uploadedFiles.length > 0) {
const filesContext = uploadedFiles.map(file =>
`File: ${file.name} (${file.type})\nContent:\n${file.content}`
).join('\n\n');
aiContext += `Uploaded files context:\n${filesContext}\n\n`;
}
// Combine context with user message for AI, but keep original for chat history
const aiUserMessage = aiContext ? `${aiContext}User query: ${newValue}` : newValue;
const newChatHistory = [
...chatHistory,
{ role: 'user', content: cleanUserMessage }
];
const params = {
messages: [
...chatHistory,
{ role: 'user', content: aiUserMessage }
],
model: 'agent-05102025'
};
// Log token usage and context info
const totalTokens = estimateTokenCount(aiUserMessage);
const contextSize = aiContext ? Math.round(aiContext.length / 1024 * 100) / 100 : 0;
console.log(`🤖 Personal AI: ${totalTokens} tokens, ${contextSize}KB context, ${uploadedFiles?.length || 0} files`);
const response = await personalChatClient.chat.completions.create(params);
const responseTime = Date.now() - startTime;
console.log(`✅ Personal AI response: ${responseTime}ms`);
// Add the response with proper name field
newChatHistory.push({
...response.choices[0].message,
name: 'Personal AI'
});
res.json(newChatHistory);
} catch (error) {
const responseTime = Date.now() - startTime;
console.error(`❌ Personal AI error (${responseTime}ms):`, error.message);
// Fallback to mock response on error
let { chatHistory, newValue } = req.body;
chatHistory = chatHistory.filter(msg => msg.role !== 'system');
const mockResponse = mockAIResponses['personal-chat'](newValue);
const newChatHistory = [
...chatHistory,
{ role: 'user', content: newValue },
{ role: 'assistant', content: mockResponse, name: 'Personal AI (Fallback)' }
];
res.json(newChatHistory);
}
});
// Fallback chat endpoints for other AI providers
app.post('/api/anthropic-chat', async (req, res) => {
const startTime = Date.now();
try {
if (!anthropic) {
return res.status(500).json({ message: 'Anthropic API key not configured' });
}
let { chatHistory, newValue, uploadedFiles } = req.body;
chatHistory = chatHistory.filter(msg => msg.role !== 'system');
// Clean chat history to remove any 'name' fields that Anthropic doesn't support
const cleanChatHistory = chatHistory.map(msg => ({
role: msg.role,
content: msg.content
}));
// Keep the original user message clean for chat history
const cleanUserMessage = newValue;
// Prepare context for the AI
let aiContext = '';
if (uploadedFiles && uploadedFiles.length > 0) {
const filesContext = uploadedFiles.map(file =>
`File: ${file.name} (${file.type})\nContent:\n${file.content}`
).join('\n\n');
aiContext = `Uploaded files context:\n${filesContext}\n\n`;
}
// Combine context with user message for AI
const aiUserMessage = aiContext ? `${aiContext}User query: ${newValue}` : newValue;
// Log token usage and context info
const totalTokens = estimateTokenCount(aiUserMessage);
const contextSize = aiContext ? Math.round(aiContext.length / 1024 * 100) / 100 : 0;
console.log(`🤖 Anthropic: ${totalTokens} tokens, ${contextSize}KB context, ${uploadedFiles?.length || 0} files`);
const response = await anthropic.messages.create({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 1000,
messages: [
...cleanChatHistory,
{ role: 'user', content: aiUserMessage }
]
});
const responseTime = Date.now() - startTime;
console.log(`✅ Anthropic response: ${responseTime}ms`);
const newChatHistory = [
...chatHistory,
{ role: 'user', content: cleanUserMessage },
{ role: 'assistant', content: response.content[0].text, name: 'Anthropic' }
];
res.json(newChatHistory);
} catch (error) {
const responseTime = Date.now() - startTime;
console.error(`❌ Anthropic error (${responseTime}ms):`, error.message);
res.status(500).json({ message: `Server error: ${error.message}` });
}
});
// Additional fallback endpoints...
app.post('/api/gemini-chat', async (req, res) => {
const startTime = Date.now();
try {
if (!process.env.GEMINI_API_KEY) {
// Fallback to mock if no API key
let { chatHistory, newValue, uploadedFiles } = req.body;
chatHistory = chatHistory.filter(msg => msg.role !== 'system');
const mockResponse = mockAIResponses['gemini-chat'](newValue);
const newChatHistory = [
...chatHistory,
{ role: 'user', content: newValue },
{ role: 'assistant', content: mockResponse, name: 'Gemini' }
];
return res.json(newChatHistory);
}
// Use actual Gemini API
let { chatHistory, newValue, uploadedFiles } = req.body;
chatHistory = chatHistory.filter(msg => msg.role !== 'system');
const { GoogleGenerativeAI } = await import('@google/generative-ai');
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
const model = genAI.getGenerativeModel({ model: 'gemini-1.5-flash' });
// Keep the original user message clean for chat history
const cleanUserMessage = newValue;
// Prepare context for the AI
let aiContext = '';
if (uploadedFiles && uploadedFiles.length > 0) {
const filesContext = uploadedFiles.map(file =>
`File: ${file.name} (${file.type})\nContent:\n${file.content}`
).join('\n\n');
aiContext = `Uploaded files context:\n${filesContext}\n\n`;
}
// Combine context with user message for AI
const aiUserMessage = aiContext ? `${aiContext}User query: ${newValue}` : newValue;
// Log token usage and context info
const totalTokens = estimateTokenCount(aiUserMessage);
const contextSize = aiContext ? Math.round(aiContext.length / 1024 * 100) / 100 : 0;
console.log(`🤖 Gemini: ${totalTokens} tokens, ${contextSize}KB context, ${uploadedFiles?.length || 0} files`);
// Start a chat session
const chat = model.startChat({
history: chatHistory.map(msg => ({
role: msg.role === 'user' ? 'user' : 'model',
parts: [{ text: msg.content }]
}))
});
// Send the new message
const result = await chat.sendMessage(aiUserMessage);
const response = await result.response;
const text = response.text();
const responseTime = Date.now() - startTime;
console.log(`✅ Gemini response: ${responseTime}ms`);
const newChatHistory = [
...chatHistory,
{ role: 'user', content: cleanUserMessage },
{ role: 'assistant', content: text, name: 'Gemini' }
];
res.json(newChatHistory);
} catch (error) {
const responseTime = Date.now() - startTime;
console.error(`❌ Gemini error (${responseTime}ms):`, error.message);
res.status(500).json({ message: `Server error: ${error.message}` });
}
});
app.post('/api/deepseek-r1-chat', async (req, res) => {
const startTime = Date.now();
try {
if (!deepseek) {
return res.status(500).json({ message: 'DeepSeek API key not configured' });
}
let { chatHistory, newValue, uploadedFiles } = req.body;
chatHistory = chatHistory.filter(msg => msg.role !== 'system');
// Keep the original user message clean for chat history
const cleanUserMessage = newValue;
// Prepare context for the AI
let aiContext = '';
if (uploadedFiles && uploadedFiles.length > 0) {
const filesContext = uploadedFiles.map(file =>
`File: ${file.name} (${file.type})\nContent:\n${file.content}`
).join('\n\n');
aiContext = `Uploaded files context:\n${filesContext}\n\n`;
}
// Combine context with user message for AI
const aiUserMessage = aiContext ? `${aiContext}User query: ${newValue}` : newValue;
// Log token usage and context info
const totalTokens = estimateTokenCount(aiUserMessage);
const contextSize = aiContext ? Math.round(aiContext.length / 1024 * 100) / 100 : 0;
console.log(`🤖 DeepSeek: ${totalTokens} tokens, ${contextSize}KB context, ${uploadedFiles?.length || 0} files`);
const response = await deepseek.chat.completions.create({
model: 'deepseek-chat',
messages: [
...chatHistory,
{ role: 'user', content: aiUserMessage }
]
});
const responseTime = Date.now() - startTime;
console.log(`✅ DeepSeek response: ${responseTime}ms`);
const newChatHistory = [
...chatHistory,
{ role: 'user', content: cleanUserMessage },
{ role: 'assistant', content: response.choices[0].message.content, name: 'DeepSeek' }
];
res.json(newChatHistory);
} catch (error) {
const responseTime = Date.now() - startTime;
console.error(`❌ DeepSeek error (${responseTime}ms):`, error.message);
res.status(500).json({ message: `Server error: ${error.message}` });
}
});
// CouchDB Chat Persistence Endpoints
// Save chat to CouchDB
app.post('/api/save-chat', async (req, res) => {
try {
const { chatHistory, uploadedFiles, patientId = 'demo_patient_001' } = req.body;
if (!chatHistory || chatHistory.length === 0) {
return res.status(400).json({ message: 'No chat history to save' });
}
console.log(`💾 Attempting to save chat with ${chatHistory.length} messages`);
const chatDoc = {
_id: `chat_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
patientId,
chatHistory,
uploadedFiles: uploadedFiles || [],
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
participantCount: chatHistory.filter(msg => msg.role === 'user').length,
messageCount: chatHistory.length
};
// Use Cloudant client
const result = await couchDBClient.saveChat(chatDoc);
console.log(`💾 Chat saved to ${couchDBClient.getServiceInfo().isCloudant ? 'Cloudant' : 'CouchDB'}: ${result.id}`);
res.json({
success: true,
chatId: result._id,
message: 'Chat saved successfully'
});
} catch (error) {
console.error('❌ Save chat error:', error);
console.error('❌ Error details:', {
message: error.message,
stack: error.stack
});
res.status(500).json({ message: `Failed to save chat: ${error.message}` });
}
});
// Load saved chats for a patient
app.get('/api/load-chats/:patientId?', async (req, res) => {
try {
const patientId = req.params.patientId || 'demo_patient_001';
// Use Cloudant client
const allChats = await couchDBClient.getAllChats();
const chats = allChats
.filter(chat => chat.patientId === patientId)
.map(chat => ({
id: chat._id,
patientId: chat.patientId,
createdAt: chat.createdAt,
updatedAt: chat.updatedAt,
participantCount: chat.participantCount,
messageCount: chat.messageCount,
chatHistory: chat.chatHistory,
uploadedFiles: chat.uploadedFiles || []
}))
.sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt));
console.log(`📋 Loaded ${chats.length} chats for patient ${patientId}`);
res.json(chats);
} catch (error) {
console.error('❌ Load chats error:', error);
res.status(500).json({ message: `Failed to load chats: ${error.message}` });
}
});
// Load a specific chat by ID
app.get('/api/load-chat/:chatId', async (req, res) => {
try {
const { chatId } = req.params;
// Use Cloudant client
const chat = await couchDBClient.getChat(chatId);
if (!chat) {
return res.status(404).json({ message: 'Chat not found' });
}
console.log(`📄 Loaded chat: ${chatId}`);
res.json({
id: chat._id,
patientId: chat.patientId,
chatHistory: chat.chatHistory,
uploadedFiles: chat.uploadedFiles || [],
createdAt: chat.createdAt,
updatedAt: chat.updatedAt
});
} catch (error) {
console.error('❌ Load chat error:', error);
res.status(500).json({ message: `Failed to load chat: ${error.message}` });
}
});
// Delete a chat
app.delete('/api/delete-chat/:chatId', async (req, res) => {
try {
const { chatId } = req.params;
// Use Cloudant client
await couchDBClient.deleteChat(chatId);
console.log(`🗑️ Deleted chat: ${chatId}`);
res.json({ success: true, message: 'Chat deleted successfully' });
} catch (error) {
console.error('❌ Delete chat error:', error);
res.status(500).json({ message: `Failed to delete chat: ${error.message}` });
}
});
// DigitalOcean API endpoints
const DIGITALOCEAN_API_KEY = process.env.DIGITALOCEAN_TOKEN;
const DIGITALOCEAN_BASE_URL = 'https://api.digitalocean.com';
// Helper function for DigitalOcean API requests
const doRequest = async (endpoint, options = {}) => {
if (!DIGITALOCEAN_API_KEY) {
throw new Error('DigitalOcean API key not configured');
}
const url = `${DIGITALOCEAN_BASE_URL}${endpoint}`;
const headers = {
'Authorization': `Bearer ${DIGITALOCEAN_API_KEY}`,
'Content-Type': 'application/json',
...options.headers
};
const config = {
headers,
...options
};
// Log the request details for debugging agent creation
if (options.method === 'POST' && endpoint.includes('/agents')) {
console.log('🌐 DIGITALOCEAN API REQUEST DETAILS:');
console.log('=====================================');
console.log(`URL: ${url}`);
console.log(`Method: ${config.method || 'GET'}`);
console.log(`Headers: ${JSON.stringify(headers, null, 2)}`);
console.log(`Body: ${options.body}`);
console.log('=====================================');
}
const response = await fetch(url, config);
if (!response.ok) {
const errorText = await response.text();
console.error(`❌ DigitalOcean API Error Response:`);
console.error(`Status: ${response.status}`);
console.error(`Headers: ${JSON.stringify(Object.fromEntries(response.headers.entries()), null, 2)}`);
console.error(`Body: ${errorText}`);
throw new Error(`DigitalOcean API error: ${response.status} - ${errorText}`);
}
return response.json();
};
// List agents
app.get('/api/agents', async (req, res) => {
try {
const agents = await doRequest('/v2/gen-ai/agents');
console.log(`🤖 Listed ${agents.agents?.length || 0} agents`);
// Transform agents to match frontend expectations
const transformedAgents = (agents.agents || []).map(agent => ({
id: agent.uuid,
name: agent.name,
description: agent.instruction || '',
model: agent.model?.name || 'Unknown',
status: agent.deployment?.status?.toLowerCase().replace('status_', '') || 'unknown',
instructions: agent.instruction || '',
uuid: agent.uuid,
deployment: agent.deployment,
created_at: agent.created_at,
updated_at: agent.updated_at
}));
res.json(transformedAgents);
} catch (error) {
console.error('❌ List agents error:', error);
res.status(500).json({ message: `Failed to list agents: ${error.message}` });
}
});
// Test route to check if API routes are working
app.get('/api/test', (req, res) => {
console.log('🔍 /api/test route hit');
res.json({ message: 'API routes are working' });
});
// Get current agent
app.get('/api/current-agent', async (req, res) => {
try {
if (!process.env.DIGITALOCEAN_GENAI_ENDPOINT) {
console.log('🤖 No agent endpoint configured');
return res.json({ agent: null });
}
// Extract agent UUID from the endpoint URL
const endpointUrl = process.env.DIGITALOCEAN_GENAI_ENDPOINT;
console.log(`🔍 Endpoint URL: ${endpointUrl}`);
// Get all agents and find the one with matching deployment URL
const agentsResponse = await doRequest('/v2/gen-ai/agents');
const agents = agentsResponse.agents || agentsResponse.data?.agents || [];
// Find the agent whose deployment URL matches our endpoint
const matchingAgent = agents.find(agent =>
agent.deployment?.url === endpointUrl.replace('/api/v1', '')
);
if (!matchingAgent) {
console.log('❌ No agent found with matching deployment URL');
return res.json({ agent: null, message: 'No agent found with this deployment URL' });
}
const agentId = matchingAgent.uuid;
console.log(`🔍 Found matching agent: ${matchingAgent.name} (${agentId})`);
// Get agent details including associated knowledge bases
const agentResponse = await doRequest(`/v2/gen-ai/agents/${agentId}`);
const agentData = agentResponse.agent || agentResponse.data?.agent || agentResponse.data || agentResponse;
console.log(`📋 Agent details from API:`, JSON.stringify(agentData, null, 2));
// Extract knowledge base information
let connectedKnowledgeBases = [];
let warning = null;
if (agentData.knowledge_bases && agentData.knowledge_bases.length > 0) {
if (agentData.knowledge_bases.length > 1) {
// Multiple KBs detected - this is a safety issue
warning = `⚠️ WARNING: Agent has ${agentData.knowledge_bases.length} knowledge bases attached. This can cause data contamination and hallucinations. Please check the DigitalOcean dashboard and ensure only one KB is attached.`;
console.log(`🚨 Multiple KBs detected: ${agentData.knowledge_bases.length} KBs attached to agent`);
}
connectedKnowledgeBases = agentData.knowledge_bases; // Return ALL connected KBs
console.log(`📚 Found ${connectedKnowledgeBases.length} associated KBs:`);
connectedKnowledgeBases.forEach((kb, index) => {
console.log(` ${index + 1}. ${kb.name} (${kb.uuid})`);
});
} else {
console.log(`📚 No knowledge bases associated with agent`);
}
// Transform agent data for frontend
const transformedAgent = {
id: agentData.uuid,
name: agentData.name,
description: agentData.instruction || '',
model: agentData.model?.name || 'Unknown',
status: agentData.deployment?.status?.toLowerCase().replace('status_', '') || 'unknown',
instructions: agentData.instruction || '',
uuid: agentData.uuid,
deployment: agentData.deployment,
knowledgeBase: connectedKnowledgeBases[0], // Keep first KB for backward compatibility
knowledgeBases: connectedKnowledgeBases // Add all connected KBs
};
const endpoint = process.env.DIGITALOCEAN_GENAI_ENDPOINT + '/api/v1';
console.log(`🤖 Current agent: ${transformedAgent.name} (${transformedAgent.id})`);
if (connectedKnowledgeBases.length > 0) {
console.log(`📚 Current KB: ${connectedKnowledgeBases[0].name} (${connectedKnowledgeBases[0].uuid})`);
}
const response = {
agent: transformedAgent,
endpoint: endpoint
};
if (warning) {
response.warning = warning;
}
res.json(response);
} catch (error) {
console.error('❌ Get current agent error:', error);
res.status(500).json({ message: `Failed to get current agent: ${error.message}` });
}
});
// Create agent
app.post('/api/agents', async (req, res) => {
try {
const { name, description, model, model_uuid, instructions } = req.body;
// Validate agent name - DigitalOcean only allows lowercase, numbers, and dashes
const validName = name.toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
console.log(`🔍 Original name: "${name}" -> Valid name: "${validName}"`);
// Determine which model to use - frontend sends model_uuid, backend expects model name
let selectedModel;
if (model_uuid) {
// Frontend sent model_uuid, find the model by UUID
const models = await doRequest('/v2/gen-ai/models');
const modelArray = models.models || [];
if (!Array.isArray(modelArray)) {
return res.status(500).json({ message: 'Failed to get models from DigitalOcean API' });
}
// Filter out models without names and log for debugging
const validModels = modelArray.filter(m => m && m.name);
console.log(`🔍 Found ${validModels.length} valid models out of ${modelArray.length} total`);
console.log(`🔍 Looking for model UUID: ${model_uuid}`);
console.log(`🔍 Available models: ${validModels.map(m => `${m.name} (${m.uuid})`).join(', ')}`);
selectedModel = validModels.find(m => m.uuid === model_uuid);
if (!selectedModel) {
return res.status(400).json({ message: `Model with UUID '${model_uuid}' not found. Available models: ${validModels.map(m => `${m.name} (${m.uuid})`).join(', ')}` });
}
} else if (model) {
// Backend expects model name, find by name
const models = await doRequest('/v2/gen-ai/models');
const modelArray = models.models || [];
if (!Array.isArray(modelArray)) {
return res.status(500).json({ message: 'Failed to get models from DigitalOcean API' });
}
// Filter out models without names and log for debugging
const validModels = modelArray.filter(m => m && m.name);
console.log(`🔍 Found ${validModels.length} valid models out of ${modelArray.length} total`);
console.log(`🔍 Looking for model: ${model}`);
console.log(`🔍 Available models: ${validModels.map(m => m.name).join(', ')}`);
selectedModel = validModels.find(m => m.name.toLowerCase().includes(model.toLowerCase()));
if (!selectedModel) {
return res.status(400).json({ message: `Model '${model}' not found. Available models: ${validModels.map(m => m.name).join(', ')}` });
}
} else {
return res.status(400).json({ message: 'Either model or model_uuid is required' });
}
// Get available regions
const regions = await doRequest('/v2/gen-ai/regions');
const defaultRegion = regions.regions[0]?.region || 'tor1';
const agentData = {
name: validName,
description,
model_uuid: selectedModel.uuid,
instruction: instructions,
region: defaultRegion,
project_id: process.env.DIGITALOCEAN_PROJECT_ID || '37455431-84bd-4fa2-94cf-e8486f8f8c5e' // Default project ID
};
// Log the exact payload being sent to DigitalOcean
console.log('🚀 DIGITALOCEAN AGENT CREATION PAYLOAD:');
console.log('========================================');
console.log(JSON.stringify(agentData, null, 2));
console.log('========================================');
console.log(`🔗 Endpoint: ${process.env.DIGITALOCEAN_BASE_URL}/v2/gen-ai/agents`);
console.log(`🔑 Token: ${process.env.DIGITALOCEAN_TOKEN ? 'Present' : 'Missing'}`);
console.log(`📋 Project ID: ${agentData.project_id}`);
const agent = await doRequest('/v2/gen-ai/agents', {
method: 'POST',
body: JSON.stringify(agentData)
});
console.log(`🤖 Created agent: ${validName}`);
res.json(agent.data);
} catch (error) {
console.error('❌ Create agent error:', error);
res.status(500).json({ message: `Failed to create agent: ${error.message}` });
}