Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

evaluator.test.ts 29 KB

You have to be logged in to leave a comment. Sign In
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
  1. import * as fs from 'fs';
  2. import * as path from 'path';
  3. import glob from 'glob';
  4. import {
  5. evaluate,
  6. renderPrompt,
  7. resolveVariables,
  8. generateVarCombinations,
  9. } from '../src/evaluator';
  10. import type { ApiProvider, TestSuite, Prompt } from '../src/types';
  11. jest.mock('node-fetch', () => jest.fn());
  12. jest.mock('proxy-agent', () => ({
  13. ProxyAgent: jest.fn().mockImplementation(() => ({})),
  14. }));
  15. jest.mock('glob', () => ({
  16. globSync: jest.fn(),
  17. }));
  18. jest.mock('fs', () => ({
  19. readFileSync: jest.fn(),
  20. writeFileSync: jest.fn(),
  21. statSync: jest.fn(),
  22. readdirSync: jest.fn(),
  23. existsSync: jest.fn(),
  24. mkdirSync: jest.fn(),
  25. promises: {
  26. readFile: jest.fn(),
  27. },
  28. }));
  29. jest.mock('../src/esm');
  30. jest.mock('../src/database');
  31. beforeEach(() => {
  32. jest.clearAllMocks();
  33. });
  34. const mockApiProvider: ApiProvider = {
  35. id: jest.fn().mockReturnValue('test-provider'),
  36. callApi: jest.fn().mockResolvedValue({
  37. output: 'Test output',
  38. tokenUsage: { total: 10, prompt: 5, completion: 5, cached: 0 },
  39. }),
  40. };
  41. const mockGradingApiProviderPasses: ApiProvider = {
  42. id: jest.fn().mockReturnValue('test-grading-provider'),
  43. callApi: jest.fn().mockResolvedValue({
  44. output: JSON.stringify({ pass: true, reason: 'Test grading output' }),
  45. tokenUsage: { total: 10, prompt: 5, completion: 5, cached: 0 },
  46. }),
  47. };
  48. const mockGradingApiProviderFails: ApiProvider = {
  49. id: jest.fn().mockReturnValue('test-grading-provider'),
  50. callApi: jest.fn().mockResolvedValue({
  51. output: JSON.stringify({ pass: false, reason: 'Grading failed reason' }),
  52. tokenUsage: { total: 10, prompt: 5, completion: 5, cached: 0 },
  53. }),
  54. };
  55. function toPrompt(text: string): Prompt {
  56. return { raw: text, label: text };
  57. }
  58. describe('evaluator', () => {
  59. afterEach(() => {
  60. jest.clearAllMocks();
  61. });
  62. test('evaluate with vars', async () => {
  63. const testSuite: TestSuite = {
  64. providers: [mockApiProvider],
  65. prompts: [toPrompt('Test prompt {{ var1 }} {{ var2 }}')],
  66. tests: [
  67. {
  68. vars: { var1: 'value1', var2: 'value2' },
  69. },
  70. ],
  71. };
  72. const summary = await evaluate(testSuite, {});
  73. expect(mockApiProvider.callApi).toHaveBeenCalledTimes(1);
  74. expect(summary.stats.successes).toBe(1);
  75. expect(summary.stats.failures).toBe(0);
  76. expect(summary.stats.tokenUsage).toEqual({ total: 10, prompt: 5, completion: 5, cached: 0 });
  77. expect(summary.results[0].prompt.raw).toBe('Test prompt value1 value2');
  78. expect(summary.results[0].prompt.label).toBe('Test prompt {{ var1 }} {{ var2 }}');
  79. expect(summary.results[0].response?.output).toBe('Test output');
  80. });
  81. test('evaluate with vars - no escaping', async () => {
  82. const testSuite: TestSuite = {
  83. providers: [mockApiProvider],
  84. prompts: [toPrompt('Test prompt {{ var1 }} {{ var2 }}')],
  85. tests: [
  86. {
  87. vars: { var1: '1 < 2', var2: 'he said "hello world"...' },
  88. },
  89. ],
  90. };
  91. const summary = await evaluate(testSuite, {});
  92. expect(mockApiProvider.callApi).toHaveBeenCalledTimes(1);
  93. expect(summary.stats.successes).toBe(1);
  94. expect(summary.stats.failures).toBe(0);
  95. expect(summary.stats.tokenUsage).toEqual({ total: 10, prompt: 5, completion: 5, cached: 0 });
  96. expect(summary.results[0].prompt.raw).toBe('Test prompt 1 < 2 he said "hello world"...');
  97. expect(summary.results[0].prompt.label).toBe('Test prompt {{ var1 }} {{ var2 }}');
  98. expect(summary.results[0].response?.output).toBe('Test output');
  99. });
  100. test('evaluate with vars as object', async () => {
  101. const testSuite: TestSuite = {
  102. providers: [mockApiProvider],
  103. prompts: [toPrompt('Test prompt {{ var1.prop1 }} {{ var2 }}')],
  104. tests: [
  105. {
  106. vars: { var1: { prop1: 'value1' }, var2: 'value2' },
  107. },
  108. ],
  109. };
  110. const summary = await evaluate(testSuite, {});
  111. expect(mockApiProvider.callApi).toHaveBeenCalledTimes(1);
  112. expect(summary.stats.successes).toBe(1);
  113. expect(summary.stats.failures).toBe(0);
  114. expect(summary.stats.tokenUsage).toEqual({ total: 10, prompt: 5, completion: 5, cached: 0 });
  115. expect(summary.results[0].prompt.raw).toBe('Test prompt value1 value2');
  116. expect(summary.results[0].prompt.label).toBe('Test prompt {{ var1.prop1 }} {{ var2 }}');
  117. expect(summary.results[0].response?.output).toBe('Test output');
  118. });
  119. test('evaluate with named prompt', async () => {
  120. const testSuite: TestSuite = {
  121. providers: [mockApiProvider],
  122. prompts: [{ raw: 'Test prompt {{ var1 }} {{ var2 }}', label: 'test display name' }],
  123. tests: [
  124. {
  125. vars: { var1: 'value1', var2: 'value2' },
  126. },
  127. ],
  128. };
  129. const summary = await evaluate(testSuite, {});
  130. expect(mockApiProvider.callApi).toHaveBeenCalledTimes(1);
  131. expect(summary.stats.successes).toBe(1);
  132. expect(summary.stats.failures).toBe(0);
  133. expect(summary.stats.tokenUsage).toEqual({ total: 10, prompt: 5, completion: 5, cached: 0 });
  134. expect(summary.results[0].prompt.raw).toBe('Test prompt value1 value2');
  135. expect(summary.results[0].prompt.label).toBe('test display name');
  136. expect(summary.results[0].response?.output).toBe('Test output');
  137. });
  138. test('evaluate with multiple vars', async () => {
  139. const testSuite: TestSuite = {
  140. providers: [mockApiProvider],
  141. prompts: [toPrompt('Test prompt {{ var1 }} {{ var2 }}')],
  142. tests: [
  143. {
  144. vars: { var1: ['value1', 'value3'], var2: ['value2', 'value4'] },
  145. },
  146. ],
  147. };
  148. const summary = await evaluate(testSuite, {});
  149. expect(mockApiProvider.callApi).toHaveBeenCalledTimes(4);
  150. expect(summary.stats.successes).toBe(4);
  151. expect(summary.stats.failures).toBe(0);
  152. expect(summary.stats.tokenUsage).toEqual({ total: 40, prompt: 20, completion: 20, cached: 0 });
  153. expect(summary.results[0].prompt.raw).toBe('Test prompt value1 value2');
  154. expect(summary.results[0].prompt.label).toBe('Test prompt {{ var1 }} {{ var2 }}');
  155. expect(summary.results[0].response?.output).toBe('Test output');
  156. });
  157. test('evaluate with multiple providers', async () => {
  158. const testSuite: TestSuite = {
  159. providers: [mockApiProvider, mockApiProvider],
  160. prompts: [toPrompt('Test prompt {{ var1 }} {{ var2 }}')],
  161. tests: [
  162. {
  163. vars: { var1: 'value1', var2: 'value2' },
  164. },
  165. ],
  166. };
  167. const summary = await evaluate(testSuite, {});
  168. expect(mockApiProvider.callApi).toHaveBeenCalledTimes(2);
  169. expect(summary.stats.successes).toBe(2);
  170. expect(summary.stats.failures).toBe(0);
  171. expect(summary.stats.tokenUsage).toEqual({ total: 20, prompt: 10, completion: 10, cached: 0 });
  172. expect(summary.results[0].prompt.raw).toBe('Test prompt value1 value2');
  173. expect(summary.results[0].prompt.label).toBe('Test prompt {{ var1 }} {{ var2 }}');
  174. expect(summary.results[0].response?.output).toBe('Test output');
  175. });
  176. test('evaluate without tests', async () => {
  177. const testSuite: TestSuite = {
  178. providers: [mockApiProvider],
  179. prompts: [toPrompt('Test prompt')],
  180. };
  181. const summary = await evaluate(testSuite, {});
  182. expect(mockApiProvider.callApi).toHaveBeenCalledTimes(1);
  183. expect(summary.stats.successes).toBe(1);
  184. expect(summary.stats.failures).toBe(0);
  185. expect(summary.stats.tokenUsage).toEqual({ total: 10, prompt: 5, completion: 5, cached: 0 });
  186. expect(summary.results[0].prompt.raw).toBe('Test prompt');
  187. expect(summary.results[0].prompt.label).toBe('Test prompt');
  188. expect(summary.results[0].response?.output).toBe('Test output');
  189. });
  190. test('evaluate without tests with multiple providers', async () => {
  191. const testSuite: TestSuite = {
  192. providers: [mockApiProvider, mockApiProvider, mockApiProvider],
  193. prompts: [toPrompt('Test prompt')],
  194. };
  195. const summary = await evaluate(testSuite, {});
  196. expect(mockApiProvider.callApi).toHaveBeenCalledTimes(3);
  197. expect(summary.stats.successes).toBe(3);
  198. expect(summary.stats.failures).toBe(0);
  199. expect(summary.stats.tokenUsage).toEqual({ total: 30, prompt: 15, completion: 15, cached: 0 });
  200. expect(summary.results[0].prompt.raw).toBe('Test prompt');
  201. expect(summary.results[0].prompt.label).toBe('Test prompt');
  202. expect(summary.results[0].response?.output).toBe('Test output');
  203. });
  204. test('evaluate with expected value matching output', async () => {
  205. const testSuite: TestSuite = {
  206. providers: [mockApiProvider],
  207. prompts: [toPrompt('Test prompt')],
  208. tests: [
  209. {
  210. assert: [
  211. {
  212. type: 'equals',
  213. value: 'Test output',
  214. },
  215. ],
  216. },
  217. ],
  218. };
  219. const summary = await evaluate(testSuite, {});
  220. expect(mockApiProvider.callApi).toHaveBeenCalledTimes(1);
  221. expect(summary.stats.successes).toBe(1);
  222. expect(summary.stats.failures).toBe(0);
  223. expect(summary.results[0].success).toBe(true);
  224. expect(summary.results[0].response?.output).toBe('Test output');
  225. });
  226. test('evaluate with expected value not matching output', async () => {
  227. const testSuite: TestSuite = {
  228. providers: [mockApiProvider],
  229. prompts: [toPrompt('Test prompt')],
  230. tests: [
  231. {
  232. assert: [
  233. {
  234. type: 'equals',
  235. value: 'Different output',
  236. },
  237. ],
  238. },
  239. ],
  240. };
  241. const summary = await evaluate(testSuite, {});
  242. expect(mockApiProvider.callApi).toHaveBeenCalledTimes(1);
  243. expect(summary.stats.successes).toBe(0);
  244. expect(summary.stats.failures).toBe(1);
  245. expect(summary.results[0].success).toBe(false);
  246. expect(summary.results[0].response?.output).toBe('Test output');
  247. });
  248. test('evaluate with fn: expected value', async () => {
  249. const testSuite: TestSuite = {
  250. providers: [mockApiProvider],
  251. prompts: [toPrompt('Test prompt')],
  252. tests: [
  253. {
  254. assert: [
  255. {
  256. type: 'javascript',
  257. value: 'output === "Test output";',
  258. },
  259. ],
  260. },
  261. ],
  262. };
  263. const summary = await evaluate(testSuite, {});
  264. expect(mockApiProvider.callApi).toHaveBeenCalledTimes(1);
  265. expect(summary.stats.successes).toBe(1);
  266. expect(summary.stats.failures).toBe(0);
  267. expect(summary.results[0].success).toBe(true);
  268. expect(summary.results[0].response?.output).toBe('Test output');
  269. });
  270. test('evaluate with fn: expected value not matching output', async () => {
  271. const testSuite: TestSuite = {
  272. providers: [mockApiProvider],
  273. prompts: [toPrompt('Test prompt')],
  274. tests: [
  275. {
  276. assert: [
  277. {
  278. type: 'javascript',
  279. value: 'output === "Different output";',
  280. },
  281. ],
  282. },
  283. ],
  284. };
  285. const summary = await evaluate(testSuite, {});
  286. expect(mockApiProvider.callApi).toHaveBeenCalledTimes(1);
  287. expect(summary.stats.successes).toBe(0);
  288. expect(summary.stats.failures).toBe(1);
  289. expect(summary.results[0].success).toBe(false);
  290. expect(summary.results[0].response?.output).toBe('Test output');
  291. });
  292. test('evaluate with grading expected value', async () => {
  293. const testSuite: TestSuite = {
  294. providers: [mockApiProvider],
  295. prompts: [toPrompt('Test prompt')],
  296. tests: [
  297. {
  298. assert: [
  299. {
  300. type: 'llm-rubric',
  301. value: 'output is a test output',
  302. },
  303. ],
  304. },
  305. ],
  306. defaultTest: {
  307. options: {
  308. provider: mockGradingApiProviderPasses,
  309. },
  310. },
  311. };
  312. const summary = await evaluate(testSuite, {});
  313. expect(mockApiProvider.callApi).toHaveBeenCalledTimes(1);
  314. expect(summary.stats.successes).toBe(1);
  315. expect(summary.stats.failures).toBe(0);
  316. expect(summary.results[0].success).toBe(true);
  317. expect(summary.results[0].response?.output).toBe('Test output');
  318. });
  319. test('evaluate with grading expected value does not pass', async () => {
  320. const testSuite: TestSuite = {
  321. providers: [mockApiProvider],
  322. prompts: [toPrompt('Test prompt')],
  323. tests: [
  324. {
  325. assert: [
  326. {
  327. type: 'llm-rubric',
  328. value: 'output is a test output',
  329. },
  330. ],
  331. },
  332. ],
  333. defaultTest: {
  334. options: {
  335. provider: mockGradingApiProviderFails,
  336. },
  337. },
  338. };
  339. const summary = await evaluate(testSuite, {});
  340. expect(mockApiProvider.callApi).toHaveBeenCalledTimes(1);
  341. expect(summary.stats.successes).toBe(0);
  342. expect(summary.stats.failures).toBe(1);
  343. expect(summary.results[0].success).toBe(false);
  344. expect(summary.results[0].response?.output).toBe('Test output');
  345. });
  346. test('evaluate with transform option - default test', async () => {
  347. const testSuite: TestSuite = {
  348. providers: [mockApiProvider],
  349. prompts: [toPrompt('Test prompt')],
  350. defaultTest: {
  351. options: {
  352. transform: 'output + " postprocessed"',
  353. },
  354. },
  355. };
  356. const summary = await evaluate(testSuite, {});
  357. expect(mockApiProvider.callApi).toHaveBeenCalledTimes(1);
  358. expect(summary.stats.successes).toBe(1);
  359. expect(summary.stats.failures).toBe(0);
  360. expect(summary.results[0].response?.output).toBe('Test output postprocessed');
  361. });
  362. test('evaluate with transform option - single test', async () => {
  363. const testSuite: TestSuite = {
  364. providers: [mockApiProvider],
  365. prompts: [toPrompt('Test prompt')],
  366. tests: [
  367. {
  368. assert: [
  369. {
  370. type: 'equals',
  371. value: 'Test output postprocessed',
  372. },
  373. ],
  374. options: {
  375. transform: 'output + " postprocessed"',
  376. },
  377. },
  378. ],
  379. };
  380. const summary = await evaluate(testSuite, {});
  381. expect(mockApiProvider.callApi).toHaveBeenCalledTimes(1);
  382. expect(summary.stats.successes).toBe(1);
  383. expect(summary.stats.failures).toBe(0);
  384. expect(summary.results[0].response?.output).toBe('Test output postprocessed');
  385. });
  386. test('evaluate with transform option - json provider', async () => {
  387. const mockApiJsonProvider: ApiProvider = {
  388. id: jest.fn().mockReturnValue('test-provider-json'),
  389. callApi: jest.fn().mockResolvedValue({
  390. output: '{"output": "testing", "value": 123}',
  391. tokenUsage: { total: 10, prompt: 5, completion: 5, cached: 0 },
  392. }),
  393. };
  394. const testSuite: TestSuite = {
  395. providers: [mockApiJsonProvider],
  396. prompts: [toPrompt('Test prompt')],
  397. tests: [
  398. {
  399. assert: [
  400. {
  401. type: 'equals',
  402. value: '123',
  403. },
  404. ],
  405. options: {
  406. transform: `JSON.parse(output).value`,
  407. },
  408. },
  409. ],
  410. };
  411. const summary = await evaluate(testSuite, {});
  412. expect(mockApiJsonProvider.callApi).toHaveBeenCalledTimes(1);
  413. expect(summary.stats.successes).toBe(1);
  414. expect(summary.stats.failures).toBe(0);
  415. expect(summary.results[0].response?.output).toBe(123);
  416. });
  417. test('evaluate with provider transform', async () => {
  418. const mockApiProviderWithTransform: ApiProvider = {
  419. id: jest.fn().mockReturnValue('test-provider-transform'),
  420. callApi: jest.fn().mockResolvedValue({
  421. output: 'Original output',
  422. tokenUsage: { total: 10, prompt: 5, completion: 5, cached: 0 },
  423. }),
  424. transform: '`Transformed: ${output}`',
  425. };
  426. const testSuite: TestSuite = {
  427. providers: [mockApiProviderWithTransform],
  428. prompts: [toPrompt('Test prompt')],
  429. tests: [
  430. {
  431. assert: [
  432. {
  433. type: 'equals',
  434. value: 'Transformed: Original output',
  435. },
  436. ],
  437. options: {}, // No test transform, relying on provider's transform
  438. },
  439. ],
  440. };
  441. const summary = await evaluate(testSuite, {});
  442. expect(mockApiProviderWithTransform.callApi).toHaveBeenCalledTimes(1);
  443. expect(summary.stats.successes).toBe(1);
  444. expect(summary.stats.failures).toBe(0);
  445. expect(summary.results[0].response?.output).toBe('Transformed: Original output');
  446. });
  447. test('evaluate with providerPromptMap', async () => {
  448. const testSuite: TestSuite = {
  449. providers: [mockApiProvider],
  450. prompts: [toPrompt('Test prompt 1'), toPrompt('Test prompt 2')],
  451. providerPromptMap: {
  452. 'test-provider': ['Test prompt 1'],
  453. },
  454. tests: [
  455. {
  456. vars: { var1: 'value1', var2: 'value2' },
  457. },
  458. ],
  459. };
  460. const summary = await evaluate(testSuite, {});
  461. expect(mockApiProvider.callApi).toHaveBeenCalledTimes(1);
  462. expect(summary.stats.successes).toBe(1);
  463. expect(summary.stats.failures).toBe(0);
  464. expect(summary.stats.tokenUsage).toEqual({ total: 10, prompt: 5, completion: 5, cached: 0 });
  465. expect(summary.results[0].prompt.raw).toBe('Test prompt 1');
  466. expect(summary.results[0].prompt.label).toBe('Test prompt 1');
  467. expect(summary.results[0].response?.output).toBe('Test output');
  468. });
  469. test('evaluate with scenarios', async () => {
  470. const mockApiProvider: ApiProvider = {
  471. id: jest.fn().mockReturnValue('test-provider'),
  472. callApi: jest
  473. .fn()
  474. .mockResolvedValueOnce({
  475. output: 'Hola mundo',
  476. tokenUsage: { total: 10, prompt: 5, completion: 5, cached: 0 },
  477. })
  478. .mockResolvedValueOnce({
  479. output: 'Bonjour le monde',
  480. tokenUsage: { total: 10, prompt: 5, completion: 5, cached: 0 },
  481. }),
  482. };
  483. const testSuite: TestSuite = {
  484. providers: [mockApiProvider],
  485. prompts: [toPrompt('Test prompt {{ language }}')],
  486. scenarios: [
  487. {
  488. config: [
  489. {
  490. vars: {
  491. language: 'Spanish',
  492. expectedHelloWorld: 'Hola mundo',
  493. },
  494. },
  495. {
  496. vars: {
  497. language: 'French',
  498. expectedHelloWorld: 'Bonjour le monde',
  499. },
  500. },
  501. ],
  502. tests: [
  503. {
  504. assert: [
  505. {
  506. type: 'equals',
  507. value: '{{expectedHelloWorld}}',
  508. },
  509. ],
  510. },
  511. ],
  512. },
  513. ],
  514. };
  515. const summary = await evaluate(testSuite, {});
  516. expect(mockApiProvider.callApi).toHaveBeenCalledTimes(2);
  517. expect(summary.stats.successes).toBe(2);
  518. expect(summary.stats.failures).toBe(0);
  519. expect(summary.results[0].response?.output).toBe('Hola mundo');
  520. expect(summary.results[1].response?.output).toBe('Bonjour le monde');
  521. });
  522. test('evaluate with scenarios and multiple vars', async () => {
  523. const mockApiProvider: ApiProvider = {
  524. id: jest.fn().mockReturnValue('test-provider'),
  525. callApi: jest
  526. .fn()
  527. .mockResolvedValueOnce({
  528. output: 'Spanish Hola',
  529. tokenUsage: { total: 10, prompt: 5, completion: 5, cached: 0 },
  530. })
  531. .mockResolvedValueOnce({
  532. output: 'Spanish Bonjour',
  533. tokenUsage: { total: 10, prompt: 5, completion: 5, cached: 0 },
  534. })
  535. .mockResolvedValueOnce({
  536. output: 'French Hola',
  537. tokenUsage: { total: 10, prompt: 5, completion: 5, cached: 0 },
  538. })
  539. .mockResolvedValueOnce({
  540. output: 'French Bonjour',
  541. tokenUsage: { total: 10, prompt: 5, completion: 5, cached: 0 },
  542. }),
  543. };
  544. const testSuite: TestSuite = {
  545. providers: [mockApiProvider],
  546. prompts: [toPrompt('Test prompt {{ language }} {{ greeting }}')],
  547. scenarios: [
  548. {
  549. config: [
  550. {
  551. vars: {
  552. language: ['Spanish', 'French'],
  553. greeting: ['Hola', 'Bonjour'],
  554. },
  555. },
  556. ],
  557. tests: [
  558. {
  559. assert: [
  560. {
  561. type: 'equals',
  562. value: '{{language}} {{greeting}}',
  563. },
  564. ],
  565. },
  566. ],
  567. },
  568. ],
  569. };
  570. const summary = await evaluate(testSuite, {});
  571. expect(mockApiProvider.callApi).toHaveBeenCalledTimes(4);
  572. expect(summary.stats.successes).toBe(4);
  573. expect(summary.stats.failures).toBe(0);
  574. expect(summary.results[0].response?.output).toBe('Spanish Hola');
  575. expect(summary.results[1].response?.output).toBe('Spanish Bonjour');
  576. expect(summary.results[2].response?.output).toBe('French Hola');
  577. expect(summary.results[3].response?.output).toBe('French Bonjour');
  578. });
  579. test('evaluate with _conversation variable', async () => {
  580. const mockApiProvider: ApiProvider = {
  581. id: jest.fn().mockReturnValue('test-provider'),
  582. callApi: jest.fn().mockImplementation((prompt) => {
  583. return Promise.resolve({
  584. output: prompt,
  585. tokenUsage: { total: 10, prompt: 5, completion: 5, cached: 0 },
  586. });
  587. }),
  588. };
  589. const testSuite: TestSuite = {
  590. providers: [mockApiProvider],
  591. prompts: [toPrompt('{{ var1 }} {{ _conversation[0].output }}')],
  592. tests: [
  593. {
  594. vars: { var1: 'First run' },
  595. },
  596. {
  597. vars: { var1: 'Second run' },
  598. },
  599. ],
  600. };
  601. const summary = await evaluate(testSuite, {});
  602. expect(mockApiProvider.callApi).toHaveBeenCalledTimes(2);
  603. expect(summary.stats.successes).toBe(2);
  604. expect(summary.stats.failures).toBe(0);
  605. expect(summary.results[0].response?.output).toBe('First run ');
  606. expect(summary.results[1].response?.output).toBe('Second run First run ');
  607. });
  608. });
  609. it('should use the options from the test if they exist', async () => {
  610. const testSuite: TestSuite = {
  611. providers: [mockApiProvider],
  612. prompts: [toPrompt('Test prompt')],
  613. tests: [
  614. {
  615. vars: { var1: 'value1', var2: 'value2' },
  616. options: {
  617. transform: 'output + " postprocessed"',
  618. },
  619. },
  620. ],
  621. };
  622. const summary = await evaluate(testSuite, {});
  623. expect(mockApiProvider.callApi).toHaveBeenCalledTimes(1);
  624. expect(summary.stats.successes).toBe(1);
  625. expect(summary.stats.failures).toBe(0);
  626. expect(summary.results[0].response?.output).toBe('Test output postprocessed');
  627. });
  628. describe('renderPrompt', () => {
  629. it('should render a prompt with a single variable', async () => {
  630. const prompt = toPrompt('Test prompt {{ var1 }}');
  631. const renderedPrompt = await renderPrompt(prompt, { var1: 'value1' }, {});
  632. expect(renderedPrompt).toBe('Test prompt value1');
  633. });
  634. it('should render a JSON prompt', async () => {
  635. const prompt = toPrompt('[{"text": "Test prompt "}, {"text": "{{ var1 }}"}]');
  636. const renderedPrompt = await renderPrompt(prompt, { var1: 'value1' }, {});
  637. expect(renderedPrompt).toBe(
  638. JSON.stringify(JSON.parse('[{"text":"Test prompt "},{"text":"value1"}]'), null, 2),
  639. );
  640. });
  641. it('should render a JSON prompt and escape the var string', async () => {
  642. const prompt = toPrompt('[{"text": "Test prompt "}, {"text": "{{ var1 }}"}]');
  643. const renderedPrompt = await renderPrompt(prompt, { var1: 'He said "hello world!"' }, {});
  644. expect(renderedPrompt).toBe(
  645. JSON.stringify(
  646. JSON.parse('[{"text":"Test prompt "},{"text":"He said \\"hello world!\\""}]'),
  647. null,
  648. 2,
  649. ),
  650. );
  651. });
  652. it('should render a JSON prompt with nested JSON', async () => {
  653. const prompt = toPrompt('[{"text": "Test prompt "}, {"text": "{{ var1 }}"}]');
  654. const renderedPrompt = await renderPrompt(prompt, { var1: '{"nested": "value1"}' }, {});
  655. expect(renderedPrompt).toBe(
  656. JSON.stringify(
  657. JSON.parse('[{"text":"Test prompt "},{"text":"{\\"nested\\": \\"value1\\"}"}]'),
  658. null,
  659. 2,
  660. ),
  661. );
  662. });
  663. it('should load external yaml files in renderPrompt', async () => {
  664. const prompt = toPrompt('Test prompt with {{ var1 }}');
  665. const vars = { var1: 'file://test.txt' };
  666. const evaluateOptions = {};
  667. // Mock fs.readFileSync to simulate loading a YAML file
  668. jest.spyOn(fs, 'readFileSync').mockReturnValueOnce('loaded from file');
  669. const renderedPrompt = await renderPrompt(prompt, vars, evaluateOptions);
  670. expect(fs.readFileSync).toHaveBeenCalledWith(expect.stringContaining('test.txt'), 'utf8');
  671. expect(renderedPrompt).toBe('Test prompt with loaded from file');
  672. });
  673. it('should load external js files in renderPrompt and execute the exported function', async () => {
  674. const prompt = toPrompt('Test prompt with {{ var1 }}');
  675. const vars = { var1: 'file:///path/to/testFunction.js' };
  676. const evaluateOptions = {};
  677. jest.doMock(
  678. path.resolve('/path/to/testFunction.js'),
  679. () => (varName: any, prompt: any, vars: any) => ({ output: `Dynamic value for ${varName}` }),
  680. { virtual: true },
  681. );
  682. const renderedPrompt = await renderPrompt(prompt, vars, evaluateOptions);
  683. expect(renderedPrompt).toBe('Test prompt with Dynamic value for var1');
  684. });
  685. it('should load external json files in renderPrompt and parse the JSON content', async () => {
  686. const prompt = toPrompt('Test prompt with {{ var1 }}');
  687. const vars = { var1: 'file:///path/to/testData.json' };
  688. const evaluateOptions = {};
  689. jest.spyOn(fs, 'readFileSync').mockReturnValueOnce(JSON.stringify({ key: 'valueFromJson' }));
  690. const renderedPrompt = await renderPrompt(prompt, vars, evaluateOptions);
  691. expect(fs.readFileSync).toHaveBeenCalledWith(expect.stringContaining('testData.json'), 'utf8');
  692. expect(renderedPrompt).toBe('Test prompt with {"key":"valueFromJson"}');
  693. });
  694. it('should load external yaml files in renderPrompt and parse the YAML content', async () => {
  695. const prompt = toPrompt('Test prompt with {{ var1 }}');
  696. const vars = { var1: 'file:///path/to/testData.yaml' };
  697. const evaluateOptions = {};
  698. jest.spyOn(fs, 'readFileSync').mockReturnValueOnce('key: valueFromYaml');
  699. const renderedPrompt = await renderPrompt(prompt, vars, evaluateOptions);
  700. expect(fs.readFileSync).toHaveBeenCalledWith(expect.stringContaining('testData.yaml'), 'utf8');
  701. expect(renderedPrompt).toBe('Test prompt with {"key":"valueFromYaml"}');
  702. });
  703. });
  704. describe('resolveVariables', () => {
  705. it('should replace placeholders with corresponding variable values', () => {
  706. const variables = { final: '{{ my_greeting }}, {{name}}!', my_greeting: 'Hello', name: 'John' };
  707. const expected = { final: 'Hello, John!', my_greeting: 'Hello', name: 'John' };
  708. expect(resolveVariables(variables)).toEqual(expected);
  709. });
  710. it('should handle nested variable substitutions', () => {
  711. const variables = { first: '{{second}}', second: '{{third}}', third: 'value' };
  712. const expected = { first: 'value', second: 'value', third: 'value' };
  713. expect(resolveVariables(variables)).toEqual(expected);
  714. });
  715. it('should not modify variables without placeholders', () => {
  716. const variables = { greeting: 'Hello, world!', name: 'John' };
  717. const expected = { greeting: 'Hello, world!', name: 'John' };
  718. expect(resolveVariables(variables)).toEqual(expected);
  719. });
  720. it('should not fail if a variable is not found', () => {
  721. const variables = { greeting: 'Hello, {{name}}!' };
  722. expect(resolveVariables(variables)).toEqual({ greeting: 'Hello, {{name}}!' });
  723. });
  724. it('should not fail for unresolved placeholders', () => {
  725. const variables = { greeting: 'Hello, {{name}}!', name: '{{unknown}}' };
  726. expect(resolveVariables(variables)).toEqual({
  727. greeting: 'Hello, {{unknown}}!',
  728. name: '{{unknown}}',
  729. });
  730. });
  731. });
  732. describe('generateVarCombinations', () => {
  733. it('should generate combinations for simple variables', () => {
  734. const vars = { language: 'English', greeting: 'Hello' };
  735. const expected = [{ language: 'English', greeting: 'Hello' }];
  736. expect(generateVarCombinations(vars)).toEqual(expected);
  737. });
  738. it('should generate combinations for array variables', () => {
  739. const vars = { language: ['English', 'French'], greeting: 'Hello' };
  740. const expected = [
  741. { language: 'English', greeting: 'Hello' },
  742. { language: 'French', greeting: 'Hello' },
  743. ];
  744. expect(generateVarCombinations(vars)).toEqual(expected);
  745. });
  746. it('should handle file paths and expand them into combinations', () => {
  747. const vars = { language: 'English', greeting: 'file:///path/to/greetings/*.txt' };
  748. jest.spyOn(glob, 'globSync').mockReturnValue(['greeting1.txt', 'greeting2.txt']);
  749. const expected = [
  750. { language: 'English', greeting: 'file://greeting1.txt' },
  751. { language: 'English', greeting: 'file://greeting2.txt' },
  752. ];
  753. expect(generateVarCombinations(vars)).toEqual(expected);
  754. });
  755. it('should correctly handle nested array variables', () => {
  756. const vars = {
  757. options: [
  758. ['opt1', 'opt2'],
  759. ['opt3', 'opt4'],
  760. ],
  761. };
  762. const expected = [
  763. {
  764. options: [
  765. ['opt1', 'opt2'],
  766. ['opt3', 'opt4'],
  767. ],
  768. },
  769. ];
  770. expect(generateVarCombinations(vars)).toEqual(expected);
  771. });
  772. it('should return an empty array for empty input', () => {
  773. const vars = {};
  774. const expected = [{}];
  775. expect(generateVarCombinations(vars)).toEqual(expected);
  776. });
  777. });
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...