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

llm-rubric.test.ts 33 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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
  1. import fs from 'fs';
  2. import path from 'path';
  3. import { loadFromJavaScriptFile } from '../../src/assertions/utils';
  4. import cliState from '../../src/cliState';
  5. import { importModule } from '../../src/esm';
  6. import { matchesLlmRubric, renderLlmRubricPrompt } from '../../src/matchers';
  7. import { OpenAiChatCompletionProvider } from '../../src/providers/openai/chat';
  8. import { DefaultGradingProvider } from '../../src/providers/openai/defaults';
  9. import * as remoteGrading from '../../src/remoteGrading';
  10. import type { ApiProvider, Assertion, GradingConfig } from '../../src/types';
  11. import { TestGrader } from '../util/utils';
  12. jest.mock('../../src/esm', () => ({
  13. importModule: jest.fn(),
  14. }));
  15. jest.mock('../../src/cliState');
  16. jest.mock('../../src/remoteGrading', () => ({
  17. doRemoteGrading: jest.fn(),
  18. }));
  19. jest.mock('../../src/redteam/remoteGeneration', () => ({
  20. shouldGenerateRemote: jest.fn().mockReturnValue(false),
  21. }));
  22. jest.mock('fs', () => ({
  23. ...jest.requireActual('fs'),
  24. readFileSync: jest.fn(),
  25. existsSync: jest.fn(),
  26. }));
  27. const Grader = new TestGrader();
  28. describe('matchesLlmRubric', () => {
  29. const mockFilePath = path.join('path', 'to', 'external', 'rubric.txt');
  30. const mockFileContent = 'This is an external rubric prompt';
  31. beforeEach(() => {
  32. jest.clearAllMocks();
  33. jest.resetAllMocks();
  34. jest.mocked(fs.existsSync).mockReturnValue(true);
  35. jest.mocked(fs.readFileSync).mockReturnValue(mockFileContent);
  36. (cliState as any).config = {};
  37. jest.mocked(remoteGrading.doRemoteGrading).mockReset();
  38. jest.mocked(remoteGrading.doRemoteGrading).mockResolvedValue({
  39. pass: true,
  40. score: 1,
  41. reason: 'Remote grading passed',
  42. });
  43. jest.spyOn(DefaultGradingProvider, 'callApi').mockReset();
  44. jest.spyOn(DefaultGradingProvider, 'callApi').mockResolvedValue({
  45. output: JSON.stringify({ pass: true, score: 1, reason: 'Test passed' }),
  46. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  47. });
  48. });
  49. it('should pass when the grading provider returns a passing result', async () => {
  50. const expected = 'Expected output';
  51. const output = 'Sample output';
  52. const options: GradingConfig = {
  53. rubricPrompt: 'Grading prompt',
  54. provider: Grader,
  55. };
  56. jest.spyOn(Grader, 'callApi').mockResolvedValue({
  57. output: JSON.stringify({ pass: true, reason: 'Test grading output' }),
  58. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  59. });
  60. await expect(matchesLlmRubric(expected, output, options)).resolves.toEqual({
  61. pass: true,
  62. reason: 'Test grading output',
  63. score: 1,
  64. tokensUsed: {
  65. total: expect.any(Number),
  66. prompt: expect.any(Number),
  67. completion: expect.any(Number),
  68. cached: expect.any(Number),
  69. completionDetails: expect.any(Object),
  70. },
  71. });
  72. });
  73. it('should handle when provider returns direct object output instead of string', async () => {
  74. const expected = 'Expected output';
  75. const output = 'Sample output';
  76. const options: GradingConfig = {
  77. rubricPrompt: 'Grading prompt',
  78. provider: {
  79. id: () => 'test-provider',
  80. callApi: jest.fn().mockResolvedValue({
  81. output: { pass: true, score: 0.85, reason: 'Direct object output' },
  82. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  83. }),
  84. },
  85. };
  86. await expect(matchesLlmRubric(expected, output, options)).resolves.toEqual({
  87. pass: true,
  88. score: 0.85,
  89. reason: 'Direct object output',
  90. assertion: undefined,
  91. tokensUsed: {
  92. total: 10,
  93. prompt: 5,
  94. completion: 5,
  95. cached: 0,
  96. completionDetails: {
  97. reasoning: 0,
  98. acceptedPrediction: 0,
  99. rejectedPrediction: 0,
  100. },
  101. },
  102. });
  103. });
  104. it('should render rubric when provided as an object', async () => {
  105. const rubric = { prompt: 'Describe the image' };
  106. const output = 'Sample output';
  107. const options: GradingConfig = {
  108. rubricPrompt: 'Grade: {{ rubric }}',
  109. provider: {
  110. id: () => 'test-provider',
  111. callApi: jest.fn().mockResolvedValue({
  112. output: JSON.stringify({ pass: true, score: 1, reason: 'ok' }),
  113. tokenUsage: { total: 1, prompt: 1, completion: 1 },
  114. }),
  115. },
  116. };
  117. await matchesLlmRubric(rubric, output, options);
  118. expect(options.provider.callApi).toHaveBeenCalledWith(
  119. expect.stringContaining(JSON.stringify(rubric)),
  120. );
  121. });
  122. it('should fail when output is neither string nor object', async () => {
  123. const expected = 'Expected output';
  124. const output = 'Sample output';
  125. const options: GradingConfig = {
  126. rubricPrompt: 'Grading prompt',
  127. provider: {
  128. id: () => 'test-provider',
  129. callApi: jest.fn().mockResolvedValue({
  130. output: 42, // Numeric output
  131. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  132. }),
  133. },
  134. };
  135. await expect(matchesLlmRubric(expected, output, options)).resolves.toEqual({
  136. assertion: undefined,
  137. pass: false,
  138. score: 0,
  139. reason: 'llm-rubric produced malformed response - output must be string or object',
  140. tokensUsed: {
  141. total: 10,
  142. prompt: 5,
  143. completion: 5,
  144. cached: 0,
  145. completionDetails: undefined,
  146. },
  147. });
  148. });
  149. it('should handle string output with invalid JSON format', async () => {
  150. const expected = 'Expected output';
  151. const output = 'Sample output';
  152. const options: GradingConfig = {
  153. rubricPrompt: 'Grading prompt',
  154. provider: {
  155. id: () => 'test-provider',
  156. callApi: jest.fn().mockResolvedValue({
  157. output: '{ "pass": true, "reason": "Invalid JSON missing closing brace',
  158. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  159. }),
  160. },
  161. };
  162. await expect(matchesLlmRubric(expected, output, options)).resolves.toEqual({
  163. assertion: undefined,
  164. pass: false,
  165. score: 0,
  166. reason: expect.stringContaining('Could not extract JSON from llm-rubric response'),
  167. tokensUsed: {
  168. total: 10,
  169. prompt: 5,
  170. completion: 5,
  171. cached: 0,
  172. completionDetails: undefined,
  173. },
  174. });
  175. });
  176. it('should fail when string output contains no JSON objects', async () => {
  177. const expected = 'Expected output';
  178. const output = 'Sample output';
  179. const options: GradingConfig = {
  180. rubricPrompt: 'Grading prompt',
  181. provider: {
  182. id: () => 'test-provider',
  183. callApi: jest.fn().mockResolvedValue({
  184. output: 'This is a valid text response but contains no JSON objects',
  185. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  186. }),
  187. },
  188. };
  189. await expect(matchesLlmRubric(expected, output, options)).resolves.toEqual({
  190. assertion: undefined,
  191. pass: false,
  192. score: 0,
  193. reason: 'Could not extract JSON from llm-rubric response',
  194. tokensUsed: {
  195. total: 10,
  196. prompt: 5,
  197. completion: 5,
  198. cached: 0,
  199. completionDetails: undefined,
  200. },
  201. });
  202. });
  203. it('should fail when the grading provider returns a failing result', async () => {
  204. const expected = 'Expected output';
  205. const output = 'Different output';
  206. const options: GradingConfig = {
  207. rubricPrompt: 'Grading prompt',
  208. provider: Grader,
  209. };
  210. jest.spyOn(Grader, 'callApi').mockResolvedValueOnce({
  211. output: JSON.stringify({ pass: false, reason: 'Grading failed' }),
  212. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  213. });
  214. await expect(matchesLlmRubric(expected, output, options)).resolves.toEqual({
  215. pass: false,
  216. reason: 'Grading failed',
  217. score: 0,
  218. tokensUsed: {
  219. total: expect.any(Number),
  220. prompt: expect.any(Number),
  221. completion: expect.any(Number),
  222. cached: expect.any(Number),
  223. completionDetails: expect.any(Object),
  224. },
  225. });
  226. });
  227. it('should throw error when throwOnError is true and provider returns an error', async () => {
  228. const rubric = 'Test rubric';
  229. const llmOutput = 'Test output';
  230. const grading: GradingConfig = {
  231. rubricPrompt: 'Grading prompt',
  232. provider: {
  233. id: () => 'test-provider',
  234. callApi: jest.fn().mockResolvedValue({
  235. error: 'Provider error',
  236. output: null,
  237. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  238. }),
  239. },
  240. };
  241. // With throwOnError: true - should throw
  242. await expect(
  243. matchesLlmRubric(rubric, llmOutput, grading, {}, null, { throwOnError: true }),
  244. ).rejects.toThrow('Provider error');
  245. });
  246. it('should throw error when throwOnError is true and provider returns no result', async () => {
  247. const rubric = 'Test rubric';
  248. const llmOutput = 'Test output';
  249. const grading: GradingConfig = {
  250. rubricPrompt: 'Grading prompt',
  251. provider: {
  252. id: () => 'test-provider',
  253. callApi: jest.fn().mockResolvedValue({
  254. error: null,
  255. output: null,
  256. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  257. }),
  258. },
  259. };
  260. // With throwOnError: true - should throw
  261. await expect(
  262. matchesLlmRubric(rubric, llmOutput, grading, {}, null, { throwOnError: true }),
  263. ).rejects.toThrow('No output');
  264. });
  265. it('should use the overridden llm rubric grading config', async () => {
  266. const expected = 'Expected output';
  267. const output = 'Sample output';
  268. const options: GradingConfig = {
  269. rubricPrompt: 'Grading prompt',
  270. provider: {
  271. id: 'openai:gpt-4o-mini',
  272. config: {
  273. apiKey: 'abc123',
  274. temperature: 3.1415926,
  275. },
  276. },
  277. };
  278. const mockCallApi = jest.spyOn(OpenAiChatCompletionProvider.prototype, 'callApi');
  279. mockCallApi.mockImplementation(function (this: OpenAiChatCompletionProvider) {
  280. expect(this.config.temperature).toBe(3.1415926);
  281. expect(this.getApiKey()).toBe('abc123');
  282. return Promise.resolve({
  283. output: JSON.stringify({ pass: true, reason: 'Grading passed' }),
  284. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  285. });
  286. });
  287. await expect(matchesLlmRubric(expected, output, options)).resolves.toEqual({
  288. reason: 'Grading passed',
  289. pass: true,
  290. score: 1,
  291. tokensUsed: {
  292. total: expect.any(Number),
  293. prompt: expect.any(Number),
  294. completion: expect.any(Number),
  295. cached: expect.any(Number),
  296. completionDetails: expect.any(Object),
  297. },
  298. });
  299. expect(mockCallApi).toHaveBeenCalledWith('Grading prompt');
  300. mockCallApi.mockRestore();
  301. });
  302. it('should use provided score threshold if llm does not return pass', async () => {
  303. const rubricPrompt = 'Rubric prompt';
  304. const llmOutput = 'Sample output';
  305. const assertion: Assertion = {
  306. type: 'llm-rubric',
  307. value: rubricPrompt,
  308. threshold: 0.5,
  309. };
  310. const lowScoreResponse = { score: 0.25, reason: 'Low score' };
  311. const lowScoreProvider: ApiProvider = {
  312. id: () => 'test-provider',
  313. callApi: jest.fn().mockResolvedValue({
  314. output: JSON.stringify(lowScoreResponse),
  315. }),
  316. };
  317. await expect(
  318. matchesLlmRubric(
  319. rubricPrompt,
  320. llmOutput,
  321. { rubricPrompt, provider: lowScoreProvider },
  322. {},
  323. assertion,
  324. ),
  325. ).resolves.toEqual(expect.objectContaining({ assertion, pass: false, ...lowScoreResponse }));
  326. const highScoreResponse = { score: 0.75, reason: 'High score' };
  327. const highScoreProvider: ApiProvider = {
  328. id: () => 'test-provider',
  329. callApi: jest.fn().mockResolvedValue({
  330. output: JSON.stringify(highScoreResponse),
  331. }),
  332. };
  333. await expect(
  334. matchesLlmRubric(
  335. rubricPrompt,
  336. llmOutput,
  337. { rubricPrompt, provider: highScoreProvider },
  338. {},
  339. assertion,
  340. ),
  341. ).resolves.toEqual(expect.objectContaining({ assertion, pass: true, ...highScoreResponse }));
  342. });
  343. it('should ignore the score threshold if llm returns pass', async () => {
  344. const rubricPrompt = 'Rubric prompt';
  345. const output = 'Sample output';
  346. const assertion: Assertion = {
  347. type: 'llm-rubric',
  348. value: rubricPrompt,
  349. threshold: 0.1,
  350. };
  351. const lowScoreResult = { score: 0.25, reason: 'Low score but pass', pass: true };
  352. const lowScoreOptions: GradingConfig = {
  353. rubricPrompt,
  354. provider: {
  355. id: () => 'test-provider',
  356. callApi: jest.fn().mockResolvedValue({
  357. output: JSON.stringify(lowScoreResult),
  358. }),
  359. },
  360. };
  361. await expect(
  362. matchesLlmRubric(rubricPrompt, output, lowScoreOptions, {}, assertion),
  363. ).resolves.toEqual(expect.objectContaining({ assertion, ...lowScoreResult }));
  364. });
  365. it('should respect both threshold and explicit pass/fail when both are present', async () => {
  366. const rubricPrompt = 'Rubric prompt';
  367. const output = 'Sample output';
  368. const assertion: Assertion = {
  369. type: 'llm-rubric',
  370. value: rubricPrompt,
  371. threshold: 0.8,
  372. };
  373. // Case 1: Pass is true but score is below threshold
  374. const failingResult = { score: 0.7, reason: 'Score below threshold', pass: true };
  375. const failingOptions: GradingConfig = {
  376. rubricPrompt,
  377. provider: {
  378. id: () => 'test-provider',
  379. callApi: jest.fn().mockResolvedValue({
  380. output: JSON.stringify(failingResult),
  381. }),
  382. },
  383. };
  384. await expect(
  385. matchesLlmRubric(rubricPrompt, output, failingOptions, {}, assertion),
  386. ).resolves.toEqual(
  387. expect.objectContaining({
  388. assertion,
  389. score: 0.7,
  390. pass: false,
  391. reason: 'Score below threshold',
  392. }),
  393. );
  394. // Case 2: Pass is false but score is above threshold
  395. const passingResult = {
  396. score: 0.9,
  397. reason: 'Score above threshold but explicit fail',
  398. pass: false,
  399. };
  400. const passingOptions: GradingConfig = {
  401. rubricPrompt,
  402. provider: {
  403. id: () => 'test-provider',
  404. callApi: jest.fn().mockResolvedValue({
  405. output: JSON.stringify(passingResult),
  406. }),
  407. },
  408. };
  409. await expect(
  410. matchesLlmRubric(rubricPrompt, output, passingOptions, {}, assertion),
  411. ).resolves.toEqual(
  412. expect.objectContaining({
  413. assertion,
  414. score: 0.9,
  415. pass: false,
  416. reason: 'Score above threshold but explicit fail',
  417. }),
  418. );
  419. });
  420. it('should handle edge cases around threshold value', async () => {
  421. const rubricPrompt = 'Rubric prompt';
  422. const output = 'Sample output';
  423. const assertion: Assertion = {
  424. type: 'llm-rubric',
  425. value: rubricPrompt,
  426. threshold: 0.8,
  427. };
  428. // Exactly at threshold should pass
  429. const exactThresholdResult = { score: 0.8, reason: 'Exactly at threshold' };
  430. const exactOptions: GradingConfig = {
  431. rubricPrompt,
  432. provider: {
  433. id: () => 'test-provider',
  434. callApi: jest.fn().mockResolvedValue({
  435. output: JSON.stringify(exactThresholdResult),
  436. }),
  437. },
  438. };
  439. await expect(
  440. matchesLlmRubric(rubricPrompt, output, exactOptions, {}, assertion),
  441. ).resolves.toEqual(
  442. expect.objectContaining({
  443. assertion,
  444. score: 0.8,
  445. pass: true,
  446. reason: 'Exactly at threshold',
  447. }),
  448. );
  449. // Just below threshold should fail
  450. const justBelowResult = { score: 0.799, reason: 'Just below threshold' };
  451. const belowOptions: GradingConfig = {
  452. rubricPrompt,
  453. provider: {
  454. id: () => 'test-provider',
  455. callApi: jest.fn().mockResolvedValue({
  456. output: JSON.stringify(justBelowResult),
  457. }),
  458. },
  459. };
  460. await expect(
  461. matchesLlmRubric(rubricPrompt, output, belowOptions, {}, assertion),
  462. ).resolves.toEqual(
  463. expect.objectContaining({
  464. assertion,
  465. score: 0.799,
  466. pass: false,
  467. reason: 'Just below threshold',
  468. }),
  469. );
  470. });
  471. it('should handle missing or invalid scores when threshold is present', async () => {
  472. const rubricPrompt = 'Rubric prompt';
  473. const output = 'Sample output';
  474. const assertion: Assertion = {
  475. type: 'llm-rubric',
  476. value: rubricPrompt,
  477. threshold: 0.8,
  478. };
  479. // Missing score should default to pass value
  480. const missingScoreResult = { pass: true, reason: 'No score provided' };
  481. const missingScoreOptions: GradingConfig = {
  482. rubricPrompt,
  483. provider: {
  484. id: () => 'test-provider',
  485. callApi: jest.fn().mockResolvedValue({
  486. output: JSON.stringify(missingScoreResult),
  487. }),
  488. },
  489. };
  490. await expect(
  491. matchesLlmRubric(rubricPrompt, output, missingScoreOptions, {}, assertion),
  492. ).resolves.toEqual(
  493. expect.objectContaining({
  494. assertion,
  495. score: 1.0,
  496. pass: true,
  497. reason: 'No score provided',
  498. }),
  499. );
  500. // Invalid score type should be handled gracefully
  501. const invalidScoreResult = { score: 'high', reason: 'Invalid score type', pass: true };
  502. const invalidScoreOptions: GradingConfig = {
  503. rubricPrompt,
  504. provider: {
  505. id: () => 'test-provider',
  506. callApi: jest.fn().mockResolvedValue({
  507. output: JSON.stringify(invalidScoreResult),
  508. }),
  509. },
  510. };
  511. await expect(
  512. matchesLlmRubric(rubricPrompt, output, invalidScoreOptions, {}, assertion),
  513. ).resolves.toEqual(
  514. expect.objectContaining({
  515. assertion,
  516. score: 1.0,
  517. pass: true,
  518. reason: 'Invalid score type',
  519. }),
  520. );
  521. });
  522. it('should handle string scores', async () => {
  523. const rubricPrompt = 'Rubric prompt';
  524. const output = 'Sample output';
  525. const assertion: Assertion = {
  526. type: 'llm-rubric',
  527. value: rubricPrompt,
  528. threshold: 0.8,
  529. };
  530. const stringScoreResult = { score: '0.9', reason: 'String score' };
  531. const stringScoreOptions: GradingConfig = {
  532. rubricPrompt,
  533. provider: {
  534. id: () => 'test-provider',
  535. callApi: jest.fn().mockResolvedValue({
  536. output: JSON.stringify(stringScoreResult),
  537. }),
  538. },
  539. };
  540. await expect(
  541. matchesLlmRubric(rubricPrompt, output, stringScoreOptions, {}, assertion),
  542. ).resolves.toEqual(
  543. expect.objectContaining({
  544. assertion,
  545. score: 0.9,
  546. pass: true,
  547. reason: 'String score',
  548. }),
  549. );
  550. });
  551. it('should handle string pass values', async () => {
  552. const rubricPrompt = 'Rubric prompt';
  553. const output = 'Sample output';
  554. const assertion: Assertion = {
  555. type: 'llm-rubric',
  556. value: rubricPrompt,
  557. threshold: 0.8,
  558. };
  559. const stringPassResult = { reason: 'String pass', pass: 'true' };
  560. const stringPassOptions: GradingConfig = {
  561. rubricPrompt,
  562. provider: {
  563. id: () => 'test-provider',
  564. callApi: jest.fn().mockResolvedValue({
  565. output: JSON.stringify(stringPassResult),
  566. }),
  567. },
  568. };
  569. await expect(
  570. matchesLlmRubric(rubricPrompt, output, stringPassOptions, {}, assertion),
  571. ).resolves.toEqual(
  572. expect.objectContaining({
  573. assertion,
  574. pass: true,
  575. reason: 'String pass',
  576. }),
  577. );
  578. const stringFailResult = { reason: 'String fail', pass: 'false' };
  579. const stringFailOptions: GradingConfig = {
  580. rubricPrompt,
  581. provider: {
  582. id: () => 'test-provider',
  583. callApi: jest.fn().mockResolvedValue({
  584. output: JSON.stringify(stringFailResult),
  585. }),
  586. },
  587. };
  588. await expect(
  589. matchesLlmRubric(rubricPrompt, output, stringFailOptions, {}, assertion),
  590. ).resolves.toEqual(
  591. expect.objectContaining({
  592. assertion,
  593. pass: false,
  594. reason: 'String fail',
  595. }),
  596. );
  597. });
  598. it('should load rubric prompt from external file when specified', async () => {
  599. const rubric = 'Test rubric';
  600. const llmOutput = 'Test output';
  601. const grading = {
  602. rubricPrompt: `file://${mockFilePath}`,
  603. provider: {
  604. id: () => 'test-provider',
  605. callApi: jest.fn().mockResolvedValue({
  606. output: JSON.stringify({ pass: true, score: 1, reason: 'Test passed' }),
  607. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  608. }),
  609. },
  610. };
  611. const result = await matchesLlmRubric(rubric, llmOutput, grading);
  612. expect(fs.existsSync).toHaveBeenCalledWith(
  613. expect.stringContaining(path.join('path', 'to', 'external', 'rubric.txt')),
  614. );
  615. expect(fs.readFileSync).toHaveBeenCalledWith(
  616. expect.stringContaining(path.join('path', 'to', 'external', 'rubric.txt')),
  617. 'utf8',
  618. );
  619. expect(grading.provider.callApi).toHaveBeenCalledWith(expect.stringContaining(mockFileContent));
  620. expect(result).toEqual({
  621. pass: true,
  622. score: 1,
  623. reason: 'Test passed',
  624. tokensUsed: {
  625. total: 10,
  626. prompt: 5,
  627. completion: 5,
  628. cached: 0,
  629. completionDetails: { reasoning: 0, acceptedPrediction: 0, rejectedPrediction: 0 },
  630. },
  631. });
  632. });
  633. it('should load rubric prompt from js file when specified', async () => {
  634. const filePath = path.join('path', 'to', 'external', 'file.js');
  635. const mockImportModule = jest.mocked(importModule);
  636. const mockFunction = jest.fn(() => 'Do this: {{ rubric }}');
  637. mockImportModule.mockResolvedValue(mockFunction);
  638. const rubric = 'Test rubric';
  639. const llmOutput = 'Test output';
  640. const grading = {
  641. rubricPrompt: `file://${filePath}`,
  642. provider: {
  643. id: () => 'test-provider',
  644. callApi: jest.fn().mockResolvedValue({
  645. output: JSON.stringify({ pass: true, score: 1, reason: 'Test passed' }),
  646. }),
  647. },
  648. };
  649. const result = await matchesLlmRubric(rubric, llmOutput, grading);
  650. await expect(loadFromJavaScriptFile(filePath, undefined, [])).resolves.toBe(
  651. 'Do this: {{ rubric }}',
  652. );
  653. expect(grading.provider.callApi).toHaveBeenCalledWith(
  654. expect.stringContaining('Do this: Test rubric'),
  655. );
  656. expect(mockImportModule).toHaveBeenCalledWith(filePath, undefined);
  657. expect(result).toEqual(
  658. expect.objectContaining({ pass: true, score: 1, reason: 'Test passed' }),
  659. );
  660. });
  661. it('should throw an error when the external file is not found', async () => {
  662. jest.mocked(fs.existsSync).mockReturnValue(false);
  663. const rubric = 'Test rubric';
  664. const llmOutput = 'Test output';
  665. const grading = {
  666. rubricPrompt: `file://${mockFilePath}`,
  667. provider: {
  668. id: () => 'test-provider',
  669. callApi: jest.fn().mockResolvedValue({
  670. output: JSON.stringify({ pass: true, score: 1, reason: 'Test passed' }),
  671. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  672. }),
  673. },
  674. };
  675. await expect(matchesLlmRubric(rubric, llmOutput, grading)).rejects.toThrow(
  676. 'File does not exist',
  677. );
  678. expect(fs.existsSync).toHaveBeenCalledWith(
  679. expect.stringContaining(path.join('path', 'to', 'external', 'rubric.txt')),
  680. );
  681. expect(fs.readFileSync).not.toHaveBeenCalled();
  682. expect(grading.provider.callApi).not.toHaveBeenCalled();
  683. });
  684. it('should not call remote when rubric prompt is overridden, even if redteam is enabled', async () => {
  685. const rubric = 'Test rubric';
  686. const llmOutput = 'Test output';
  687. const grading = {
  688. rubricPrompt: 'Custom prompt',
  689. provider: {
  690. id: () => 'test-provider',
  691. callApi: jest.fn().mockResolvedValue({
  692. output: JSON.stringify({ pass: true, score: 1, reason: 'Test passed' }),
  693. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  694. }),
  695. },
  696. };
  697. // Give it a redteam config
  698. cliState.config = { redteam: {} };
  699. await matchesLlmRubric(rubric, llmOutput, grading);
  700. const { doRemoteGrading } = remoteGrading;
  701. expect(doRemoteGrading).not.toHaveBeenCalled();
  702. expect(grading.provider.callApi).toHaveBeenCalledWith(expect.stringContaining('Custom prompt'));
  703. });
  704. it('should call remote when redteam is enabled and rubric prompt is not overridden', async () => {
  705. const rubric = 'Test rubric';
  706. const llmOutput = 'Test output';
  707. const grading = {
  708. provider: {
  709. id: () => 'test-provider',
  710. callApi: jest.fn().mockResolvedValue({
  711. output: JSON.stringify({ pass: true, score: 1, reason: 'Test passed' }),
  712. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  713. }),
  714. },
  715. };
  716. // Clear and set up specific mock behavior for this test
  717. jest.mocked(remoteGrading.doRemoteGrading).mockClear();
  718. jest.mocked(remoteGrading.doRemoteGrading).mockResolvedValue({
  719. pass: true,
  720. score: 1,
  721. reason: 'Remote grading passed',
  722. });
  723. // Import and set up shouldGenerateRemote mock properly
  724. const { shouldGenerateRemote } = jest.requireMock('../../src/redteam/remoteGeneration');
  725. jest.mocked(shouldGenerateRemote).mockReturnValue(true);
  726. // Give it a redteam config
  727. (cliState as any).config = { redteam: {} };
  728. await matchesLlmRubric(rubric, llmOutput, grading);
  729. const { doRemoteGrading } = remoteGrading;
  730. expect(doRemoteGrading).toHaveBeenCalledWith({
  731. task: 'llm-rubric',
  732. rubric,
  733. output: llmOutput,
  734. vars: {},
  735. });
  736. expect(grading.provider.callApi).not.toHaveBeenCalled();
  737. });
  738. });
  739. describe('tryParse and renderLlmRubricPrompt', () => {
  740. let tryParse: (content: string | null | undefined) => any;
  741. beforeAll(async () => {
  742. const context: { capturedFn: null | Function } = { capturedFn: null };
  743. await renderLlmRubricPrompt('{"test":"value"}', {
  744. __capture(fn: Function) {
  745. context.capturedFn = fn;
  746. return 'captured';
  747. },
  748. });
  749. tryParse = function (content: string | null | undefined) {
  750. try {
  751. if (content === null || content === undefined) {
  752. return content;
  753. }
  754. return JSON.parse(content);
  755. } catch {}
  756. return content;
  757. };
  758. });
  759. it('should parse valid JSON', () => {
  760. const input = '{"key": "value"}';
  761. expect(tryParse(input)).toEqual({ key: 'value' });
  762. });
  763. it('should return original string for invalid JSON', () => {
  764. const input = 'not json';
  765. expect(tryParse(input)).toBe('not json');
  766. });
  767. it('should handle empty string', () => {
  768. const input = '';
  769. expect(tryParse(input)).toBe('');
  770. });
  771. it('should handle null and undefined', () => {
  772. expect(tryParse(null)).toBeNull();
  773. expect(tryParse(undefined)).toBeUndefined();
  774. });
  775. it('should render strings inside JSON objects', async () => {
  776. const template = '{"role": "user", "content": "Hello {{name}}"}';
  777. const result = await renderLlmRubricPrompt(template, { name: 'World' });
  778. const parsed = JSON.parse(result);
  779. expect(parsed).toEqual({ role: 'user', content: 'Hello World' });
  780. });
  781. it('should preserve JSON structure while rendering only strings', async () => {
  782. const template = '{"nested": {"text": "{{var}}", "number": 42}}';
  783. const result = await renderLlmRubricPrompt(template, { var: 'test' });
  784. const parsed = JSON.parse(result);
  785. expect(parsed).toEqual({ nested: { text: 'test', number: 42 } });
  786. });
  787. it('should handle non-JSON templates with legacy rendering', async () => {
  788. const template = 'Hello {{name}}';
  789. const result = await renderLlmRubricPrompt(template, { name: 'World' });
  790. expect(result).toBe('Hello World');
  791. });
  792. it('should handle complex objects in context', async () => {
  793. const template = '{"text": "{{object}}"}';
  794. const complexObject = { foo: 'bar', baz: [1, 2, 3] };
  795. const result = await renderLlmRubricPrompt(template, { object: complexObject });
  796. const parsed = JSON.parse(result);
  797. expect(typeof parsed.text).toBe('string');
  798. // With our fix, this should now be stringified JSON instead of [object Object]
  799. expect(parsed.text).toBe(JSON.stringify(complexObject));
  800. });
  801. it('should properly stringify objects', async () => {
  802. const template = 'Source Text:\n{{input}}';
  803. // Create objects that would typically cause the [object Object] issue
  804. const objects = [
  805. { name: 'Object 1', properties: { color: 'red', size: 'large' } },
  806. { name: 'Object 2', properties: { color: 'blue', size: 'small' } },
  807. ];
  808. const result = await renderLlmRubricPrompt(template, { input: objects });
  809. // With our fix, this should properly stringify the objects
  810. expect(result).not.toContain('[object Object]');
  811. expect(result).toContain(JSON.stringify(objects[0]));
  812. expect(result).toContain(JSON.stringify(objects[1]));
  813. });
  814. it('should handle mixed arrays of objects and primitives', async () => {
  815. const template = 'Items: {{items}}';
  816. const mixedArray = ['string item', { name: 'Object item' }, 42, [1, 2, 3]];
  817. const result = await renderLlmRubricPrompt(template, { items: mixedArray });
  818. // Objects in array should be stringified
  819. expect(result).not.toContain('[object Object]');
  820. expect(result).toContain('string item');
  821. expect(result).toContain(JSON.stringify({ name: 'Object item' }));
  822. expect(result).toContain('42');
  823. expect(result).toContain(JSON.stringify([1, 2, 3]));
  824. });
  825. it('should render arrays of objects correctly', async () => {
  826. const template = '{"items": [{"name": "{{name1}}"}, {"name": "{{name2}}"}]}';
  827. const result = await renderLlmRubricPrompt(template, { name1: 'Alice', name2: 'Bob' });
  828. const parsed = JSON.parse(result);
  829. expect(parsed).toEqual({
  830. items: [{ name: 'Alice' }, { name: 'Bob' }],
  831. });
  832. });
  833. it('should handle multiline strings', async () => {
  834. const template = `{"content": "Line 1\\nLine {{number}}\\nLine 3"}`;
  835. const result = await renderLlmRubricPrompt(template, { number: '2' });
  836. const parsed = JSON.parse(result);
  837. expect(parsed).toEqual({
  838. content: 'Line 1\nLine 2\nLine 3',
  839. });
  840. });
  841. it('should handle nested templates', async () => {
  842. const template = '{"outer": "{{value1}}", "inner": {"value": "{{value2}}"}}';
  843. const result = await renderLlmRubricPrompt(template, {
  844. value1: 'outer value',
  845. value2: 'inner value',
  846. });
  847. const parsed = JSON.parse(result);
  848. expect(parsed).toEqual({
  849. outer: 'outer value',
  850. inner: { value: 'inner value' },
  851. });
  852. });
  853. it('should handle escaping in JSON strings', async () => {
  854. const template = '{"content": "This needs \\"escaping\\" and {{var}} too"}';
  855. const result = await renderLlmRubricPrompt(template, { var: 'var with "quotes"' });
  856. const parsed = JSON.parse(result);
  857. expect(parsed.content).toBe('This needs "escaping" and var with "quotes" too');
  858. });
  859. it('should work with nested arrays and objects', async () => {
  860. const template = JSON.stringify({
  861. role: 'system',
  862. content: 'Process this: {{input}}',
  863. config: {
  864. options: [
  865. { id: 1, label: '{{option1}}' },
  866. { id: 2, label: '{{option2}}' },
  867. ],
  868. },
  869. });
  870. const evalResult = await renderLlmRubricPrompt(template, {
  871. input: 'test input',
  872. option1: 'First Option',
  873. option2: 'Second Option',
  874. });
  875. const parsed = JSON.parse(evalResult);
  876. expect(parsed.content).toBe('Process this: test input');
  877. expect(parsed.config.options[0].label).toBe('First Option');
  878. expect(parsed.config.options[1].label).toBe('Second Option');
  879. });
  880. it('should handle rendering statements with join filter', async () => {
  881. const statements = ['Statement 1', 'Statement 2', 'Statement 3'];
  882. const template = 'statements:\n{{statements|join("\\n")}}';
  883. const result = await renderLlmRubricPrompt(template, { statements });
  884. const expected = 'statements:\nStatement 1\nStatement 2\nStatement 3';
  885. expect(result).toBe(expected);
  886. });
  887. it('should stringify objects in arrays', async () => {
  888. const template = 'Items: {{items}}';
  889. const items = [{ name: 'Item 1', price: 10 }, 'string item', { name: 'Item 2', price: 20 }];
  890. const result = await renderLlmRubricPrompt(template, { items });
  891. expect(result).not.toContain('[object Object]');
  892. expect(result).toContain(JSON.stringify(items[0]));
  893. expect(result).toContain('string item');
  894. expect(result).toContain(JSON.stringify(items[2]));
  895. });
  896. it('should stringify deeply nested objects and arrays', async () => {
  897. const template = 'Complex data: {{data}}';
  898. const data = {
  899. products: [
  900. {
  901. name: 'Item 1',
  902. price: 10,
  903. details: {
  904. color: 'red',
  905. specs: { weight: '2kg', dimensions: { width: 10, height: 20 } },
  906. },
  907. },
  908. 'string item',
  909. {
  910. name: 'Item 2',
  911. price: 20,
  912. nested: [{ a: 1 }, { b: 2 }],
  913. metadata: { tags: ['electronics', 'gadget'] },
  914. },
  915. ],
  916. };
  917. const result = await renderLlmRubricPrompt(template, { data });
  918. expect(result).not.toContain('[object Object]');
  919. expect(result).toContain('"specs":{"weight":"2kg"');
  920. expect(result).toContain('"dimensions":{"width":10,"height":20}');
  921. expect(result).toContain('[{"a":1},{"b":2}]');
  922. expect(result).toContain('"tags":["electronics","gadget"]');
  923. expect(result).toContain('string item');
  924. });
  925. });
Tip!

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

Comments

Loading...