-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-all-ai-services.js
More file actions
583 lines (492 loc) · 17.3 KB
/
test-all-ai-services.js
File metadata and controls
583 lines (492 loc) · 17.3 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
/**
* Comprehensive AI Services Test Suite
* Tests all 5 AI services with different models and scenarios
*/
const fs = require('fs');
const path = require('path');
require('dotenv').config({ path: '.env.local' });
// Global fetch for Node.js
const fetch = globalThis.fetch;
const APP_URL = 'http://localhost:3000';
// Test models from different providers
const testModels = [
'llama-3.1-8b-instant', // Groq - Fast
'llama-3.1-8b-instruct-hf', // HF - Coding
'deepseek-v3.2', // HF - Coding
'rnj-1-instruct', // HF - Conversation
'gpt-oss-20b', // HF - General
'gemini-2.5-flash', // Google - Multimodal
'gemini-flash-latest', // Google - Latest
'gemini-2.5-flash-lite', // Google - Lite
'auto' // Auto routing
];
// Colors for console output
const colors = {
reset: '\x1b[0m',
bold: '\x1b[1m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
magenta: '\x1b[35m',
cyan: '\x1b[36m'
};
function log(color, message) {
console.log(`${colors[color]}${message}${colors.reset}`);
}
// Create simple test image (base64 encoded 1x1 pixel PNG)
const testImageBase64 = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=';
// Create simple test PDF (minimal base64 encoded PDF)
const testPdfBase64 = 'data:application/pdf;base64,JVBERi0xLjQKMSAwIG9iago8PAovVHlwZSAvQ2F0YWxvZwovUGFnZXMgMiAwIFIKPj4KZW5kb2JqCjIgMCBvYmoKPDwKL1R5cGUgL1BhZ2VzCi9LaWRzIFszIDAgUl0KL0NvdW50IDEKPJ4KZW5kb2JqCjMgMCBvYmoKPDwKL1R5cGUgL1BhZ2UKL1BhcmVudCAyIDAgUgovTWVkaWFCb3ggWzAgMCAxMjAgMTIwXQo+PgplbmRvYmoKeHJlZgowIDQKMDAwMDAwMDAwMCA2NTUzNSBmCjAwMDAwMDAwMTAgMDAwMDAgbgowMDAwMDAwMDUzIDAwMDAwIG4KMDAwMDAwMDEyNSAwMDAwMCBuCnRyYWlsZXIKPDwKL1NpemUgNAovUm9vdCAxIDAgUgo+PgpzdGFydHhyZWYKMTg0CiUlRU9G';
/**
* Test 1: Problem Solving Service
*/
async function testSolveService() {
log('cyan', '\n🧮 Testing Problem Solving Service...');
const testCases = [
{
name: 'Math Problem',
data: {
problem: 'What is 15 + 27?',
tone: 'helpful',
technicalLevel: 'beginner'
}
},
{
name: 'Coding Problem',
data: {
problem: 'Write a simple Python function to reverse a string',
tone: 'formal',
technicalLevel: 'intermediate'
}
},
{
name: 'Logic Problem',
data: {
problem: 'If all roses are flowers and some flowers are red, can we conclude that some roses are red?',
tone: 'casual',
technicalLevel: 'expert'
}
}
];
const results = [];
for (const testCase of testCases) {
for (const model of testModels.slice(0, 2)) { // Test with fewer models for speed
log('yellow', ` Testing ${testCase.name} with ${model}...`);
try {
const response = await fetch(`${APP_URL}/api/ai/solve`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
...testCase.data,
preferredModel: model === 'auto' ? undefined : model
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
if (data.error) {
throw new Error(data.error);
}
results.push({
service: 'solve',
testCase: testCase.name,
model,
success: true,
modelUsed: data.modelUsed,
responseLength: data.solution?.length || 0
});
log('green', ` ✅ ${testCase.name} (${model}): ${data.solution?.substring(0, 50)}...`);
log('blue', ` Model used: ${data.modelUsed}`);
} catch (error) {
results.push({
service: 'solve',
testCase: testCase.name,
model,
success: false,
error: error.message
});
log('red', ` ❌ ${testCase.name} (${model}): ${error.message}`);
}
// Small delay to avoid overwhelming the server
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
return results;
}
/**
* Test 2: Summarization Service
*/
async function testSummarizeService() {
log('cyan', '\n📝 Testing Summarization Service...');
const testCases = [
{
name: 'Short Article',
data: {
text: 'Artificial Intelligence (AI) is a branch of computer science that aims to create intelligent machines that can think and work like humans. Some of the activities computers with artificial intelligence are designed for include speech recognition, learning, planning, and problem solving. AI is used in various industries including healthcare, finance, transportation, and entertainment. Machine learning, a subset of AI, enables computers to learn and improve from experience without being explicitly programmed.',
style: 'brief'
}
},
{
name: 'Technical Content',
data: {
text: 'React is a JavaScript library for building user interfaces. It was developed by Facebook and is now maintained by Facebook and the community. The main purpose of React is to be fast, scalable, and simple. It works only on user interfaces in the application. This corresponds to the view in the MVC template. It can be used with a combination of other JavaScript libraries or frameworks, such as Angular JS in MVC. React allows developers to create large web applications that can change data, without reloading the page. The main purpose of React is to be fast, scalable, and simple.',
style: 'detailed'
}
}
];
const results = [];
for (const testCase of testCases) {
for (const model of testModels.slice(0, 2)) { // Test with fewer models
log('yellow', ` Testing ${testCase.name} with ${model}...`);
try {
const response = await fetch(`${APP_URL}/api/ai/summarize`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
...testCase.data,
preferredModel: model === 'auto' ? undefined : model
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
if (data.error) {
throw new Error(data.error);
}
results.push({
service: 'summarize',
testCase: testCase.name,
model,
success: true,
modelUsed: data.modelUsed,
responseLength: data.summary?.length || 0
});
log('green', ` ✅ ${testCase.name} (${model}): ${data.summary?.substring(0, 50)}...`);
log('blue', ` Model used: ${data.modelUsed}`);
} catch (error) {
results.push({
service: 'summarize',
testCase: testCase.name,
model,
success: false,
error: error.message
});
log('red', ` ❌ ${testCase.name} (${model}): ${error.message}`);
}
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
return results;
}
/**
* Test 3: Search Service
*/
async function testSearchService() {
log('cyan', '\n🔍 Testing Search Service...');
const testCases = [
{
name: 'Tech Query',
data: {
query: 'What is the latest version of Node.js?'
}
},
{
name: 'General Knowledge',
data: {
query: 'What is the capital of Japan?'
}
}
];
const results = [];
for (const testCase of testCases) {
for (const model of testModels.slice(0, 2)) { // Test with fewer models
log('yellow', ` Testing ${testCase.name} with ${model}...`);
try {
const response = await fetch(`${APP_URL}/api/ai/search`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
...testCase.data,
preferredModel: model === 'auto' ? undefined : model
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
if (data.error) {
throw new Error(data.error);
}
results.push({
service: 'search',
testCase: testCase.name,
model,
success: true,
modelUsed: data.modelUsed,
responseLength: data.answer?.length || 0,
sourcesCount: data.sources?.length || 0
});
log('green', ` ✅ ${testCase.name} (${model}): ${data.answer?.substring(0, 50)}...`);
log('magenta', ` Sources: ${data.sources?.length || 0} found`);
log('blue', ` Model used: ${data.modelUsed}`);
} catch (error) {
results.push({
service: 'search',
testCase: testCase.name,
model,
success: false,
error: error.message
});
log('red', ` ❌ ${testCase.name} (${model}): ${error.message}`);
}
// Longer delay for search as it involves external API calls
await new Promise(resolve => setTimeout(resolve, 2000));
}
}
return results;
}
/**
* Test 4: Image Solver Service
*/
async function testImageSolverService() {
log('cyan', '\n🖼️ Testing Image Solver Service...');
// Only test with multimodal models for image processing
const multimodalModels = ['gemini-2.5-flash', 'auto'];
const testCases = [
{
name: 'Math Problem Image',
data: {
imageDataUri: testImageBase64,
problemType: 'math'
}
},
{
name: 'General Image Analysis',
data: {
imageDataUri: testImageBase64,
problemType: 'general'
}
}
];
const results = [];
for (const testCase of testCases) {
for (const model of multimodalModels) {
log('yellow', ` Testing ${testCase.name} with ${model}...`);
try {
const response = await fetch(`${APP_URL}/api/ai/image-solver`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
...testCase.data,
preferredModel: model === 'auto' ? undefined : model
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
if (data.error) {
throw new Error(data.error);
}
results.push({
service: 'image-solver',
testCase: testCase.name,
model,
success: true,
modelUsed: data.modelUsed,
responseLength: data.solution?.length || 0,
recognized: !!data.recognizedContent
});
log('green', ` ✅ ${testCase.name} (${model}): ${data.solution?.substring(0, 50)}...`);
log('magenta', ` Recognized: ${data.recognizedContent?.substring(0, 30)}...`);
log('blue', ` Model used: ${data.modelUsed}`);
} catch (error) {
results.push({
service: 'image-solver',
testCase: testCase.name,
model,
success: false,
error: error.message
});
log('red', ` ❌ ${testCase.name} (${model}): ${error.message}`);
}
await new Promise(resolve => setTimeout(resolve, 2000));
}
}
return results;
}
/**
* Test 5: PDF Analyzer Service
*/
async function testPdfAnalyzerService() {
log('cyan', '\n📄 Testing PDF Analyzer Service...');
// Test with models that can handle document analysis
const documentModels = ['gemini-2.5-flash', 'auto'];
const testCases = [
{
name: 'PDF Analysis',
data: {
pdfDataUri: testPdfBase64,
question: 'What is the content of this PDF?'
}
},
{
name: 'PDF Summary',
data: {
pdfDataUri: testPdfBase64,
question: 'Summarize the main points of this document.'
}
}
];
const results = [];
for (const testCase of testCases) {
for (const model of documentModels) {
log('yellow', ` Testing ${testCase.name} with ${model}...`);
try {
const response = await fetch(`${APP_URL}/api/ai/pdf-analyzer`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
...testCase.data,
preferredModel: model === 'auto' ? undefined : model
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
if (data.error) {
throw new Error(data.error);
}
results.push({
service: 'pdf-analyzer',
testCase: testCase.name,
model,
success: true,
modelUsed: data.modelUsed,
responseLength: data.answer?.length || 0
});
log('green', ` ✅ ${testCase.name} (${model}): ${data.answer?.substring(0, 50)}...`);
log('blue', ` Model used: ${data.modelUsed}`);
} catch (error) {
results.push({
service: 'pdf-analyzer',
testCase: testCase.name,
model,
success: false,
error: error.message
});
log('red', ` ❌ ${testCase.name} (${model}): ${error.message}`);
}
await new Promise(resolve => setTimeout(resolve, 2000));
}
}
return results;
}
/**
* Generate comprehensive test report
*/
function generateReport(allResults) {
log('bold', '\n📊 COMPREHENSIVE TEST REPORT');
log('bold', '='.repeat(50));
// Calculate statistics
let totalTests = 0;
let totalSuccess = 0;
const serviceStats = {};
const modelStats = {};
allResults.forEach(result => {
totalTests++;
if (result.success) totalSuccess++;
// Service statistics
if (!serviceStats[result.service]) {
serviceStats[result.service] = { total: 0, success: 0 };
}
serviceStats[result.service].total++;
if (result.success) serviceStats[result.service].success++;
// Model statistics
if (result.modelUsed) {
if (!modelStats[result.modelUsed]) {
modelStats[result.modelUsed] = { total: 0, success: 0 };
}
modelStats[result.modelUsed].total++;
if (result.success) modelStats[result.modelUsed].success++;
}
});
// Overall statistics
const rate = Math.round(totalSuccess/totalTests*100);
const status = rate === 100 ? '✅' : rate >= 80 ? '⚠️' : '❌';
log('green', `\n✅ Overall Success Rate: ${totalSuccess}/${totalTests} (${rate}%)`);
// Service breakdown
log('cyan', '\n📋 Service Breakdown:');
Object.entries(serviceStats).forEach(([service, stats]) => {
const rate = Math.round(stats.success/stats.total*100);
const status = rate === 100 ? '✅' : rate >= 80 ? '⚠️' : '❌';
log('blue', ` ${status} ${service}: ${stats.success}/${stats.total} (${rate}%)`);
});
// Model performance
log('cyan', '\n🤖 Model Performance:');
Object.entries(modelStats).forEach(([model, stats]) => {
const rate = Math.round(stats.success/stats.total*100);
const status = rate === 100 ? '✅' : rate >= 80 ? '⚠️' : '❌';
log('magenta', ` ${status} ${model}: ${stats.success}/${stats.total} (${rate}%)`);
});
// Failed tests
const failures = allResults.filter(r => !r.success);
if (failures.length > 0) {
log('red', '\n❌ Failed Tests:');
failures.forEach(failure => {
log('red', ` ${failure.service}/${failure.testCase} (${failure.model}): ${failure.error}`);
});
}
// Save detailed report to file
const reportData = {
timestamp: new Date().toISOString(),
totalTests: totalTests,
successfulTests: totalSuccess,
successRate: rate,
serviceStats,
modelStats,
allResults
};
fs.writeFileSync('ai-services-test-report.json', JSON.stringify(reportData, null, 2));
log('blue', '\n📄 Detailed report saved to: ai-services-test-report.json');
log('green', '\n🎉 Test Suite Complete!');
}
/**
* Main test runner
*/
async function runAllTests() {
log('bold', '🚀 Starting Comprehensive AI Services Test Suite...');
log('yellow', 'Testing all 5 AI services with multiple models and scenarios\n');
// Wait for server to be ready
await new Promise(resolve => setTimeout(resolve, 2000));
const allResults = [];
try {
// Run all service tests
log('bold', '🧮 Testing Problem Solving Service...');
const solveResults = await testSolveService();
allResults.push(...solveResults);
log('bold', '📝 Testing Summarization Service...');
const summarizeResults = await testSummarizeService();
allResults.push(...summarizeResults);
log('bold', '🔍 Testing Search Service...');
const searchResults = await testSearchService();
allResults.push(...searchResults);
log('bold', '🖼️ Testing Image Solver Service...');
const imageResults = await testImageSolverService();
allResults.push(...imageResults);
log('bold', '📄 Testing PDF Analyzer Service...');
const pdfResults = await testPdfAnalyzerService();
allResults.push(...pdfResults);
// Generate comprehensive report
generateReport(allResults);
} catch (error) {
log('red', `\n💥 Test suite failed: ${error.message}`);
console.error(error);
}
}
// Run the test suite
runAllTests();