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.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
891
892
893
894
895
896
897
898
899
900
  1. import invariant from 'tiny-invariant';
  2. import logger from './logger';
  3. import { getNunjucksEngine } from './util';
  4. import { loadApiProvider } from './providers';
  5. import {
  6. ANSWER_RELEVANCY_GENERATE,
  7. SELECT_BEST_PROMPT,
  8. CONTEXT_FAITHFULNESS_LONGFORM,
  9. CONTEXT_FAITHFULNESS_NLI_STATEMENTS,
  10. CONTEXT_RECALL,
  11. CONTEXT_RECALL_ATTRIBUTED_TOKEN,
  12. CONTEXT_RELEVANCE,
  13. CONTEXT_RELEVANCE_BAD,
  14. DEFAULT_GRADING_PROMPT,
  15. OPENAI_CLOSED_QA_PROMPT,
  16. OPENAI_FACTUALITY_PROMPT,
  17. } from './prompts';
  18. import type {
  19. ApiClassificationProvider,
  20. ApiEmbeddingProvider,
  21. ApiProvider,
  22. ApiSimilarityProvider,
  23. GradingConfig,
  24. GradingResult,
  25. ProviderOptions,
  26. ProviderTypeMap,
  27. TokenUsage,
  28. ProviderType,
  29. ApiModerationProvider,
  30. } from './types';
  31. import { getDefaultProviders } from './providers/defaults';
  32. const nunjucks = getNunjucksEngine();
  33. function cosineSimilarity(vecA: number[], vecB: number[]) {
  34. if (vecA.length !== vecB.length) {
  35. throw new Error('Vectors must be of equal length');
  36. }
  37. const dotProduct = vecA.reduce((acc, val, idx) => acc + val * vecB[idx], 0);
  38. const vecAMagnitude = Math.sqrt(vecA.reduce((acc, val) => acc + val * val, 0));
  39. const vecBMagnitude = Math.sqrt(vecB.reduce((acc, val) => acc + val * val, 0));
  40. return dotProduct / (vecAMagnitude * vecBMagnitude);
  41. }
  42. function fromVars(vars?: Record<string, string | object>) {
  43. if (!vars) {
  44. return {};
  45. }
  46. const ret: Record<string, string> = {};
  47. for (const [key, value] of Object.entries(vars)) {
  48. if (typeof value === 'object') {
  49. ret[key] = JSON.stringify(value);
  50. } else {
  51. ret[key] = value;
  52. }
  53. }
  54. return ret;
  55. }
  56. async function loadFromProviderOptions(provider: ProviderOptions) {
  57. invariant(
  58. typeof provider === 'object',
  59. `Provider must be an object, but received a ${typeof provider}: ${provider}`,
  60. );
  61. invariant(
  62. !Array.isArray(provider),
  63. `Provider must be an object, but received an array: ${JSON.stringify(provider)}`,
  64. );
  65. invariant(provider.id, 'Provider supplied to assertion must have an id');
  66. // TODO(ian): set basepath if invoked from filesystem config
  67. return loadApiProvider(provider.id, { options: provider as ProviderOptions });
  68. }
  69. export async function getGradingProvider(
  70. type: ProviderType,
  71. provider: GradingConfig['provider'],
  72. defaultProvider: ApiProvider | null,
  73. ): Promise<ApiProvider | null> {
  74. let finalProvider: ApiProvider | null;
  75. if (typeof provider === 'string') {
  76. // Defined as a string
  77. finalProvider = await loadApiProvider(provider);
  78. } else if (typeof provider === 'object' && typeof (provider as ApiProvider).id === 'function') {
  79. // Defined as an ApiProvider interface
  80. finalProvider = provider as ApiProvider;
  81. } else if (typeof provider === 'object') {
  82. const typeValue = (provider as ProviderTypeMap)[type];
  83. if (typeValue) {
  84. // Defined as embedding, classification, or text record
  85. finalProvider = await getGradingProvider(type, typeValue, defaultProvider);
  86. } else if ((provider as ProviderOptions).id) {
  87. // Defined as ProviderOptions
  88. finalProvider = await loadFromProviderOptions(provider as ProviderOptions);
  89. } else if (Array.isArray(provider)) {
  90. throw new Error(
  91. `Provider must be an object or string, but received an array.\n\nCheck that the provider ${JSON.stringify(
  92. provider[0],
  93. null,
  94. 2,
  95. )} is not nested in an array.`,
  96. );
  97. } else {
  98. throw new Error(
  99. `Invalid provider definition for output type '${type}': ${JSON.stringify(
  100. provider,
  101. null,
  102. 2,
  103. )}`,
  104. );
  105. }
  106. } else {
  107. finalProvider = defaultProvider;
  108. }
  109. return finalProvider;
  110. }
  111. export async function getAndCheckProvider(
  112. type: ProviderType,
  113. provider: GradingConfig['provider'],
  114. defaultProvider: ApiProvider | null,
  115. checkName: string,
  116. ): Promise<ApiProvider> {
  117. let matchedProvider = await getGradingProvider(type, provider, defaultProvider);
  118. if (!matchedProvider) {
  119. if (defaultProvider) {
  120. logger.warn(`No provider of type ${type} found for '${checkName}', falling back to default`);
  121. return defaultProvider;
  122. } else {
  123. throw new Error(`No provider of type ${type} found for '${checkName}'`);
  124. }
  125. }
  126. let isValidProviderType = true;
  127. if (type === 'embedding') {
  128. isValidProviderType =
  129. 'callEmbeddingApi' in matchedProvider || 'callSimilarityApi' in matchedProvider;
  130. } else if (type === 'classification') {
  131. isValidProviderType = 'callClassificationApi' in matchedProvider;
  132. } else if (type === 'moderation') {
  133. isValidProviderType = 'callModerationApi' in matchedProvider;
  134. }
  135. if (!isValidProviderType) {
  136. if (defaultProvider) {
  137. logger.warn(
  138. `Provider ${matchedProvider.id()} is not a valid ${type} provider for '${checkName}', falling back to default`,
  139. );
  140. return defaultProvider;
  141. } else {
  142. throw new Error(
  143. `Provider ${matchedProvider.id()} is not a valid ${type} provider for '${checkName}'`,
  144. );
  145. }
  146. }
  147. return matchedProvider;
  148. }
  149. function fail(reason: string, tokensUsed?: Partial<TokenUsage>): Omit<GradingResult, 'assertion'> {
  150. return {
  151. pass: false,
  152. score: 0,
  153. reason,
  154. tokensUsed: {
  155. total: tokensUsed?.total || 0,
  156. prompt: tokensUsed?.prompt || 0,
  157. completion: tokensUsed?.completion || 0,
  158. },
  159. };
  160. }
  161. export async function matchesSimilarity(
  162. expected: string,
  163. output: string,
  164. threshold: number,
  165. inverse: boolean = false,
  166. grading?: GradingConfig,
  167. ): Promise<Omit<GradingResult, 'assertion'>> {
  168. let finalProvider = (await getAndCheckProvider(
  169. 'embedding',
  170. grading?.provider,
  171. getDefaultProviders().embeddingProvider,
  172. 'similarity check',
  173. )) as ApiEmbeddingProvider | ApiSimilarityProvider;
  174. let similarity: number;
  175. let tokensUsed: TokenUsage = {
  176. total: 0,
  177. prompt: 0,
  178. completion: 0,
  179. };
  180. if ('callSimilarityApi' in finalProvider) {
  181. const similarityResp = await finalProvider.callSimilarityApi(expected, output);
  182. tokensUsed = {
  183. ...tokensUsed,
  184. ...similarityResp.tokenUsage,
  185. };
  186. if (similarityResp.error) {
  187. return fail(similarityResp.error, tokensUsed);
  188. }
  189. if (similarityResp.similarity == null) {
  190. return fail('Unknown error fetching similarity', tokensUsed);
  191. }
  192. similarity = similarityResp.similarity;
  193. } else if ('callEmbeddingApi' in finalProvider) {
  194. const expectedEmbedding = await finalProvider.callEmbeddingApi(expected);
  195. const outputEmbedding = await finalProvider.callEmbeddingApi(output);
  196. tokensUsed = {
  197. total: (expectedEmbedding.tokenUsage?.total || 0) + (outputEmbedding.tokenUsage?.total || 0),
  198. prompt:
  199. (expectedEmbedding.tokenUsage?.prompt || 0) + (outputEmbedding.tokenUsage?.prompt || 0),
  200. completion:
  201. (expectedEmbedding.tokenUsage?.completion || 0) +
  202. (outputEmbedding.tokenUsage?.completion || 0),
  203. };
  204. if (expectedEmbedding.error || outputEmbedding.error) {
  205. return fail(
  206. expectedEmbedding.error || outputEmbedding.error || 'Unknown error fetching embeddings',
  207. tokensUsed,
  208. );
  209. }
  210. if (!expectedEmbedding.embedding || !outputEmbedding.embedding) {
  211. return fail('Embedding not found', tokensUsed);
  212. }
  213. similarity = cosineSimilarity(expectedEmbedding.embedding, outputEmbedding.embedding);
  214. } else {
  215. throw new Error('Provider must implement callSimilarityApi or callEmbeddingApi');
  216. }
  217. const pass = inverse ? similarity <= threshold : similarity >= threshold;
  218. const greaterThanReason = `Similarity ${similarity.toFixed(
  219. 2,
  220. )} is greater than threshold ${threshold}`;
  221. const lessThanReason = `Similarity ${similarity.toFixed(2)} is less than threshold ${threshold}`;
  222. if (pass) {
  223. return {
  224. pass: true,
  225. score: inverse ? 1 - similarity : similarity,
  226. reason: inverse ? lessThanReason : greaterThanReason,
  227. tokensUsed,
  228. };
  229. }
  230. return {
  231. pass: false,
  232. score: inverse ? 1 - similarity : similarity,
  233. reason: inverse ? greaterThanReason : lessThanReason,
  234. tokensUsed,
  235. };
  236. }
  237. /**
  238. *
  239. * @param expected Expected classification. If undefined, matches any classification.
  240. * @param output Text to classify.
  241. * @param threshold Value between 0 and 1. If the expected classification is undefined, the threshold is the minimum score for any classification. If the expected classification is defined, the threshold is the minimum score for that classification.
  242. * @param grading
  243. * @returns Pass if the output matches the classification with a score greater than or equal to the threshold.
  244. */
  245. export async function matchesClassification(
  246. expected: string | undefined,
  247. output: string,
  248. threshold: number,
  249. grading?: GradingConfig,
  250. ): Promise<Omit<GradingResult, 'assertion'>> {
  251. let finalProvider = (await getAndCheckProvider(
  252. 'classification',
  253. grading?.provider,
  254. null,
  255. 'classification check',
  256. )) as ApiClassificationProvider;
  257. const resp = await finalProvider.callClassificationApi(output);
  258. if (!resp.classification) {
  259. return fail(resp.error || 'Unknown error fetching classification');
  260. }
  261. let score;
  262. if (expected === undefined) {
  263. score = Math.max(...Object.values(resp.classification));
  264. } else {
  265. score = resp.classification[expected] || 0;
  266. }
  267. if (score >= threshold) {
  268. const reason =
  269. expected === undefined
  270. ? `Maximum classification score ${score.toFixed(2)} >= ${threshold}`
  271. : `Classification ${expected} has score ${score.toFixed(2)} >= ${threshold}`;
  272. return {
  273. pass: true,
  274. score,
  275. reason,
  276. };
  277. }
  278. return {
  279. pass: false,
  280. score,
  281. reason: `Classification ${expected} has score ${score.toFixed(2)} < ${threshold}`,
  282. };
  283. }
  284. export async function matchesLlmRubric(
  285. expected: string,
  286. output: string,
  287. grading?: GradingConfig,
  288. vars?: Record<string, string | object>,
  289. ): Promise<Omit<GradingResult, 'assertion'>> {
  290. if (!grading) {
  291. throw new Error(
  292. 'Cannot grade output without grading config. Specify --grader option or grading config.',
  293. );
  294. }
  295. let rubricPrompt = grading?.rubricPrompt || DEFAULT_GRADING_PROMPT;
  296. invariant(typeof rubricPrompt === 'string', 'rubricPrompt must be a string');
  297. const prompt = nunjucks.renderString(rubricPrompt, {
  298. output: JSON.stringify(output).slice(1, -1),
  299. rubric: JSON.stringify(expected).slice(1, -1),
  300. ...fromVars(vars),
  301. });
  302. let finalProvider = await getAndCheckProvider(
  303. 'text',
  304. grading.provider,
  305. getDefaultProviders().gradingJsonProvider,
  306. 'llm-rubric check',
  307. );
  308. const resp = await finalProvider.callApi(prompt);
  309. if (resp.error || !resp.output) {
  310. return fail(resp.error || 'No output', resp.tokenUsage);
  311. }
  312. invariant(typeof resp.output === 'string', 'llm-rubric produced malformed response');
  313. try {
  314. const firstOpeningBrace = resp.output.indexOf('{');
  315. const firstClosingBrace = resp.output.indexOf('}');
  316. const jsonStr = resp.output.substring(firstOpeningBrace, firstClosingBrace + 1);
  317. const parsed = JSON.parse(jsonStr) as Partial<GradingResult>;
  318. const pass = parsed.pass ?? (typeof parsed.score === 'undefined' ? true : parsed.score > 0);
  319. return {
  320. pass,
  321. score: parsed.score ?? (pass ? 1.0 : 0.0),
  322. reason: parsed.reason || (pass ? 'Grading passed' : 'Grading failed'),
  323. tokensUsed: {
  324. total: resp.tokenUsage?.total || 0,
  325. prompt: resp.tokenUsage?.prompt || 0,
  326. completion: resp.tokenUsage?.completion || 0,
  327. },
  328. };
  329. } catch (err) {
  330. return fail(`llm-rubric produced malformed response: ${resp.output}`, resp.tokenUsage);
  331. }
  332. }
  333. export async function matchesFactuality(
  334. input: string,
  335. expected: string,
  336. output: string,
  337. grading?: GradingConfig,
  338. vars?: Record<string, string | object>,
  339. ): Promise<Omit<GradingResult, 'assertion'>> {
  340. if (!grading) {
  341. throw new Error(
  342. 'Cannot grade output without grading config. Specify --grader option or grading config.',
  343. );
  344. }
  345. const rubricPrompt = grading?.rubricPrompt || OPENAI_FACTUALITY_PROMPT;
  346. invariant(typeof rubricPrompt === 'string', 'rubricPrompt must be a string');
  347. const prompt = nunjucks.renderString(rubricPrompt, {
  348. input: JSON.stringify(input).slice(1, -1),
  349. ideal: JSON.stringify(expected).slice(1, -1),
  350. completion: JSON.stringify(output).slice(1, -1),
  351. ...fromVars(vars),
  352. });
  353. let finalProvider = await getAndCheckProvider(
  354. 'text',
  355. grading.provider,
  356. getDefaultProviders().gradingProvider,
  357. 'factuality check',
  358. );
  359. const resp = await finalProvider.callApi(prompt);
  360. if (resp.error || !resp.output) {
  361. return fail(resp.error || 'No output', resp.tokenUsage);
  362. }
  363. invariant(typeof resp.output === 'string', 'factuality produced malformed response');
  364. try {
  365. const output = resp.output;
  366. // The preferred output starts like "(A)...", but we also support leading whitespace, lowercase letters, and omitting the first parenthesis.
  367. const answerMatch = output.match(/\s*\(?([a-eA-E])\)/);
  368. if (!answerMatch) {
  369. return fail(
  370. `Factuality checker output did not match expected format: ${output}`,
  371. resp.tokenUsage,
  372. );
  373. }
  374. const option = answerMatch[1].toUpperCase();
  375. let reason = '';
  376. const scoreLookup: Record<string, number> = {
  377. A: grading.factuality?.subset ?? 1,
  378. B: grading.factuality?.superset ?? 1,
  379. C: grading.factuality?.agree ?? 1,
  380. D: grading.factuality?.disagree ?? 0,
  381. E: grading.factuality?.differButFactual ?? 1,
  382. };
  383. // Passing is defined as scores with value >0, and failing as scores with value 0.
  384. const passing = Object.keys(scoreLookup).filter((key) => scoreLookup[key] > 0);
  385. const failing = Object.keys(scoreLookup).filter((key) => scoreLookup[key] === 0);
  386. let pass = passing.includes(option) && !failing.includes(option);
  387. const optionReasons: Record<string, string> = {
  388. A: `The submitted answer is a subset of the expert answer and is fully consistent with it.`,
  389. B: `The submitted answer is a superset of the expert answer and is fully consistent with it.`,
  390. C: `The submitted answer contains all the same details as the expert answer.`,
  391. D: `There is a disagreement between the submitted answer and the expert answer.`,
  392. E: `The answers differ, but these differences don't matter from the perspective of factuality.`,
  393. };
  394. if (optionReasons[option]) {
  395. reason = optionReasons[option];
  396. } else {
  397. pass = false;
  398. reason = `Invalid option: ${option}. Full response from factuality checker: ${resp.output}`;
  399. }
  400. let score = pass ? 1 : 0;
  401. if (typeof scoreLookup[option] !== 'undefined') {
  402. score = scoreLookup[option];
  403. }
  404. return {
  405. pass,
  406. score,
  407. reason,
  408. tokensUsed: {
  409. total: resp.tokenUsage?.total || 0,
  410. prompt: resp.tokenUsage?.prompt || 0,
  411. completion: resp.tokenUsage?.completion || 0,
  412. },
  413. };
  414. } catch (err) {
  415. return fail(`Error parsing output: ${(err as Error).message}`, resp.tokenUsage);
  416. }
  417. }
  418. export async function matchesClosedQa(
  419. input: string,
  420. expected: string,
  421. output: string,
  422. grading?: GradingConfig,
  423. vars?: Record<string, string | object>,
  424. ): Promise<Omit<GradingResult, 'assertion'>> {
  425. if (!grading) {
  426. throw new Error(
  427. 'Cannot grade output without grading config. Specify --grader option or grading config.',
  428. );
  429. }
  430. const rubricPrompt = grading?.rubricPrompt || OPENAI_CLOSED_QA_PROMPT;
  431. invariant(typeof rubricPrompt === 'string', 'rubricPrompt must be a string');
  432. const prompt = nunjucks.renderString(rubricPrompt, {
  433. input: JSON.stringify(input).slice(1, -1),
  434. criteria: JSON.stringify(expected).slice(1, -1),
  435. completion: JSON.stringify(output).slice(1, -1),
  436. ...fromVars(vars),
  437. });
  438. let finalProvider = await getAndCheckProvider(
  439. 'text',
  440. grading.provider,
  441. getDefaultProviders().gradingProvider,
  442. 'model-graded-closedqa check',
  443. );
  444. const resp = await finalProvider.callApi(prompt);
  445. if (resp.error || !resp.output) {
  446. return fail(resp.error || 'No output', resp.tokenUsage);
  447. }
  448. invariant(typeof resp.output === 'string', 'model-graded-closedqa produced malformed response');
  449. try {
  450. const pass = resp.output.endsWith('Y');
  451. let reason;
  452. if (pass) {
  453. reason = 'The submission meets the criterion';
  454. } else if (resp.output.endsWith('N')) {
  455. reason = `The submission does not meet the criterion:\n${resp.output}`;
  456. } else {
  457. reason = `Model grader produced a malformed response:\n${resp.output}`;
  458. }
  459. return {
  460. pass,
  461. score: pass ? 1 : 0,
  462. reason,
  463. tokensUsed: {
  464. total: resp.tokenUsage?.total || 0,
  465. prompt: resp.tokenUsage?.prompt || 0,
  466. completion: resp.tokenUsage?.completion || 0,
  467. },
  468. };
  469. } catch (err) {
  470. return fail(`Error parsing output: ${(err as Error).message}`, resp.tokenUsage);
  471. }
  472. }
  473. export async function matchesAnswerRelevance(
  474. input: string,
  475. output: string,
  476. threshold: number,
  477. grading?: GradingConfig,
  478. ): Promise<Omit<GradingResult, 'assertion'>> {
  479. let embeddingProvider = await getAndCheckProvider(
  480. 'embedding',
  481. grading?.provider,
  482. getDefaultProviders().embeddingProvider,
  483. 'answer relevancy check',
  484. );
  485. let textProvider = await getAndCheckProvider(
  486. 'text',
  487. grading?.provider,
  488. getDefaultProviders().gradingProvider,
  489. 'answer relevancy check',
  490. );
  491. const tokensUsed = {
  492. total: 0,
  493. prompt: 0,
  494. completion: 0,
  495. };
  496. const candidateQuestions: string[] = [];
  497. for (let i = 0; i < 3; i++) {
  498. // TODO(ian): Parallelize
  499. const rubricPrompt = grading?.rubricPrompt || ANSWER_RELEVANCY_GENERATE;
  500. invariant(typeof rubricPrompt === 'string', 'rubricPrompt must be a string');
  501. const promptText = nunjucks.renderString(rubricPrompt, {
  502. answer: JSON.stringify(output).slice(1, -1),
  503. });
  504. const resp = await textProvider.callApi(promptText);
  505. if (resp.error || !resp.output) {
  506. tokensUsed.total += resp.tokenUsage?.total || 0;
  507. tokensUsed.prompt += resp.tokenUsage?.prompt || 0;
  508. tokensUsed.completion += resp.tokenUsage?.completion || 0;
  509. return fail(resp.error || 'No output', tokensUsed);
  510. }
  511. invariant(
  512. typeof resp.output === 'string',
  513. 'answer relevancy check produced malformed response',
  514. );
  515. candidateQuestions.push(resp.output);
  516. }
  517. invariant(
  518. typeof embeddingProvider.callEmbeddingApi === 'function',
  519. `Provider ${embeddingProvider.id} must implement callEmbeddingApi for similarity check`,
  520. );
  521. const inputEmbeddingResp = await embeddingProvider.callEmbeddingApi(input);
  522. if (inputEmbeddingResp.error || !inputEmbeddingResp.embedding) {
  523. tokensUsed.total += inputEmbeddingResp.tokenUsage?.total || 0;
  524. tokensUsed.prompt += inputEmbeddingResp.tokenUsage?.prompt || 0;
  525. tokensUsed.completion += inputEmbeddingResp.tokenUsage?.completion || 0;
  526. return fail(inputEmbeddingResp.error || 'No embedding', tokensUsed);
  527. }
  528. const inputEmbedding = inputEmbeddingResp.embedding;
  529. const similarities: number[] = [];
  530. for (const question of candidateQuestions) {
  531. const resp = await embeddingProvider.callEmbeddingApi(question);
  532. tokensUsed.total += resp.tokenUsage?.total || 0;
  533. tokensUsed.prompt += resp.tokenUsage?.prompt || 0;
  534. tokensUsed.completion += resp.tokenUsage?.completion || 0;
  535. if (resp.error || !resp.embedding) {
  536. return fail(resp.error || 'No embedding', tokensUsed);
  537. }
  538. similarities.push(cosineSimilarity(inputEmbedding, resp.embedding));
  539. }
  540. const similarity = similarities.reduce((a, b) => a + b, 0) / similarities.length;
  541. const pass = similarity >= threshold;
  542. const greaterThanReason = `Relevance ${similarity.toFixed(
  543. 2,
  544. )} is greater than threshold ${threshold}`;
  545. const lessThanReason = `Relevance ${similarity.toFixed(2)} is less than threshold ${threshold}`;
  546. if (pass) {
  547. return {
  548. pass: true,
  549. score: similarity,
  550. reason: greaterThanReason,
  551. tokensUsed,
  552. };
  553. }
  554. return {
  555. pass: false,
  556. score: similarity,
  557. reason: lessThanReason,
  558. tokensUsed,
  559. };
  560. }
  561. export async function matchesContextRecall(
  562. context: string,
  563. groundTruth: string,
  564. threshold: number,
  565. grading?: GradingConfig,
  566. vars?: Record<string, string | object>,
  567. ): Promise<Omit<GradingResult, 'assertion'>> {
  568. let textProvider = await getAndCheckProvider(
  569. 'text',
  570. grading?.provider,
  571. getDefaultProviders().gradingProvider,
  572. 'context recall check',
  573. );
  574. const rubricPrompt = grading?.rubricPrompt || CONTEXT_RECALL;
  575. invariant(typeof rubricPrompt === 'string', 'rubricPrompt must be a string');
  576. const promptText = nunjucks.renderString(rubricPrompt, {
  577. context: JSON.stringify(context).slice(1, -1),
  578. groundTruth: JSON.stringify(groundTruth).slice(1, -1),
  579. ...fromVars(vars),
  580. });
  581. const resp = await textProvider.callApi(promptText);
  582. if (resp.error || !resp.output) {
  583. return fail(resp.error || 'No output', resp.tokenUsage);
  584. }
  585. invariant(typeof resp.output === 'string', 'context-recall produced malformed response');
  586. const sentences = resp.output.split('\n');
  587. const numerator = sentences.reduce(
  588. (acc, sentence) => acc + (sentence.includes(CONTEXT_RECALL_ATTRIBUTED_TOKEN) ? 1 : 0),
  589. 0,
  590. );
  591. const score = numerator / sentences.length;
  592. const pass = score >= threshold;
  593. return {
  594. pass,
  595. score,
  596. reason: pass
  597. ? `Recall ${score.toFixed(2)} is >= ${threshold}`
  598. : `Recall ${score.toFixed(2)} is < ${threshold}`,
  599. tokensUsed: {
  600. total: resp.tokenUsage?.total || 0,
  601. prompt: resp.tokenUsage?.prompt || 0,
  602. completion: resp.tokenUsage?.completion || 0,
  603. },
  604. };
  605. }
  606. export async function matchesContextRelevance(
  607. question: string,
  608. context: string,
  609. threshold: number,
  610. grading?: GradingConfig,
  611. ): Promise<Omit<GradingResult, 'assertion'>> {
  612. let textProvider = await getAndCheckProvider(
  613. 'text',
  614. grading?.provider,
  615. getDefaultProviders().gradingProvider,
  616. 'context relevance check',
  617. );
  618. const rubricPrompt = grading?.rubricPrompt || CONTEXT_RELEVANCE;
  619. invariant(typeof rubricPrompt === 'string', 'rubricPrompt must be a string');
  620. const promptText = nunjucks.renderString(rubricPrompt, {
  621. context: JSON.stringify(context).slice(1, -1),
  622. query: JSON.stringify(question).slice(1, -1),
  623. });
  624. const resp = await textProvider.callApi(promptText);
  625. if (resp.error || !resp.output) {
  626. return fail(resp.error || 'No output', resp.tokenUsage);
  627. }
  628. invariant(typeof resp.output === 'string', 'context-relevance produced malformed response');
  629. const sentences = resp.output.split('\n');
  630. const numerator = sentences.reduce(
  631. (acc, sentence) => acc + (sentence.includes(CONTEXT_RELEVANCE_BAD) ? 0 : 1),
  632. 0,
  633. );
  634. const score = numerator / sentences.length;
  635. const pass = score >= threshold;
  636. return {
  637. pass,
  638. score,
  639. reason: pass
  640. ? `Relevance ${score.toFixed(2)} is >= ${threshold}`
  641. : `Relevance ${score.toFixed(2)} is < ${threshold}`,
  642. tokensUsed: {
  643. total: resp.tokenUsage?.total || 0,
  644. prompt: resp.tokenUsage?.prompt || 0,
  645. completion: resp.tokenUsage?.completion || 0,
  646. },
  647. };
  648. }
  649. export async function matchesContextFaithfulness(
  650. query: string,
  651. output: string,
  652. context: string,
  653. threshold: number,
  654. grading?: GradingConfig,
  655. vars?: Record<string, string | object>,
  656. ): Promise<Omit<GradingResult, 'assertion'>> {
  657. let textProvider = await getAndCheckProvider(
  658. 'text',
  659. grading?.provider,
  660. getDefaultProviders().gradingProvider,
  661. 'faithfulness check',
  662. );
  663. if (grading?.rubricPrompt) {
  664. invariant(Array.isArray(grading.rubricPrompt), 'rubricPrompt must be an array');
  665. }
  666. const longformPrompt = grading?.rubricPrompt?.[0] || CONTEXT_FAITHFULNESS_LONGFORM;
  667. const nliPrompt = grading?.rubricPrompt?.[1] || CONTEXT_FAITHFULNESS_NLI_STATEMENTS;
  668. let promptText = nunjucks.renderString(longformPrompt, {
  669. question: JSON.stringify(query).slice(1, -1),
  670. answer: JSON.stringify(output).slice(1, -1),
  671. ...fromVars(vars),
  672. });
  673. let resp = await textProvider.callApi(promptText);
  674. if (resp.error || !resp.output) {
  675. return fail(resp.error || 'No output', resp.tokenUsage);
  676. }
  677. invariant(typeof resp.output === 'string', 'context-faithfulness produced malformed response');
  678. let statements = resp.output.split('\n');
  679. promptText = nunjucks.renderString(nliPrompt, {
  680. context: JSON.stringify(context).slice(1, -1),
  681. statements: JSON.stringify(statements.join('\n')).slice(1, -1),
  682. ...fromVars(vars),
  683. });
  684. resp = await textProvider.callApi(promptText);
  685. if (resp.error || !resp.output) {
  686. return fail(resp.error || 'No output', resp.tokenUsage);
  687. }
  688. invariant(typeof resp.output === 'string', 'context-faithfulness produced malformed response');
  689. let finalAnswer = 'Final verdict for each statement in order:';
  690. finalAnswer = finalAnswer.toLowerCase();
  691. let verdicts = resp.output.toLowerCase().trim();
  692. let score: number;
  693. if (verdicts.includes(finalAnswer)) {
  694. verdicts = verdicts.slice(verdicts.indexOf(finalAnswer) + finalAnswer.length);
  695. score =
  696. verdicts.split('.').filter((answer) => answer.trim() !== '' && !answer.includes('yes'))
  697. .length / statements.length;
  698. } else {
  699. score = (verdicts.split('verdict: no').length - 1) / statements.length;
  700. }
  701. score = 1 - score;
  702. let pass = score >= threshold;
  703. return {
  704. pass,
  705. score,
  706. reason: pass
  707. ? `Faithfulness ${score.toFixed(2)} is >= ${threshold}`
  708. : `Faithfulness ${score.toFixed(2)} is < ${threshold}`,
  709. tokensUsed: {
  710. total: resp.tokenUsage?.total || 0,
  711. prompt: resp.tokenUsage?.prompt || 0,
  712. completion: resp.tokenUsage?.completion || 0,
  713. },
  714. };
  715. }
  716. export async function matchesSelectBest(
  717. criteria: string,
  718. outputs: string[],
  719. grading?: GradingConfig,
  720. vars?: Record<string, string | object>,
  721. ): Promise<Omit<GradingResult, 'assertion'>[]> {
  722. invariant(
  723. outputs.length >= 2,
  724. 'select-best assertion must have at least two outputs to compare between',
  725. );
  726. let textProvider = await getAndCheckProvider(
  727. 'text',
  728. grading?.provider,
  729. getDefaultProviders().gradingProvider,
  730. 'select-best check',
  731. );
  732. const rubricPrompt = grading?.rubricPrompt || SELECT_BEST_PROMPT;
  733. invariant(typeof rubricPrompt === 'string', 'rubricPrompt must be a string');
  734. let promptText = nunjucks.renderString(rubricPrompt, {
  735. criteria: JSON.stringify(criteria).slice(1, -1),
  736. outputs: outputs.map((output) => JSON.stringify(output).slice(1, -1)),
  737. ...fromVars(vars),
  738. });
  739. let resp = await textProvider.callApi(promptText);
  740. if (resp.error || !resp.output) {
  741. return new Array(outputs.length).fill(fail(resp.error || 'No output', resp.tokenUsage));
  742. }
  743. invariant(typeof resp.output === 'string', 'select-best produced malformed response');
  744. const firstDigitMatch = resp.output.trim().match(/\d/);
  745. const verdict = firstDigitMatch ? parseInt(firstDigitMatch[0], 10) : NaN;
  746. if (isNaN(verdict) || verdict < 0 || verdict >= outputs.length) {
  747. return new Array(outputs.length).fill(fail(`Invalid select-best verdict: ${verdict}`));
  748. }
  749. const tokensUsed = {
  750. total: resp.tokenUsage?.total || 0,
  751. prompt: resp.tokenUsage?.prompt || 0,
  752. completion: resp.tokenUsage?.completion || 0,
  753. };
  754. return outputs.map((output, index) => {
  755. if (index === verdict) {
  756. return {
  757. pass: true,
  758. score: 1,
  759. reason: `Output selected as the best: ${criteria}`,
  760. tokensUsed,
  761. };
  762. } else {
  763. return {
  764. pass: false,
  765. score: 0,
  766. reason: `Output not selected: ${criteria}`,
  767. tokensUsed,
  768. };
  769. }
  770. });
  771. }
  772. interface ModerationMatchOptions {
  773. userPrompt: string;
  774. assistantResponse: string;
  775. categories?: string[];
  776. }
  777. export async function matchesModeration(
  778. { userPrompt, assistantResponse, categories = [] }: ModerationMatchOptions,
  779. grading?: GradingConfig,
  780. ) {
  781. const moderationProvider = (await getAndCheckProvider(
  782. 'moderation',
  783. grading?.provider,
  784. getDefaultProviders().moderationProvider,
  785. 'moderation check',
  786. )) as ApiModerationProvider;
  787. invariant(moderationProvider, 'Moderation provider must be defined');
  788. const resp = await moderationProvider.callModerationApi(userPrompt, assistantResponse);
  789. if (resp.error) {
  790. return {
  791. pass: false,
  792. score: 0,
  793. reason: `Moderation API error: ${resp.error}`,
  794. };
  795. }
  796. const { flags } = resp;
  797. if (!flags || flags.length === 0) {
  798. return {
  799. pass: true,
  800. score: 1,
  801. reason: 'No moderation flags detected',
  802. };
  803. }
  804. const filteredFlags =
  805. categories.length === 0 ? flags : flags.filter((flag) => categories.includes(flag.code));
  806. if (filteredFlags.length > 0) {
  807. return {
  808. pass: false,
  809. score: 0,
  810. reason: `Moderation flags detected: ${filteredFlags
  811. .map((flag) => flag.description)
  812. .join(', ')}`,
  813. };
  814. }
  815. return {
  816. pass: true,
  817. score: 1,
  818. reason: 'No relevant moderation flags detected',
  819. };
  820. }
Tip!

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

Comments

Loading...