-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathagent_api_tester.js
More file actions
997 lines (891 loc) Β· 38.2 KB
/
agent_api_tester.js
File metadata and controls
997 lines (891 loc) Β· 38.2 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
// Comprehensive AI Agent API Tools Testing Suite
// Tests all backend API endpoints used by AI agents
import dotenv from 'dotenv';
dotenv.config();
import axios from 'axios';
// Import BackendTools class from query.js
class BackendTools {
constructor(baseURL = `http://localhost:${process.env.PORT || 3000}`) {
this.baseURL = baseURL;
this.axiosInstance = axios.create({
baseURL: this.baseURL,
timeout: 10000,
headers: {
'Content-Type': 'application/json',
'X-Test-Mode': 'true' // Enable test mode to bypass auth
}
});
}
// Set authentication headers for API calls
setAuth(userId, authToken) {
this.axiosInstance.defaults.headers.common['X-Test-Mode'] = 'true';
this.axiosInstance.defaults.headers.common['X-User-ID'] = userId;
// Don't set Authorization for test mode
}
// Journal API Tools
async createJournal(title = "untitled", content = "") {
try {
const response = await this.axiosInstance.post('/api/journals', { title, content });
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
async getJournalById(id) {
try {
const response = await this.axiosInstance.get(`/api/journals/${id}`);
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
async getJournalHistory(limit = 10, page = 1) {
try {
const response = await this.axiosInstance.get('/api/journals', {
params: { limit, page }
});
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
async updateJournal(id, title, content) {
try {
const response = await this.axiosInstance.put(`/api/journals/${id}`, { title, content });
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
async searchJournals(keyword, tags = '', from = null, to = null) {
try {
const params = { keyword };
if (tags) params.tags = tags;
if (from) params.from = from;
if (to) params.to = to;
const response = await this.axiosInstance.get('/api/journals/search', { params });
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
async addTagsToJournal(journalId, tags) {
try {
const response = await this.axiosInstance.post('/api/journals/tags', { journalId, tags });
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
async removeTagsFromJournal(journalId, tags) {
try {
const response = await this.axiosInstance.delete('/api/journals/tags', {
data: { journalId, tags }
});
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
async getJournalVersions(id, limit = 10, page = 1) {
try {
const response = await this.axiosInstance.get(`/api/journals/versions/${id}`, {
params: { limit, page }
});
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
async renameJournal(id, name) {
try {
const response = await this.axiosInstance.post(`/api/journals/rename/${id}`, { name });
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
async deleteJournal(id) {
try {
const response = await this.axiosInstance.delete(`/api/journals/delete/${id}`);
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
// Chat API Tools
async createChat() {
try {
const response = await this.axiosInstance.post('/api/chats');
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
async getChatById(id) {
try {
const response = await this.axiosInstance.get(`/api/chats/${id}`);
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
async getChatHistory(limit = 10, page = 1) {
try {
const response = await this.axiosInstance.get('/api/chats', {
params: { limit, page }
});
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
async updateChatName(id, name) {
try {
const response = await this.axiosInstance.post(`/api/chats/rename/${id}`, { name });
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
async deleteChat(id) {
try {
const response = await this.axiosInstance.delete(`/api/chats/delete/${id}`);
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
// RAG Memory API Tools
async createMemory(memoryType, title, content, metadata = {}, tags = []) {
try {
const response = await this.axiosInstance.post('/api/rag', {
memoryType,
title,
content,
metadata,
tags
});
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
async getUserMemories(memoryType = null, limit = 50, page = 1, sortBy = 'relevanceScore') {
try {
const params = { limit, page, sortBy };
if (memoryType) params.memoryType = memoryType;
const response = await this.axiosInstance.get('/api/rag', { params });
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
async getMemoryById(id) {
try {
const response = await this.axiosInstance.get(`/api/rag/${id}`);
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
async updateMemory(id, updateData) {
try {
const response = await this.axiosInstance.put(`/api/rag/${id}`, updateData);
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
async searchMemories(query, memoryType = null, tags = null, limit = 20, minRelevance = 0.3) {
try {
const params = { query, limit, minRelevance };
if (memoryType) params.memoryType = memoryType;
if (tags) params.tags = tags;
const response = await this.axiosInstance.get('/api/rag/search', { params });
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
async getMemoriesByType(type, limit = 50, page = 1) {
try {
const response = await this.axiosInstance.get(`/api/rag/type/${type}`, {
params: { limit, page }
});
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
async addTagsToMemory(id, tags) {
try {
const response = await this.axiosInstance.post(`/api/rag/${id}/tags`, { tags });
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
async removeTagsFromMemory(id, tags) {
try {
const response = await this.axiosInstance.delete(`/api/rag/${id}/tags`, {
data: { tags }
});
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
async deleteMemory(id, permanent = false) {
try {
const response = await this.axiosInstance.delete(`/api/rag/${id}`, {
params: { permanent }
});
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
async getMemoryStats() {
try {
const response = await this.axiosInstance.get('/api/rag/stats');
return { success: true, data: response.data };
} catch (error) {
return { success: false, error: error.response?.data?.message || error.message };
}
}
}
console.log('π§ͺ AI AGENT API TOOLS TESTING SUITE');
console.log('π― Testing all backend API endpoints used by AI agents');
console.log('π Will iterate until all API calls work properly');
console.log('=' .repeat(70));
class AgentAPITester {
constructor() {
this.baseURL = `http://localhost:${process.env.PORT || 3000}`;
this.testUserId = '507f1f77bcf86cd799439011'; // Valid ObjectId
this.testAuthToken = 'test-auth-token'; // Not used in test mode
this.backendTools = new BackendTools(this.baseURL);
this.testResults = [];
this.createdResources = {
journals: [],
chats: [],
memories: []
};
this.iterationCount = 0;
this.maxIterations = 5;
}
async initialize() {
console.log('\nπ§ Initializing API tester...');
// Set authentication for backend tools
this.backendTools.setAuth(this.testUserId, this.testAuthToken);
// Test server connectivity with test mode - expect 404 for empty journals
try {
const response = await axios.get(`${this.baseURL}/api/journals`, {
headers: {
'X-Test-Mode': 'true',
'X-User-ID': this.testUserId
},
timeout: 5000,
validateStatus: function (status) {
// Accept 200 (has journals) and 404 (no journals) as successful
return status === 200 || status === 404;
}
});
console.log('β
Server connectivity confirmed');
if (response.status === 404) {
console.log(' π No existing journals (expected for fresh test)');
}
return true;
} catch (error) {
console.error('β Server connectivity failed:', error.message);
if (error.response) {
console.error(' Response status:', error.response.status);
console.error(' Response data:', error.response.data);
}
return false;
}
}
// Test all Journal API tools
async testJournalAPIs() {
console.log('\nπ TESTING JOURNAL API TOOLS');
console.log('β'.repeat(50));
const journalTests = [
{
name: 'createJournal',
test: async () => {
const result = await this.backendTools.createJournal(
'Test Journal for API Testing',
'This is a test journal content for API validation.'
);
if (result.success && result.data) {
this.createdResources.journals.push(result.data._id || result.data.id);
return { success: true, data: result.data };
}
return result;
},
expectedFields: ['_id', 'title', 'content', 'userId']
},
{
name: 'getJournalHistory',
test: async () => {
return await this.backendTools.getJournalHistory(10, 1);
},
expectedFields: ['length'] // Array response
},
{
name: 'getJournalById',
test: async () => {
if (this.createdResources.journals.length === 0) {
return { success: false, error: 'No journal ID available for testing' };
}
const journalId = this.createdResources.journals[0];
return await this.backendTools.getJournalById(journalId);
},
expectedFields: ['_id', 'title', 'content'],
dependencies: ['createJournal']
},
{
name: 'updateJournal',
test: async () => {
if (this.createdResources.journals.length === 0) {
return { success: false, error: 'No journal ID available for testing' };
}
const journalId = this.createdResources.journals[0];
return await this.backendTools.updateJournal(
journalId,
'Updated Test Journal',
'This is updated content for testing.'
);
},
expectedFields: ['_id', 'title', 'content'],
dependencies: ['createJournal']
},
{
name: 'searchJournals',
test: async () => {
return await this.backendTools.searchJournals('test', '', null, null);
},
expectedFields: ['length'] // Array response
},
{
name: 'addTagsToJournal',
test: async () => {
if (this.createdResources.journals.length === 0) {
return { success: false, error: 'No journal ID available for testing' };
}
const journalId = this.createdResources.journals[0];
return await this.backendTools.addTagsToJournal(journalId, ['test', 'api', 'validation']);
},
expectedFields: ['message', 'journal'],
dependencies: ['createJournal']
},
{
name: 'removeTagsFromJournal',
test: async () => {
if (this.createdResources.journals.length === 0) {
return { success: false, error: 'No journal ID available for testing' };
}
const journalId = this.createdResources.journals[0];
return await this.backendTools.removeTagsFromJournal(journalId, ['test']);
},
expectedFields: ['message', 'journal'],
dependencies: ['addTagsToJournal']
},
{
name: 'getJournalVersions',
test: async () => {
if (this.createdResources.journals.length === 0) {
return { success: false, error: 'No journal ID available for testing' };
}
const journalId = this.createdResources.journals[0];
return await this.backendTools.getJournalVersions(journalId, 10, 1);
},
expectedFields: ['length'], // Array response
dependencies: ['createJournal']
},
{
name: 'renameJournal',
test: async () => {
if (this.createdResources.journals.length === 0) {
return { success: false, error: 'No journal ID available for testing' };
}
const journalId = this.createdResources.journals[0];
return await this.backendTools.renameJournal(journalId, 'Renamed Test Journal');
},
expectedFields: ['message'],
dependencies: ['createJournal']
}
];
return await this.runTestSuite('Journal API', journalTests);
}
// Test all Chat API tools
async testChatAPIs() {
console.log('\n㪠TESTING CHAT API TOOLS');
console.log('β'.repeat(50));
const chatTests = [
{
name: 'createChat',
test: async () => {
const result = await this.backendTools.createChat();
if (result.success && result.data) {
this.createdResources.chats.push(result.data._id || result.data.id);
return { success: true, data: result.data };
}
return result;
},
expectedFields: ['_id', 'userId']
},
{
name: 'getChatHistory',
test: async () => {
return await this.backendTools.getChatHistory(10, 1);
},
expectedFields: ['length'] // Array response
},
{
name: 'getChatById',
test: async () => {
if (this.createdResources.chats.length === 0) {
return { success: false, error: 'No chat ID available for testing' };
}
const chatId = this.createdResources.chats[0];
return await this.backendTools.getChatById(chatId);
},
expectedFields: ['_id', 'userId', 'messages'],
dependencies: ['createChat']
},
{
name: 'updateChatName',
test: async () => {
if (this.createdResources.chats.length === 0) {
return { success: false, error: 'No chat ID available for testing' };
}
const chatId = this.createdResources.chats[0];
return await this.backendTools.updateChatName(chatId, 'Test Chat Name');
},
expectedFields: [],
dependencies: ['createChat']
}
];
return await this.runTestSuite('Chat API', chatTests);
}
// Test all RAG Memory API tools
async testMemoryAPIs() {
console.log('\nπ§ TESTING RAG MEMORY API TOOLS');
console.log('β'.repeat(50));
const memoryTests = [
{
name: 'createMemory',
test: async () => {
const result = await this.backendTools.createMemory(
'user_preferences',
'Test Memory',
'This is a test memory for API validation.',
{ test: true },
['test', 'api', 'validation']
);
if (result.success && result.data) {
this.createdResources.memories.push(result.data._id || result.data.id);
return { success: true, data: result.data };
}
return result;
},
expectedFields: ['_id', 'memoryType', 'title', 'content']
},
{
name: 'getUserMemories',
test: async () => {
return await this.backendTools.getUserMemories('user_preferences', 10, 1, 'relevanceScore');
},
expectedFields: ['length'] // Array response
},
{
name: 'getMemoryById',
test: async () => {
if (this.createdResources.memories.length === 0) {
return { success: false, error: 'No memory ID available for testing' };
}
const memoryId = this.createdResources.memories[0];
return await this.backendTools.getMemoryById(memoryId);
},
expectedFields: ['_id', 'memoryType', 'title', 'content'],
dependencies: ['createMemory']
},
{
name: 'updateMemory',
test: async () => {
if (this.createdResources.memories.length === 0) {
return { success: false, error: 'No memory ID available for testing' };
}
const memoryId = this.createdResources.memories[0];
return await this.backendTools.updateMemory(memoryId, {
title: 'Updated Test Memory',
content: 'This is updated memory content for testing.'
});
},
expectedFields: ['_id', 'title', 'content'],
dependencies: ['createMemory']
},
{
name: 'searchMemories',
test: async () => {
return await this.backendTools.searchMemories('test', 'user_preferences', null, 10, 0.1);
},
expectedFields: ['length'] // Array response
},
{
name: 'getMemoriesByType',
test: async () => {
return await this.backendTools.getMemoriesByType('user_preferences', 10, 1);
},
expectedFields: ['length'] // Array response
},
{
name: 'addTagsToMemory',
test: async () => {
if (this.createdResources.memories.length === 0) {
return { success: false, error: 'No memory ID available for testing' };
}
const memoryId = this.createdResources.memories[0];
return await this.backendTools.addTagsToMemory(memoryId, ['additional', 'tags']);
},
expectedFields: ['message'],
dependencies: ['createMemory']
},
{
name: 'removeTagsFromMemory',
test: async () => {
if (this.createdResources.memories.length === 0) {
return { success: false, error: 'No memory ID available for testing' };
}
const memoryId = this.createdResources.memories[0];
return await this.backendTools.removeTagsFromMemory(memoryId, ['test']);
},
expectedFields: ['message'],
dependencies: ['addTagsToMemory']
},
{
name: 'getMemoryStats',
test: async () => {
return await this.backendTools.getMemoryStats();
},
expectedFields: ['totalMemories']
}
];
return await this.runTestSuite('Memory API', memoryTests);
}
// Run a test suite for a specific API category
async runTestSuite(suiteName, tests) {
console.log(`π Running ${suiteName} tests...`);
const suiteResults = {
suiteName,
totalTests: tests.length,
passedTests: 0,
failedTests: 0,
results: [],
issues: []
};
for (const testSpec of tests) {
console.log(` π§ͺ Testing ${testSpec.name}...`);
try {
const startTime = Date.now();
const result = await testSpec.test();
const endTime = Date.now();
const responseTime = endTime - startTime;
const validation = this.validateTestResult(result, testSpec);
const testResult = {
name: testSpec.name,
success: validation.isValid,
responseTime,
result: validation.isValid ? result : null,
error: validation.isValid ? null : validation.error,
issues: validation.issues,
expectedFields: testSpec.expectedFields
};
suiteResults.results.push(testResult);
if (validation.isValid) {
suiteResults.passedTests++;
console.log(` β
${testSpec.name} passed (${responseTime}ms)`);
} else {
suiteResults.failedTests++;
console.log(` β ${testSpec.name} failed: ${validation.error}`);
if (validation.issues.length > 0) {
validation.issues.forEach(issue => {
console.log(` - ${issue}`);
suiteResults.issues.push(`${testSpec.name}: ${issue}`);
});
}
}
} catch (error) {
suiteResults.failedTests++;
suiteResults.results.push({
name: testSpec.name,
success: false,
error: error.message,
issues: [`Unexpected error: ${error.message}`]
});
console.log(` π₯ ${testSpec.name} threw error: ${error.message}`);
suiteResults.issues.push(`${testSpec.name}: Unexpected error - ${error.message}`);
}
}
console.log(`\nπ ${suiteName} Results: ${suiteResults.passedTests}/${suiteResults.totalTests} passed`);
return suiteResults;
}
// Validate test result against expectations
validateTestResult(result, testSpec) {
const validation = {
isValid: true,
error: null,
issues: []
};
// Check if result has success property and is true
if (!result || typeof result.success !== 'boolean') {
validation.isValid = false;
validation.error = 'Result does not have success property';
return validation;
}
if (!result.success) {
validation.isValid = false;
validation.error = result.error || 'API call returned success: false';
return validation;
}
// Check expected fields in response data
if (testSpec.expectedFields && testSpec.expectedFields.length > 0) {
const data = result.data;
if (!data) {
validation.issues.push('No data property in successful response');
} else {
// Check if it's an array response
if (testSpec.expectedFields.includes('length')) {
if (!Array.isArray(data)) {
validation.issues.push('Expected array response but got object');
}
} else {
// Check for specific fields
testSpec.expectedFields.forEach(field => {
if (!(field in data)) {
validation.issues.push(`Missing expected field: ${field}`);
}
});
}
}
}
// If there are issues but the API call succeeded, it's still a partial success
if (validation.issues.length > 0) {
validation.error = `API works but has structural issues: ${validation.issues.join(', ')}`;
}
return validation;
}
// Fix identified API issues
async fixAPIIssues(allResults) {
console.log('\nπ§ ANALYZING AND FIXING API ISSUES');
console.log('β'.repeat(50));
const allIssues = [];
allResults.forEach(suite => {
allIssues.push(...suite.issues);
});
if (allIssues.length === 0) {
console.log('β
No API issues found - all endpoints working correctly!');
return true;
}
console.log(`π Found ${allIssues.length} issues to fix:`);
allIssues.forEach((issue, index) => {
console.log(` ${index + 1}. ${issue}`);
});
// Categorize and fix issues
const fixes = [];
// Analyze common patterns
const missingFieldIssues = allIssues.filter(issue => issue.includes('Missing expected field'));
const structuralIssues = allIssues.filter(issue => issue.includes('structural issues'));
const errorIssues = allIssues.filter(issue => issue.includes('error') || issue.includes('failed'));
if (missingFieldIssues.length > 0) {
fixes.push({
type: 'missing_fields',
description: 'Some API responses are missing expected fields',
recommendation: 'Check controller functions to ensure all required fields are included in responses'
});
}
if (structuralIssues.length > 0) {
fixes.push({
type: 'structural',
description: 'API responses have structural inconsistencies',
recommendation: 'Standardize response format across all endpoints'
});
}
if (errorIssues.length > 0) {
fixes.push({
type: 'errors',
description: 'Some API calls are failing',
recommendation: 'Check authentication, route configuration, and controller implementations'
});
}
console.log('\nπ‘ RECOMMENDED FIXES:');
fixes.forEach((fix, index) => {
console.log(` ${index + 1}. ${fix.type.toUpperCase()}: ${fix.description}`);
console.log(` β ${fix.recommendation}`);
});
return false; // Issues found, need manual fixes
}
// Clean up created test resources
async cleanup() {
console.log('\nπ§Ή Cleaning up test resources...');
// Delete created journals
for (const journalId of this.createdResources.journals) {
try {
await this.backendTools.deleteJournal(journalId);
console.log(` β
Deleted journal: ${journalId}`);
} catch (error) {
console.log(` β οΈ Failed to delete journal ${journalId}: ${error.message}`);
}
}
// Delete created chats
for (const chatId of this.createdResources.chats) {
try {
await this.backendTools.deleteChat(chatId);
console.log(` β
Deleted chat: ${chatId}`);
} catch (error) {
console.log(` β οΈ Failed to delete chat ${chatId}: ${error.message}`);
}
}
// Delete created memories
for (const memoryId of this.createdResources.memories) {
try {
await this.backendTools.deleteMemory(memoryId, true); // Permanent delete
console.log(` β
Deleted memory: ${memoryId}`);
} catch (error) {
console.log(` β οΈ Failed to delete memory ${memoryId}: ${error.message}`);
}
}
}
// Main testing iteration cycle
async runTestingCycle() {
console.log(`\nπ TESTING ITERATION ${this.iterationCount + 1}/${this.maxIterations}`);
console.log('=' .repeat(60));
try {
// Test all API categories
const journalResults = await this.testJournalAPIs();
const chatResults = await this.testChatAPIs();
const memoryResults = await this.testMemoryAPIs();
const allResults = [journalResults, chatResults, memoryResults];
this.testResults.push({
iteration: this.iterationCount + 1,
timestamp: new Date().toISOString(),
results: allResults
});
// Analyze results
const totalTests = allResults.reduce((sum, suite) => sum + suite.totalTests, 0);
const totalPassed = allResults.reduce((sum, suite) => sum + suite.passedTests, 0);
const totalFailed = allResults.reduce((sum, suite) => sum + suite.failedTests, 0);
const successRate = (totalPassed / totalTests) * 100;
console.log('\nπ ITERATION SUMMARY:');
console.log(` π Total Tests: ${totalTests}`);
console.log(` β
Passed: ${totalPassed}`);
console.log(` β Failed: ${totalFailed}`);
console.log(` π Success Rate: ${successRate.toFixed(1)}%`);
// Check if all tests passed
if (totalFailed === 0) {
console.log('\nπ ALL API TESTS PASSED!');
console.log('β
All AI agent tools are working correctly');
return { success: true, allPassed: true };
}
// Try to fix issues
const fixesSuccessful = await this.fixAPIIssues(allResults);
this.iterationCount++;
// Continue iteration if under max and not all fixed
if (this.iterationCount < this.maxIterations && !fixesSuccessful) {
console.log(`\nβ° Waiting 5 seconds before next iteration...`);
await new Promise(resolve => setTimeout(resolve, 5000));
return await this.runTestingCycle();
} else {
console.log('\nβ οΈ Maximum iterations reached or manual fixes needed');
return { success: true, allPassed: false, needsManualFixes: true };
}
} catch (error) {
console.error('π₯ Testing cycle failed:', error.message);
return { success: false, error: error.message };
}
}
// Generate final test report
generateFinalReport(finalResult) {
console.log('\nπ FINAL AI AGENT API TESTING REPORT');
console.log('=' .repeat(60));
const report = {
timestamp: new Date().toISOString(),
totalIterations: this.iterationCount,
finalStatus: finalResult.allPassed ? 'ALL_TESTS_PASSED' : 'ISSUES_REMAINING',
testResults: this.testResults,
summary: {
testedAPIs: {
journalAPIs: 9,
chatAPIs: 4,
memoryAPIs: 9,
total: 22
},
finalOutcome: finalResult.allPassed ? 'SUCCESS' : 'NEEDS_ATTENTION'
}
};
console.log(`π Testing Summary:`);
console.log(` π Iterations: ${report.totalIterations}`);
console.log(` π― Final Status: ${report.finalStatus}`);
console.log(` π Total APIs Tested: ${report.summary.testedAPIs.total}`);
console.log(` π Journal APIs: ${report.summary.testedAPIs.journalAPIs}`);
console.log(` π¬ Chat APIs: ${report.summary.testedAPIs.chatAPIs}`);
console.log(` π§ Memory APIs: ${report.summary.testedAPIs.memoryAPIs}`);
if (finalResult.allPassed) {
console.log('\nπ SUCCESS: All AI agent API tools are working correctly!');
console.log('β
Your backend endpoints are ready for AI agent usage');
} else {
console.log('\nβ οΈ Some issues remain that require manual attention');
console.log('π§ Check the detailed error messages above for specific fixes needed');
}
return report;
}
}
// Main execution function
async function main() {
console.log('π― Starting comprehensive AI agent API testing...');
const tester = new AgentAPITester();
try {
// Initialize tester
const initialized = await tester.initialize();
if (!initialized) {
console.error('β Failed to initialize tester');
return { success: false };
}
// Run testing cycle
const result = await tester.runTestingCycle();
// Generate final report
const report = tester.generateFinalReport(result);
// Cleanup
await tester.cleanup();
console.log('\nβ
AI agent API testing completed!');
return {
success: true,
allPassed: result.allPassed,
report
};
} catch (error) {
console.error('π₯ Testing failed:', error.message);
await tester.cleanup();
return { success: false, error: error.message };
}
}
// Execute testing
main()
.then(result => {
console.log('\nπ AI AGENT API TESTING COMPLETE');
if (result.success) {
if (result.allPassed) {
console.log('π₯ ALL TESTS PASSED - API tools ready for AI agents!');
} else {
console.log('π§ SOME ISSUES REMAIN - Manual fixes needed');
}
} else {
console.log('β TESTING FAILED');
}
process.exit(result.success ? 0 : 1);
})
.catch(error => {
console.error('π₯ Fatal testing error:', error);
process.exit(1);
});