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

runAssertions.test.ts 13 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
  1. import { runAssertions } from '../../src/assertions';
  2. import { OpenAiChatCompletionProvider } from '../../src/providers/openai/chat';
  3. import { DefaultGradingJsonProvider } from '../../src/providers/openai/defaults';
  4. import { ReplicateModerationProvider } from '../../src/providers/replicate';
  5. import { TestGrader } from '../util/utils';
  6. import type { ApiProvider, AtomicTestCase, GradingResult, ProviderResponse } from '../../src/types';
  7. jest.mock('../../src/redteam/remoteGeneration', () => ({
  8. shouldGenerateRemote: jest.fn().mockReturnValue(false),
  9. }));
  10. jest.mock('proxy-agent', () => ({
  11. ProxyAgent: jest.fn().mockImplementation(() => ({})),
  12. }));
  13. jest.mock('node:module', () => {
  14. const mockRequire: NodeJS.Require = {
  15. resolve: jest.fn() as unknown as NodeJS.RequireResolve,
  16. } as unknown as NodeJS.Require;
  17. return {
  18. createRequire: jest.fn().mockReturnValue(mockRequire),
  19. };
  20. });
  21. jest.mock('../../src/fetch', () => {
  22. const actual = jest.requireActual('../../src/fetch');
  23. return {
  24. ...actual,
  25. fetchWithRetries: jest.fn(actual.fetchWithRetries),
  26. };
  27. });
  28. jest.mock('glob', () => ({
  29. globSync: jest.fn(),
  30. }));
  31. jest.mock('fs', () => ({
  32. readFileSync: jest.fn(),
  33. promises: {
  34. readFile: jest.fn(),
  35. },
  36. }));
  37. jest.mock('../../src/esm');
  38. jest.mock('../../src/database', () => ({
  39. getDb: jest.fn(),
  40. }));
  41. jest.mock('path', () => ({
  42. ...jest.requireActual('path'),
  43. resolve: jest.fn(jest.requireActual('path').resolve),
  44. extname: jest.fn(jest.requireActual('path').extname),
  45. }));
  46. jest.mock('../../src/cliState', () => ({
  47. basePath: '/base/path',
  48. }));
  49. jest.mock('../../src/matchers', () => {
  50. const actual = jest.requireActual('../../src/matchers');
  51. return {
  52. ...actual,
  53. matchesContextRelevance: jest
  54. .fn()
  55. .mockResolvedValue({ pass: true, score: 1, reason: 'Mocked reason' }),
  56. matchesContextFaithfulness: jest
  57. .fn()
  58. .mockResolvedValue({ pass: true, score: 1, reason: 'Mocked reason' }),
  59. };
  60. });
  61. const _Grader = new TestGrader();
  62. describe('runAssertions', () => {
  63. const test: AtomicTestCase = {
  64. assert: [
  65. {
  66. type: 'equals',
  67. value: 'Expected output',
  68. },
  69. ],
  70. };
  71. beforeEach(() => {
  72. jest.resetModules();
  73. });
  74. afterEach(() => {
  75. jest.clearAllMocks();
  76. });
  77. it('should pass when all assertions pass', async () => {
  78. const output = 'Expected output';
  79. const result: GradingResult = await runAssertions({
  80. prompt: 'Some prompt',
  81. provider: new OpenAiChatCompletionProvider('gpt-4o-mini'),
  82. test,
  83. providerResponse: { output },
  84. });
  85. expect(result).toMatchObject({
  86. pass: true,
  87. reason: 'All assertions passed',
  88. });
  89. });
  90. it('should fail when any assertion fails', async () => {
  91. const output = 'Actual output';
  92. const result: GradingResult = await runAssertions({
  93. prompt: 'Some prompt',
  94. provider: new OpenAiChatCompletionProvider('gpt-4o-mini'),
  95. test,
  96. providerResponse: { output },
  97. });
  98. expect(result).toMatchObject({
  99. pass: false,
  100. reason: 'Expected output "Actual output" to equal "Expected output"',
  101. });
  102. });
  103. it('should handle output as an object', async () => {
  104. const output = { key: 'value' };
  105. const result: GradingResult = await runAssertions({
  106. prompt: 'Some prompt',
  107. provider: new OpenAiChatCompletionProvider('gpt-4o-mini'),
  108. test,
  109. providerResponse: { output },
  110. });
  111. expect(result).toMatchObject({
  112. pass: false,
  113. reason: 'Expected output "{"key":"value"}" to equal "Expected output"',
  114. });
  115. });
  116. it('should fail when combined score is less than threshold', async () => {
  117. const result: GradingResult = await runAssertions({
  118. prompt: 'Some prompt',
  119. provider: new OpenAiChatCompletionProvider('gpt-4o-mini'),
  120. test: {
  121. threshold: 0.5,
  122. assert: [
  123. {
  124. type: 'equals',
  125. value: 'Hello world',
  126. weight: 2,
  127. },
  128. {
  129. type: 'contains',
  130. value: 'world',
  131. weight: 1,
  132. },
  133. ],
  134. },
  135. providerResponse: { output: 'Hi there world' },
  136. });
  137. expect(result).toMatchObject({
  138. pass: false,
  139. reason: 'Aggregate score 0.33 < 0.5 threshold',
  140. });
  141. });
  142. it('should pass when combined score is greater than threshold', async () => {
  143. const result: GradingResult = await runAssertions({
  144. prompt: 'Some prompt',
  145. provider: new OpenAiChatCompletionProvider('gpt-4o-mini'),
  146. test: {
  147. threshold: 0.25,
  148. assert: [
  149. {
  150. type: 'equals',
  151. value: 'Hello world',
  152. weight: 2,
  153. },
  154. {
  155. type: 'contains',
  156. value: 'world',
  157. weight: 1,
  158. },
  159. ],
  160. },
  161. providerResponse: { output: 'Hi there world' },
  162. });
  163. expect(result).toMatchObject({
  164. pass: true,
  165. reason: 'Aggregate score 0.33 ≥ 0.25 threshold',
  166. });
  167. });
  168. describe('assert-set', () => {
  169. const prompt = 'Some prompt';
  170. const provider = new OpenAiChatCompletionProvider('gpt-4o-mini');
  171. it('assert-set success', async () => {
  172. const output = 'Expected output';
  173. const test: AtomicTestCase = {
  174. assert: [
  175. {
  176. type: 'assert-set',
  177. assert: [
  178. {
  179. type: 'equals',
  180. value: output,
  181. },
  182. ],
  183. },
  184. ],
  185. };
  186. const result: GradingResult = await runAssertions({
  187. prompt,
  188. provider,
  189. test,
  190. providerResponse: { output },
  191. });
  192. expect(result).toMatchObject({
  193. pass: true,
  194. reason: 'All assertions passed',
  195. });
  196. });
  197. it('assert-set failure', async () => {
  198. const output = 'Actual output';
  199. const test: AtomicTestCase = {
  200. assert: [
  201. {
  202. type: 'assert-set',
  203. assert: [
  204. {
  205. type: 'equals',
  206. value: 'Expected output',
  207. },
  208. ],
  209. },
  210. ],
  211. };
  212. const result: GradingResult = await runAssertions({
  213. prompt,
  214. provider,
  215. test,
  216. providerResponse: { output },
  217. });
  218. expect(result).toMatchObject({
  219. pass: false,
  220. reason: 'Expected output "Actual output" to equal "Expected output"',
  221. });
  222. });
  223. it('assert-set threshold success', async () => {
  224. const output = 'Expected output';
  225. const test: AtomicTestCase = {
  226. assert: [
  227. {
  228. type: 'assert-set',
  229. threshold: 0.25,
  230. assert: [
  231. {
  232. type: 'equals',
  233. value: 'Hello world',
  234. weight: 2,
  235. },
  236. {
  237. type: 'contains',
  238. value: 'Expected',
  239. weight: 1,
  240. },
  241. ],
  242. },
  243. ],
  244. };
  245. const result: GradingResult = await runAssertions({
  246. prompt,
  247. provider,
  248. test,
  249. providerResponse: { output },
  250. });
  251. expect(result).toMatchObject({
  252. pass: true,
  253. reason: 'All assertions passed',
  254. });
  255. });
  256. it('assert-set threshold failure', async () => {
  257. const output = 'Expected output';
  258. const test: AtomicTestCase = {
  259. assert: [
  260. {
  261. type: 'assert-set',
  262. threshold: 0.5,
  263. assert: [
  264. {
  265. type: 'equals',
  266. value: 'Hello world',
  267. weight: 2,
  268. },
  269. {
  270. type: 'contains',
  271. value: 'Expected',
  272. weight: 1,
  273. },
  274. ],
  275. },
  276. ],
  277. };
  278. const result: GradingResult = await runAssertions({
  279. prompt,
  280. provider,
  281. test,
  282. providerResponse: { output },
  283. });
  284. expect(result).toMatchObject({
  285. pass: false,
  286. reason: 'Aggregate score 0.33 < 0.5 threshold',
  287. });
  288. });
  289. it('assert-set with metric', async () => {
  290. const metric = 'The best metric';
  291. const output = 'Expected output';
  292. const test: AtomicTestCase = {
  293. assert: [
  294. {
  295. type: 'assert-set',
  296. metric,
  297. threshold: 0.5,
  298. assert: [
  299. {
  300. type: 'equals',
  301. value: 'Hello world',
  302. },
  303. {
  304. type: 'contains',
  305. value: 'Expected',
  306. },
  307. ],
  308. },
  309. ],
  310. };
  311. const result: GradingResult = await runAssertions({
  312. prompt,
  313. provider,
  314. test,
  315. providerResponse: { output },
  316. });
  317. expect(result.namedScores).toStrictEqual({
  318. [metric]: 0.5,
  319. });
  320. });
  321. it('uses assert-set weight', async () => {
  322. const output = 'Expected';
  323. const test: AtomicTestCase = {
  324. assert: [
  325. {
  326. type: 'equals',
  327. value: 'Nope',
  328. weight: 10,
  329. },
  330. {
  331. type: 'assert-set',
  332. weight: 90,
  333. assert: [
  334. {
  335. type: 'equals',
  336. value: 'Expected',
  337. },
  338. ],
  339. },
  340. ],
  341. };
  342. const result: GradingResult = await runAssertions({
  343. prompt,
  344. provider,
  345. test,
  346. providerResponse: { output },
  347. });
  348. expect(result.score).toBe(0.9);
  349. });
  350. });
  351. it('preserves default provider', async () => {
  352. const provider = new OpenAiChatCompletionProvider('gpt-4o-mini');
  353. const output = 'Expected output';
  354. const test: AtomicTestCase = {
  355. assert: [
  356. {
  357. type: 'moderation',
  358. provider: 'replicate:moderation:foo/bar',
  359. },
  360. {
  361. type: 'llm-rubric',
  362. value: 'insert rubric here',
  363. },
  364. ],
  365. };
  366. const callApiSpy = jest.spyOn(DefaultGradingJsonProvider, 'callApi').mockResolvedValue({
  367. output: JSON.stringify({ pass: true, score: 1.0, reason: 'I love you' }),
  368. });
  369. const callModerationApiSpy = jest
  370. .spyOn(ReplicateModerationProvider.prototype, 'callModerationApi')
  371. .mockResolvedValue({ flags: [] });
  372. const result: GradingResult = await runAssertions({
  373. prompt: 'foobar',
  374. provider,
  375. test,
  376. providerResponse: { output },
  377. });
  378. expect(result.pass).toBeTruthy();
  379. expect(callApiSpy).toHaveBeenCalledTimes(1);
  380. expect(callModerationApiSpy).toHaveBeenCalledTimes(1);
  381. });
  382. it('should use stored grader result from crescendo strategy', async () => {
  383. const storedResult = {
  384. pass: false,
  385. score: 0,
  386. reason: 'Detected jailbreak via crescendo strategy',
  387. metadata: { confidence: 0.95 },
  388. };
  389. const test: AtomicTestCase = {
  390. assert: [
  391. {
  392. type: 'promptfoo:redteam:medical:prioritization-error' as const,
  393. value: 'test assertion',
  394. },
  395. ],
  396. metadata: {
  397. pluginId: 'medical:prioritization-error',
  398. strategyId: 'crescendo',
  399. },
  400. };
  401. const providerResponse: ProviderResponse = {
  402. output: 'Some target response',
  403. metadata: {
  404. storedGraderResult: storedResult,
  405. },
  406. };
  407. const result = await runAssertions({
  408. prompt: 'test prompt',
  409. provider: {} as ApiProvider,
  410. test,
  411. providerResponse,
  412. });
  413. // Should use stored result instead of calling grader
  414. expect(result.pass).toBe(false);
  415. expect(result.score).toBe(0);
  416. expect(result.reason).toBe('Detected jailbreak via crescendo strategy');
  417. // Check that component results contain the stored grader result
  418. expect(result.componentResults).toHaveLength(1);
  419. expect(result.componentResults![0].pass).toBe(false);
  420. expect(result.componentResults![0].score).toBe(0);
  421. expect(result.componentResults![0].reason).toBe('Detected jailbreak via crescendo strategy');
  422. expect(result.componentResults![0].metadata?.confidence).toBe(0.95);
  423. });
  424. it('should construct proper return shape for stored grader result', async () => {
  425. const storedResult = {
  426. pass: false,
  427. score: 0,
  428. reason: 'Internal evaluator detected successful attack',
  429. };
  430. const assertion = {
  431. type: 'promptfoo:redteam:medical:prioritization-error' as const,
  432. value: 'test assertion',
  433. };
  434. const test: AtomicTestCase = {
  435. assert: [assertion],
  436. metadata: {
  437. pluginId: 'medical:prioritization-error',
  438. strategyId: 'crescendo',
  439. },
  440. };
  441. const providerResponse: ProviderResponse = {
  442. output: 'Some target response',
  443. metadata: {
  444. storedGraderResult: storedResult,
  445. },
  446. };
  447. const result = await runAssertions({
  448. prompt: 'test prompt',
  449. provider: {} as ApiProvider,
  450. test,
  451. providerResponse,
  452. });
  453. // Should have proper assertion structure in component results
  454. expect(result.componentResults).toHaveLength(1);
  455. expect(result.componentResults![0].assertion).toEqual({
  456. ...assertion,
  457. value: assertion.value,
  458. });
  459. // Should include test metadata in component results
  460. expect(result.componentResults![0].metadata).toEqual(
  461. expect.objectContaining({
  462. pluginId: 'medical:prioritization-error',
  463. strategyId: 'crescendo',
  464. }),
  465. );
  466. });
  467. });
Tip!

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

Comments

Loading...