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

matchers.test.ts 27 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
  1. import { getAndCheckProvider, getGradingProvider, matchesClassification } from '../src/matchers';
  2. import { OpenAiChatCompletionProvider, OpenAiEmbeddingProvider } from '../src/providers/openai';
  3. import {
  4. matchesSimilarity,
  5. matchesLlmRubric,
  6. matchesFactuality,
  7. matchesClosedQa,
  8. matchesAnswerRelevance,
  9. matchesContextRelevance,
  10. matchesContextRecall,
  11. matchesContextFaithfulness,
  12. } from '../src/matchers';
  13. import { DefaultEmbeddingProvider, DefaultGradingProvider } from '../src/providers/openai';
  14. import { TestGrader } from './assertions.test';
  15. import type {
  16. GradingConfig,
  17. ProviderResponse,
  18. ProviderClassificationResponse,
  19. ApiProvider,
  20. ProviderTypeMap,
  21. } from '../src/types';
  22. import { HuggingfaceTextClassificationProvider } from '../src/providers/huggingface';
  23. jest.mock('../src/esm');
  24. const Grader = new TestGrader();
  25. describe('matchesSimilarity', () => {
  26. beforeEach(() => {
  27. jest.spyOn(DefaultEmbeddingProvider, 'callEmbeddingApi').mockImplementation((text) => {
  28. if (text === 'Expected output' || text === 'Sample output') {
  29. return Promise.resolve({
  30. embedding: [1, 0, 0],
  31. tokenUsage: { total: 5, prompt: 2, completion: 3 },
  32. });
  33. } else if (text === 'Different output') {
  34. return Promise.resolve({
  35. embedding: [0, 1, 0],
  36. tokenUsage: { total: 5, prompt: 2, completion: 3 },
  37. });
  38. }
  39. return Promise.reject(new Error('Unexpected input'));
  40. });
  41. });
  42. afterEach(() => {
  43. jest.restoreAllMocks();
  44. });
  45. it('should pass when similarity is above the threshold', async () => {
  46. const expected = 'Expected output';
  47. const output = 'Sample output';
  48. const threshold = 0.5;
  49. const result = await matchesSimilarity(expected, output, threshold);
  50. expect(result.pass).toBeTruthy();
  51. expect(result.reason).toBe('Similarity 1.00 is greater than threshold 0.5');
  52. });
  53. it('should fail when similarity is below the threshold', async () => {
  54. const expected = 'Expected output';
  55. const output = 'Different output';
  56. const threshold = 0.9;
  57. const result = await matchesSimilarity(expected, output, threshold);
  58. expect(result.pass).toBeFalsy();
  59. expect(result.reason).toBe('Similarity 0.00 is less than threshold 0.9');
  60. });
  61. it('should fail when inverted similarity is above the threshold', async () => {
  62. const expected = 'Expected output';
  63. const output = 'Sample output';
  64. const threshold = 0.5;
  65. const result = await matchesSimilarity(expected, output, threshold, true /* invert */);
  66. expect(result.pass).toBeFalsy();
  67. expect(result.reason).toBe('Similarity 1.00 is greater than threshold 0.5');
  68. });
  69. it('should pass when inverted similarity is below the threshold', async () => {
  70. const expected = 'Expected output';
  71. const output = 'Different output';
  72. const threshold = 0.9;
  73. const result = await matchesSimilarity(expected, output, threshold, true /* invert */);
  74. expect(result.pass).toBeTruthy();
  75. expect(result.reason).toBe('Similarity 0.00 is less than threshold 0.9');
  76. });
  77. it('should use the overridden simmilarity grading config', async () => {
  78. const expected = 'Expected output';
  79. const output = 'Sample output';
  80. const threshold = 0.5;
  81. const grading: GradingConfig = {
  82. provider: {
  83. id: 'openai:embedding:text-embedding-ada-9999999',
  84. config: {
  85. apiKey: 'abc123',
  86. temperature: 3.1415926,
  87. },
  88. },
  89. };
  90. const mockCallApi = jest.spyOn(OpenAiEmbeddingProvider.prototype, 'callEmbeddingApi');
  91. mockCallApi.mockImplementation(function (this: OpenAiChatCompletionProvider) {
  92. expect(this.config.temperature).toBe(3.1415926);
  93. expect(this.getApiKey()).toBe('abc123');
  94. return Promise.resolve({
  95. embedding: [1, 0, 0],
  96. tokenUsage: { total: 5, prompt: 2, completion: 3 },
  97. });
  98. });
  99. const result = await matchesSimilarity(expected, output, threshold, false, grading);
  100. expect(result.pass).toBeTruthy();
  101. expect(result.reason).toBe('Similarity 1.00 is greater than threshold 0.5');
  102. expect(mockCallApi).toHaveBeenCalled();
  103. mockCallApi.mockRestore();
  104. });
  105. it('should throw an error when API call fails', async () => {
  106. const expected = 'Expected output';
  107. const output = 'Sample output';
  108. const threshold = 0.5;
  109. const grading: GradingConfig = {
  110. provider: {
  111. id: 'openai:embedding:text-embedding-ada-9999999',
  112. config: {
  113. apiKey: 'abc123',
  114. temperature: 3.1415926,
  115. },
  116. },
  117. };
  118. jest
  119. .spyOn(OpenAiEmbeddingProvider.prototype, 'callEmbeddingApi')
  120. .mockRejectedValueOnce(new Error('API call failed'));
  121. await expect(async () => {
  122. await matchesSimilarity(expected, output, threshold, false, grading);
  123. }).rejects.toThrow('API call failed');
  124. });
  125. });
  126. describe('matchesLlmRubric', () => {
  127. it('should pass when the grading provider returns a passing result', async () => {
  128. const expected = 'Expected output';
  129. const output = 'Sample output';
  130. const options: GradingConfig = {
  131. rubricPrompt: 'Grading prompt',
  132. provider: Grader,
  133. };
  134. const result = await matchesLlmRubric(expected, output, options);
  135. expect(result.pass).toBeTruthy();
  136. });
  137. it('should fail when the grading provider returns a failing result', async () => {
  138. const expected = 'Expected output';
  139. const output = 'Different output';
  140. const options: GradingConfig = {
  141. rubricPrompt: 'Grading prompt',
  142. provider: Grader,
  143. };
  144. jest.spyOn(Grader, 'callApi').mockResolvedValueOnce({
  145. output: JSON.stringify({ pass: false, reason: 'Grading failed' }),
  146. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  147. });
  148. const result = await matchesLlmRubric(expected, output, options);
  149. expect(result.pass).toBeFalsy();
  150. expect(result.reason).toBe('Grading failed');
  151. });
  152. it('should use the overridden llm rubric grading config', async () => {
  153. const expected = 'Expected output';
  154. const output = 'Sample output';
  155. const options: GradingConfig = {
  156. rubricPrompt: 'Grading prompt',
  157. provider: {
  158. id: 'openai:gpt-3.5-turbo',
  159. config: {
  160. apiKey: 'abc123',
  161. temperature: 3.1415926,
  162. },
  163. },
  164. };
  165. const mockCallApi = jest.spyOn(OpenAiChatCompletionProvider.prototype, 'callApi');
  166. mockCallApi.mockImplementation(function (this: OpenAiChatCompletionProvider) {
  167. expect(this.config.temperature).toBe(3.1415926);
  168. expect(this.getApiKey()).toBe('abc123');
  169. return Promise.resolve({
  170. output: JSON.stringify({ pass: true, reason: 'Grading passed' }),
  171. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  172. });
  173. });
  174. const result = await matchesLlmRubric(expected, output, options);
  175. expect(result.reason).toBe('Grading passed');
  176. expect(result.pass).toBeTruthy();
  177. expect(mockCallApi).toHaveBeenCalled();
  178. mockCallApi.mockRestore();
  179. });
  180. });
  181. describe('matchesFactuality', () => {
  182. it('should pass when the factuality check passes', async () => {
  183. const input = 'Input text';
  184. const expected = 'Expected output';
  185. const output = 'Sample output';
  186. const grading = {};
  187. jest.spyOn(DefaultGradingProvider, 'callApi').mockResolvedValueOnce({
  188. output:
  189. '(A) The submitted answer is a subset of the expert answer and is fully consistent with it.',
  190. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  191. });
  192. const result = await matchesFactuality(input, expected, output, grading);
  193. expect(result.pass).toBeTruthy();
  194. expect(result.reason).toBe(
  195. 'The submitted answer is a subset of the expert answer and is fully consistent with it.',
  196. );
  197. });
  198. it('should fail when the factuality check fails', async () => {
  199. const input = 'Input text';
  200. const expected = 'Expected output';
  201. const output = 'Sample output';
  202. const grading = {};
  203. jest.spyOn(DefaultGradingProvider, 'callApi').mockResolvedValueOnce({
  204. output: '(D) There is a disagreement between the submitted answer and the expert answer.',
  205. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  206. });
  207. const result = await matchesFactuality(input, expected, output, grading);
  208. expect(result.pass).toBeFalsy();
  209. expect(result.reason).toBe(
  210. 'There is a disagreement between the submitted answer and the expert answer.',
  211. );
  212. });
  213. it('should use the overridden factuality grading config', async () => {
  214. const input = 'Input text';
  215. const expected = 'Expected output';
  216. const output = 'Sample output';
  217. const grading = {
  218. factuality: {
  219. subset: 0.8,
  220. superset: 0.9,
  221. agree: 1,
  222. disagree: 0,
  223. differButFactual: 0.7,
  224. },
  225. };
  226. jest.spyOn(DefaultGradingProvider, 'callApi').mockResolvedValueOnce({
  227. output:
  228. '(A) The submitted answer is a subset of the expert answer and is fully consistent with it.',
  229. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  230. });
  231. const result = await matchesFactuality(input, expected, output, grading);
  232. expect(result.score).toBe(0.8);
  233. expect(result.pass).toBeTruthy();
  234. expect(result.reason).toBe(
  235. 'The submitted answer is a subset of the expert answer and is fully consistent with it.',
  236. );
  237. });
  238. it('should throw an error when an error occurs', async () => {
  239. const input = 'Input text';
  240. const expected = 'Expected output';
  241. const output = 'Sample output';
  242. const grading = {};
  243. jest.spyOn(DefaultGradingProvider, 'callApi').mockImplementation(() => {
  244. throw new Error('An error occurred');
  245. });
  246. await expect(matchesFactuality(input, expected, output, grading)).rejects.toThrow(
  247. 'An error occurred',
  248. );
  249. });
  250. });
  251. describe('matchesClosedQa', () => {
  252. it('should pass when the closed QA check passes', async () => {
  253. const input = 'Input text';
  254. const expected = 'Expected output';
  255. const output = 'Sample output';
  256. const grading = {};
  257. jest.spyOn(DefaultGradingProvider, 'callApi').mockResolvedValueOnce({
  258. output: 'foo \n \n bar\n Y Y',
  259. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  260. });
  261. const result = await matchesClosedQa(input, expected, output, grading);
  262. expect(result.pass).toBeTruthy();
  263. expect(result.reason).toBe('The submission meets the criterion');
  264. });
  265. it('should fail when the closed QA check fails', async () => {
  266. const input = 'Input text';
  267. const expected = 'Expected output';
  268. const output = 'Sample output';
  269. const grading = {};
  270. jest.spyOn(DefaultGradingProvider, 'callApi').mockResolvedValueOnce({
  271. output: 'foo bar N',
  272. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  273. });
  274. const result = await matchesClosedQa(input, expected, output, grading);
  275. expect(result.pass).toBeFalsy();
  276. expect(result.reason).toBe('The submission does not meet the criterion:\nfoo bar N');
  277. });
  278. it('should throw an error when an error occurs', async () => {
  279. const input = 'Input text';
  280. const expected = 'Expected output';
  281. const output = 'Sample output';
  282. const grading = {};
  283. jest.spyOn(DefaultGradingProvider, 'callApi').mockImplementation(() => {
  284. throw new Error('An error occurred');
  285. });
  286. await expect(matchesClosedQa(input, expected, output, grading)).rejects.toThrow(
  287. 'An error occurred',
  288. );
  289. });
  290. it('should handle input, criteria, and completion that need escaping', async () => {
  291. const input = 'Input "text" with \\ escape characters and \\"nested\\" escapes';
  292. const expected = 'Expected "output" with \\\\ escape characters and \\"nested\\" escapes';
  293. const output = 'Sample "output" with \\\\ escape characters and \\"nested\\" escapes';
  294. const grading = {};
  295. let isJson = false;
  296. jest.spyOn(DefaultGradingProvider, 'callApi').mockImplementation((prompt) => {
  297. try {
  298. JSON.parse(prompt);
  299. isJson = true;
  300. } catch (err) {
  301. isJson = false;
  302. }
  303. return Promise.resolve({
  304. output: 'foo \n \n bar\n Y Y',
  305. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  306. });
  307. });
  308. const result = await matchesClosedQa(input, expected, output, grading);
  309. expect(isJson).toBeTruthy();
  310. expect(result.pass).toBeTruthy();
  311. expect(result.reason).toBe('The submission meets the criterion');
  312. });
  313. });
  314. describe('getGradingProvider', () => {
  315. it('should return the correct provider when provider is a string', async () => {
  316. const provider = await getGradingProvider(
  317. 'text',
  318. 'openai:chat:gpt-3.5-turbo-foobar',
  319. DefaultGradingProvider,
  320. );
  321. // ok for this not to match exactly when the string is parsed
  322. expect(provider?.id()).toBe('openai:gpt-3.5-turbo-foobar');
  323. });
  324. it('should return the correct provider when provider is an ApiProvider', async () => {
  325. const provider = await getGradingProvider(
  326. 'embedding',
  327. DefaultEmbeddingProvider,
  328. DefaultGradingProvider,
  329. );
  330. expect(provider).toBe(DefaultEmbeddingProvider);
  331. });
  332. it('should return the correct provider when provider is ProviderOptions', async () => {
  333. const providerOptions = {
  334. id: 'openai:chat:gpt-3.5-turbo-foobar',
  335. config: {
  336. apiKey: 'abc123',
  337. temperature: 3.1415926,
  338. },
  339. };
  340. const provider = await getGradingProvider('text', providerOptions, DefaultGradingProvider);
  341. expect(provider?.id()).toBe('openai:chat:gpt-3.5-turbo-foobar');
  342. });
  343. it('should return the default provider when provider is not provided', async () => {
  344. const provider = await getGradingProvider('text', undefined, DefaultGradingProvider);
  345. expect(provider).toBe(DefaultGradingProvider);
  346. });
  347. });
  348. describe('getAndCheckProvider', () => {
  349. it('should return the default provider when provider is not defined', async () => {
  350. expect(await getAndCheckProvider('text', undefined, DefaultGradingProvider, 'test check')).toBe(
  351. DefaultGradingProvider,
  352. );
  353. });
  354. it('should return the default provider when provider does not support type', async () => {
  355. const provider = {
  356. id: () => 'test-provider',
  357. callApi: () => Promise.resolve({ output: 'test' }),
  358. };
  359. expect(
  360. await getAndCheckProvider('embedding', provider, DefaultEmbeddingProvider, 'test check'),
  361. ).toBe(DefaultEmbeddingProvider);
  362. });
  363. it('should return the provider if it implements the required method', async () => {
  364. const provider = {
  365. id: () => 'test-provider',
  366. callApi: () => Promise.resolve({ output: 'test' }),
  367. callEmbeddingApi: () => Promise.resolve({ embedding: [] }),
  368. };
  369. const result = await getAndCheckProvider(
  370. 'embedding',
  371. provider,
  372. DefaultEmbeddingProvider,
  373. 'test check',
  374. );
  375. expect(result).toBe(provider);
  376. });
  377. });
  378. describe('getGradingProvider', () => {
  379. it('should return the default provider when no provider is specified', async () => {
  380. const provider = await getGradingProvider('text', undefined, DefaultGradingProvider);
  381. expect(provider).toBe(DefaultGradingProvider);
  382. });
  383. it('should return a specific provider when a provider id is specified', async () => {
  384. const provider = await getGradingProvider('text', 'openai:chat:foo', DefaultGradingProvider);
  385. // loadApiProvider removes `chat` from the id
  386. expect(provider?.id()).toBe('openai:foo');
  387. });
  388. it('should return a provider from ApiProvider when specified', async () => {
  389. const providerOptions: ApiProvider = {
  390. id: () => 'custom-provider',
  391. callApi: async () => ({}),
  392. };
  393. const provider = await getGradingProvider('text', providerOptions, DefaultGradingProvider);
  394. expect(provider?.id()).toBe('custom-provider');
  395. });
  396. it('should return a provider from ProviderTypeMap when specified', async () => {
  397. const providerTypeMap: ProviderTypeMap = {
  398. text: {
  399. id: 'openai:chat:foo',
  400. },
  401. embedding: {
  402. id: 'openai:embedding:bar',
  403. },
  404. };
  405. const provider = await getGradingProvider('text', providerTypeMap, DefaultGradingProvider);
  406. expect(provider?.id()).toBe('openai:chat:foo');
  407. });
  408. it('should return a provider from ProviderTypeMap with basic strings', async () => {
  409. const providerTypeMap: ProviderTypeMap = {
  410. text: 'openai:chat:foo',
  411. embedding: 'openai:embedding:bar',
  412. };
  413. const provider = await getGradingProvider('text', providerTypeMap, DefaultGradingProvider);
  414. expect(provider?.id()).toBe('openai:foo');
  415. });
  416. it('should throw an error when the provider does not match the type', async () => {
  417. const providerTypeMap: ProviderTypeMap = {
  418. embedding: {
  419. id: 'openai:embedding:foo',
  420. },
  421. };
  422. await expect(
  423. getGradingProvider('text', providerTypeMap, DefaultGradingProvider),
  424. ).rejects.toThrow(
  425. new Error(
  426. `Invalid provider definition for output type 'text': ${JSON.stringify(
  427. providerTypeMap,
  428. null,
  429. 2,
  430. )}`,
  431. ),
  432. );
  433. });
  434. });
  435. describe('matchesAnswerRelevance', () => {
  436. it('should pass when the relevance score is above the threshold', async () => {
  437. const input = 'Input text';
  438. const output = 'Sample output';
  439. const threshold = 0.5;
  440. const mockCallApi = jest.spyOn(DefaultGradingProvider, 'callApi');
  441. mockCallApi.mockImplementation(() => {
  442. return Promise.resolve({
  443. output: 'foobar',
  444. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  445. });
  446. });
  447. const mockCallEmbeddingApi = jest.spyOn(DefaultEmbeddingProvider, 'callEmbeddingApi');
  448. mockCallEmbeddingApi.mockImplementation(function (this: OpenAiEmbeddingProvider) {
  449. return Promise.resolve({
  450. embedding: [1, 0, 0],
  451. tokenUsage: { total: 5, prompt: 2, completion: 3 },
  452. });
  453. });
  454. const result = await matchesAnswerRelevance(input, output, threshold);
  455. expect(result.pass).toBeTruthy();
  456. expect(result.reason).toBe('Relevance 1.00 is greater than threshold 0.5');
  457. expect(mockCallApi).toHaveBeenCalled();
  458. expect(mockCallEmbeddingApi).toHaveBeenCalled();
  459. mockCallApi.mockRestore();
  460. mockCallEmbeddingApi.mockRestore();
  461. });
  462. it('should fail when the relevance score is below the threshold', async () => {
  463. const input = 'Input text';
  464. const output = 'Different output';
  465. const threshold = 0.5;
  466. const mockCallApi = jest.spyOn(DefaultGradingProvider, 'callApi');
  467. mockCallApi.mockImplementation((text) => {
  468. return Promise.resolve({
  469. output: text,
  470. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  471. });
  472. });
  473. const mockCallEmbeddingApi = jest.spyOn(DefaultEmbeddingProvider, 'callEmbeddingApi');
  474. mockCallEmbeddingApi.mockImplementation((text) => {
  475. if (text.includes('Input text')) {
  476. return Promise.resolve({
  477. embedding: [1, 0, 0],
  478. tokenUsage: { total: 5, prompt: 2, completion: 3 },
  479. });
  480. } else if (text.includes('Different output')) {
  481. return Promise.resolve({
  482. embedding: [0, 1, 0],
  483. tokenUsage: { total: 5, prompt: 2, completion: 3 },
  484. });
  485. }
  486. return Promise.reject(new Error('Unexpected input ' + text));
  487. });
  488. const result = await matchesAnswerRelevance(input, output, threshold);
  489. expect(result.pass).toBeFalsy();
  490. expect(result.reason).toBe('Relevance 0.00 is less than threshold 0.5');
  491. expect(mockCallApi).toHaveBeenCalled();
  492. expect(mockCallEmbeddingApi).toHaveBeenCalled();
  493. mockCallApi.mockRestore();
  494. mockCallEmbeddingApi.mockRestore();
  495. });
  496. });
  497. describe('matchesClassification', () => {
  498. class TestGrader implements ApiProvider {
  499. async callApi(): Promise<ProviderResponse> {
  500. throw new Error('Not implemented');
  501. }
  502. async callClassificationApi(): Promise<ProviderClassificationResponse> {
  503. return {
  504. classification: {
  505. classA: 0.6,
  506. classB: 0.5,
  507. },
  508. };
  509. }
  510. id(): string {
  511. return 'TestClassificationProvider';
  512. }
  513. }
  514. it('should pass when the classification score is above the threshold', async () => {
  515. const expected = 'classA';
  516. const output = 'Sample output';
  517. const threshold = 0.5;
  518. const grader = new TestGrader();
  519. const grading: GradingConfig = {
  520. provider: grader,
  521. };
  522. const result = await matchesClassification(expected, output, threshold, grading);
  523. expect(result.pass).toBeTruthy();
  524. expect(result.reason).toBe(`Classification ${expected} has score 0.60 >= ${threshold}`);
  525. });
  526. it('should fail when the classification score is below the threshold', async () => {
  527. const expected = 'classA';
  528. const output = 'Different output';
  529. const threshold = 0.9;
  530. const grader = new TestGrader();
  531. const grading: GradingConfig = {
  532. provider: grader,
  533. };
  534. const result = await matchesClassification(expected, output, threshold, grading);
  535. expect(result.pass).toBeFalsy();
  536. expect(result.reason).toBe(`Classification ${expected} has score 0.60 < ${threshold}`);
  537. });
  538. it('should pass when the maximum classification score is above the threshold with undefined expected', async () => {
  539. const expected = undefined;
  540. const output = 'Sample output';
  541. const threshold = 0.55;
  542. const grader = new TestGrader();
  543. const grading: GradingConfig = {
  544. provider: grader,
  545. };
  546. const result = await matchesClassification(expected, output, threshold, grading);
  547. expect(result.pass).toBeTruthy();
  548. expect(result.reason).toBe(`Maximum classification score 0.60 >= ${threshold}`);
  549. });
  550. it('should use the overridden classification grading config', async () => {
  551. const expected = 'classA';
  552. const output = 'Sample output';
  553. const threshold = 0.5;
  554. const grading: GradingConfig = {
  555. provider: {
  556. id: 'hf:text-classification:foobar',
  557. },
  558. };
  559. const mockCallApi = jest.spyOn(
  560. HuggingfaceTextClassificationProvider.prototype,
  561. 'callClassificationApi',
  562. );
  563. mockCallApi.mockImplementation(function (this: HuggingfaceTextClassificationProvider) {
  564. return Promise.resolve({
  565. classification: { [expected]: 0.6 },
  566. });
  567. });
  568. const result = await matchesClassification(expected, output, threshold, grading);
  569. expect(result.pass).toBeTruthy();
  570. expect(result.reason).toBe(`Classification ${expected} has score 0.60 >= ${threshold}`);
  571. expect(mockCallApi).toHaveBeenCalled();
  572. mockCallApi.mockRestore();
  573. });
  574. });
  575. describe('matchesContextRelevance', () => {
  576. it('should pass when the relevance score is above the threshold', async () => {
  577. const input = 'Input text';
  578. const context = 'Context text';
  579. const threshold = 0.5;
  580. const mockCallApi = jest.spyOn(DefaultGradingProvider, 'callApi');
  581. mockCallApi.mockImplementation(() => {
  582. return Promise.resolve({
  583. output: 'foo\nbar\nbaz Insufficient Information',
  584. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  585. });
  586. });
  587. const result = await matchesContextRelevance(input, context, threshold);
  588. expect(result.pass).toBeTruthy();
  589. expect(result.reason).toBe('Relevance 0.67 is >= 0.5');
  590. expect(mockCallApi).toHaveBeenCalled();
  591. mockCallApi.mockRestore();
  592. });
  593. it('should fail when the relevance score is below the threshold', async () => {
  594. const input = 'Input text';
  595. const context = 'Context text';
  596. const threshold = 0.9;
  597. const mockCallApi = jest.spyOn(DefaultGradingProvider, 'callApi');
  598. mockCallApi.mockImplementation(() => {
  599. return Promise.resolve({
  600. output: 'foo\nbar\nbaz Insufficient Information',
  601. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  602. });
  603. });
  604. const result = await matchesContextRelevance(input, context, threshold);
  605. expect(result.pass).toBeFalsy();
  606. expect(result.reason).toBe('Relevance 0.67 is < 0.9');
  607. expect(mockCallApi).toHaveBeenCalled();
  608. mockCallApi.mockRestore();
  609. });
  610. });
  611. describe('matchesContextFaithfulness', () => {
  612. it('should pass when the faithfulness score is above the threshold', async () => {
  613. const query = 'Query text';
  614. const output = 'Output text';
  615. const context = 'Context text';
  616. const threshold = 0.5;
  617. const mockCallApi = jest.spyOn(DefaultGradingProvider, 'callApi');
  618. mockCallApi
  619. .mockImplementationOnce(() => {
  620. return Promise.resolve({
  621. output: 'Statement 1\nStatement 2\nStatement 3',
  622. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  623. });
  624. })
  625. .mockImplementationOnce(() => {
  626. return Promise.resolve({
  627. output: 'Final verdict for each statement in order: Yes. No. Yes.',
  628. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  629. });
  630. });
  631. const result = await matchesContextFaithfulness(query, output, context, threshold);
  632. expect(result.pass).toBeTruthy();
  633. expect(result.reason).toBe('Faithfulness 0.67 is >= 0.5');
  634. expect(mockCallApi).toHaveBeenCalledTimes(2);
  635. mockCallApi.mockRestore();
  636. });
  637. it('should fail when the faithfulness score is below the threshold', async () => {
  638. const query = 'Query text';
  639. const output = 'Output text';
  640. const context = 'Context text';
  641. const threshold = 0.7;
  642. const mockCallApi = jest.spyOn(DefaultGradingProvider, 'callApi');
  643. mockCallApi
  644. .mockImplementationOnce(() => {
  645. return Promise.resolve({
  646. output: 'Statement 1\nStatement 2\nStatement 3',
  647. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  648. });
  649. })
  650. .mockImplementationOnce(() => {
  651. return Promise.resolve({
  652. output: 'Final verdict for each statement in order: Yes. Yes. No.',
  653. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  654. });
  655. });
  656. const result = await matchesContextFaithfulness(query, output, context, threshold);
  657. expect(result.pass).toBeFalsy();
  658. expect(result.reason).toBe('Faithfulness 0.67 is < 0.7');
  659. expect(mockCallApi).toHaveBeenCalledTimes(2);
  660. mockCallApi.mockRestore();
  661. });
  662. });
  663. describe('matchesContextRecall', () => {
  664. it('should pass when the recall score is above the threshold', async () => {
  665. const context = 'Context text';
  666. const groundTruth = 'Ground truth text';
  667. const threshold = 0.5;
  668. const mockCallApi = jest.spyOn(DefaultGradingProvider, 'callApi');
  669. mockCallApi.mockImplementation(() => {
  670. return Promise.resolve({
  671. output: 'foo [Attributed]\nbar [Not attributed]\nbaz [Attributed]',
  672. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  673. });
  674. });
  675. const result = await matchesContextRecall(context, groundTruth, threshold);
  676. expect(result.pass).toBeTruthy();
  677. expect(result.reason).toBe('Recall 0.67 is >= 0.5');
  678. expect(mockCallApi).toHaveBeenCalled();
  679. mockCallApi.mockRestore();
  680. });
  681. it('should fail when the recall score is below the threshold', async () => {
  682. const context = 'Context text';
  683. const groundTruth = 'Ground truth text';
  684. const threshold = 0.9;
  685. const mockCallApi = jest.spyOn(DefaultGradingProvider, 'callApi');
  686. mockCallApi.mockImplementation(() => {
  687. return Promise.resolve({
  688. output: 'foo [Attributed]\nbar [Not attributed]\nbaz [Attributed]',
  689. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  690. });
  691. });
  692. const result = await matchesContextRecall(context, groundTruth, threshold);
  693. expect(result.pass).toBeFalsy();
  694. expect(result.reason).toBe('Recall 0.67 is < 0.9');
  695. expect(mockCallApi).toHaveBeenCalled();
  696. mockCallApi.mockRestore();
  697. });
  698. });
Tip!

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

Comments

Loading...