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

evaluator.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
  1. import readline from 'readline';
  2. import * as fs from 'fs';
  3. import * as path from 'path';
  4. import async from 'async';
  5. import chalk from 'chalk';
  6. import invariant from 'tiny-invariant';
  7. import yaml from 'js-yaml';
  8. import { globSync } from 'glob';
  9. import cliState from './cliState';
  10. import logger from './logger';
  11. import telemetry from './telemetry';
  12. import { runAssertions, runCompareAssertion } from './assertions';
  13. import { generatePrompts } from './suggestions';
  14. import { getNunjucksEngine, transformOutput, sha256, renderVarsInObject } from './util';
  15. import { maybeEmitAzureOpenAiWarning } from './providers/azureopenaiUtil';
  16. import { runPython } from './python/wrapper';
  17. import { importModule } from './esm';
  18. import { fetchWithCache, getCache } from './cache';
  19. import type { MultiBar, SingleBar } from 'cli-progress';
  20. import type {
  21. ApiProvider,
  22. CompletedPrompt,
  23. EvaluateOptions,
  24. EvaluateResult,
  25. EvaluateStats,
  26. EvaluateSummary,
  27. EvaluateTable,
  28. NunjucksFilterMap,
  29. Prompt,
  30. RunEvalOptions,
  31. TestSuite,
  32. ProviderResponse,
  33. Assertion,
  34. } from './types';
  35. export const DEFAULT_MAX_CONCURRENCY = 4;
  36. export function generateVarCombinations(
  37. vars: Record<string, string | string[] | any>,
  38. ): Record<string, string | any[]>[] {
  39. const keys = Object.keys(vars);
  40. const combinations: Record<string, string | any[]>[] = [{}];
  41. for (const key of keys) {
  42. let values: any[] = [];
  43. if (typeof vars[key] === 'string' && vars[key].startsWith('file://')) {
  44. const filePath = vars[key].slice('file://'.length);
  45. const resolvedPath = path.resolve(cliState.basePath || '', filePath);
  46. const filePaths = globSync(resolvedPath.replace(/\\/g, '/'));
  47. values = filePaths.map((path: string) => `file://${path}`);
  48. if (values.length === 0) {
  49. throw new Error(`No files found for variable ${key} at path ${resolvedPath}`);
  50. }
  51. } else {
  52. values = Array.isArray(vars[key]) ? vars[key] : [vars[key]];
  53. }
  54. // Check if it's an array but not a string array
  55. if (Array.isArray(vars[key]) && typeof vars[key][0] !== 'string') {
  56. values = [vars[key]];
  57. }
  58. const newCombinations: Record<string, any>[] = [];
  59. for (const combination of combinations) {
  60. for (const value of values) {
  61. newCombinations.push({ ...combination, [key]: value });
  62. }
  63. }
  64. combinations.length = 0;
  65. combinations.push(...newCombinations);
  66. }
  67. return combinations;
  68. }
  69. export function resolveVariables(
  70. variables: Record<string, string | object>,
  71. ): Record<string, string | object> {
  72. let resolved = true;
  73. const regex = /\{\{\s*(\w+)\s*\}\}/; // Matches {{variableName}}, {{ variableName }}, etc.
  74. let iterations = 0;
  75. do {
  76. resolved = true;
  77. for (const key of Object.keys(variables)) {
  78. if (typeof variables[key] !== 'string') {
  79. continue;
  80. }
  81. const value = variables[key] as string;
  82. const match = regex.exec(value);
  83. if (match) {
  84. const [placeholder, varName] = match;
  85. if (variables[varName] !== undefined) {
  86. variables[key] = value.replace(placeholder, variables[varName] as string);
  87. resolved = false; // Indicate that we've made a replacement and should check again
  88. } else {
  89. // Do nothing - final nunjucks render will fail if necessary.
  90. // logger.warn(`Variable "${varName}" not found for substitution.`);
  91. }
  92. }
  93. }
  94. iterations++;
  95. } while (!resolved && iterations < 5);
  96. return variables;
  97. }
  98. export async function renderPrompt(
  99. prompt: Prompt,
  100. vars: Record<string, string | object>,
  101. nunjucksFilters?: NunjucksFilterMap,
  102. provider?: ApiProvider,
  103. ): Promise<string> {
  104. const nunjucks = getNunjucksEngine(nunjucksFilters);
  105. let basePrompt = prompt.raw;
  106. // Load files
  107. for (const [varName, value] of Object.entries(vars)) {
  108. if (typeof value === 'string' && value.startsWith('file://')) {
  109. const basePath = cliState.basePath || '';
  110. const filePath = path.resolve(process.cwd(), basePath, value.slice('file://'.length));
  111. const fileExtension = filePath.split('.').pop();
  112. logger.debug(`Loading var ${varName} from file: ${filePath}`);
  113. switch (fileExtension) {
  114. case 'js':
  115. const javascriptOutput = (await (
  116. await importModule(filePath)
  117. )(varName, basePrompt, vars, provider)) as {
  118. output?: string;
  119. error?: string;
  120. };
  121. if (javascriptOutput.error) {
  122. throw new Error(`Error running ${filePath}: ${javascriptOutput.error}`);
  123. }
  124. if (!javascriptOutput.output) {
  125. throw new Error(
  126. `Expected ${filePath} to return { output: string } but got ${javascriptOutput}`,
  127. );
  128. }
  129. vars[varName] = javascriptOutput.output;
  130. break;
  131. case 'py':
  132. const pythonScriptOutput = (await runPython(filePath, 'get_var', [
  133. varName,
  134. basePrompt,
  135. vars,
  136. ])) as { output?: string; error?: string };
  137. if (pythonScriptOutput.error) {
  138. throw new Error(`Error running Python script ${filePath}: ${pythonScriptOutput.error}`);
  139. }
  140. if (!pythonScriptOutput.output) {
  141. throw new Error(`Python script ${filePath} did not return any output`);
  142. }
  143. vars[varName] = pythonScriptOutput.output.trim();
  144. break;
  145. case 'yaml':
  146. case 'yml':
  147. vars[varName] = JSON.stringify(
  148. yaml.load(fs.readFileSync(filePath, 'utf8')) as string | object,
  149. );
  150. break;
  151. case 'json':
  152. default:
  153. vars[varName] = fs.readFileSync(filePath, 'utf8').trim();
  154. break;
  155. }
  156. }
  157. }
  158. // Apply prompt functions
  159. if (prompt.function) {
  160. const result = await prompt.function({ vars, provider });
  161. if (typeof result === 'string') {
  162. basePrompt = result;
  163. } else if (typeof result === 'object') {
  164. basePrompt = JSON.stringify(result);
  165. } else {
  166. throw new Error(`Prompt function must return a string or object, got ${typeof result}`);
  167. }
  168. }
  169. // Remove any trailing newlines from vars, as this tends to be a footgun for JSON prompts.
  170. for (const key of Object.keys(vars)) {
  171. if (typeof vars[key] === 'string') {
  172. vars[key] = (vars[key] as string).replace(/\n$/, '');
  173. }
  174. }
  175. // Resolve variable mappings
  176. resolveVariables(vars);
  177. // Third party integrations
  178. if (prompt.raw.startsWith('portkey://')) {
  179. const { getPrompt } = await import('./integrations/portkey');
  180. const portKeyResult = await getPrompt(prompt.raw.slice('portkey://'.length), vars);
  181. return JSON.stringify(portKeyResult.messages);
  182. } else if (prompt.raw.startsWith('langfuse://')) {
  183. const { getPrompt } = await import('./integrations/langfuse');
  184. const langfusePrompt = prompt.raw.slice('langfuse://'.length);
  185. // we default to "text" type.
  186. const [helper, version, promptType = 'text'] = langfusePrompt.split(':');
  187. if (promptType !== 'text' && promptType !== 'chat') {
  188. throw new Error('Unknown promptfoo prompt type');
  189. }
  190. const langfuseResult = await getPrompt(
  191. helper,
  192. vars,
  193. promptType,
  194. version !== 'latest' ? Number(version) : undefined,
  195. );
  196. return langfuseResult;
  197. }
  198. // Render prompt
  199. try {
  200. if (process.env.PROMPTFOO_DISABLE_JSON_AUTOESCAPE) {
  201. return nunjucks.renderString(basePrompt, vars);
  202. }
  203. const parsed = JSON.parse(basePrompt);
  204. // The _raw_ prompt is valid JSON. That means that the user likely wants to substitute vars _within_ the JSON itself.
  205. // Recursively walk the JSON structure. If we find a string, render it with nunjucks.
  206. return JSON.stringify(renderVarsInObject(parsed, vars), null, 2);
  207. } catch (err) {
  208. return nunjucks.renderString(basePrompt, vars);
  209. }
  210. }
  211. class Evaluator {
  212. testSuite: TestSuite;
  213. options: EvaluateOptions;
  214. stats: EvaluateStats;
  215. conversations: Record<
  216. string,
  217. { prompt: string | object; input: string; output: string | object }[]
  218. >;
  219. registers: Record<string, string | object>;
  220. constructor(testSuite: TestSuite, options: EvaluateOptions) {
  221. this.testSuite = testSuite;
  222. this.options = options;
  223. this.stats = {
  224. successes: 0,
  225. failures: 0,
  226. tokenUsage: {
  227. total: 0,
  228. prompt: 0,
  229. completion: 0,
  230. cached: 0,
  231. },
  232. };
  233. this.conversations = {};
  234. this.registers = {};
  235. }
  236. async runEval({
  237. provider,
  238. prompt,
  239. test,
  240. delay,
  241. nunjucksFilters: filters,
  242. evaluateOptions,
  243. }: RunEvalOptions): Promise<EvaluateResult> {
  244. // Use the original prompt to set the label, not renderedPrompt
  245. let promptLabel = prompt.label;
  246. // Set up the special _conversation variable
  247. const vars = test.vars || {};
  248. const conversationKey = `${provider.label || provider.id()}:${prompt.id}`;
  249. const usesConversation = prompt.raw.includes('_conversation');
  250. if (
  251. !process.env.PROMPTFOO_DISABLE_CONVERSATION_VAR &&
  252. !test.options?.disableConversationVar &&
  253. usesConversation
  254. ) {
  255. vars._conversation = this.conversations[conversationKey] || [];
  256. }
  257. // Overwrite vars with any saved register values
  258. Object.assign(vars, this.registers);
  259. // Render the prompt
  260. const renderedPrompt = await renderPrompt(prompt, vars, filters, provider);
  261. let renderedJson = undefined;
  262. try {
  263. renderedJson = JSON.parse(renderedPrompt);
  264. } catch {}
  265. const setup = {
  266. provider: {
  267. id: provider.id(),
  268. label: provider.label,
  269. },
  270. prompt: {
  271. raw: renderedPrompt,
  272. label: promptLabel,
  273. },
  274. vars,
  275. };
  276. // Call the API
  277. let latencyMs = 0;
  278. try {
  279. const startTime = Date.now();
  280. let response: ProviderResponse = {
  281. output: '',
  282. tokenUsage: {},
  283. cost: 0,
  284. cached: false,
  285. };
  286. if (test.providerOutput) {
  287. response.output = test.providerOutput;
  288. } else {
  289. response = await ((test.provider as ApiProvider) || provider).callApi(
  290. renderedPrompt,
  291. {
  292. vars,
  293. // These are removed in python and script providers, but every Javascript provider gets them
  294. logger,
  295. fetchWithCache,
  296. getCache,
  297. },
  298. {
  299. originalProvider: provider,
  300. includeLogProbs: test.assert?.some((a) => a.type === 'perplexity'),
  301. },
  302. );
  303. }
  304. const endTime = Date.now();
  305. latencyMs = endTime - startTime;
  306. let conversationLastInput = undefined;
  307. if (renderedJson && Array.isArray(renderedJson)) {
  308. const lastElt = renderedJson[renderedJson.length - 1];
  309. // Use the `content` field if present (OpenAI chat format)
  310. conversationLastInput = lastElt?.content || lastElt;
  311. }
  312. this.conversations[conversationKey] = this.conversations[conversationKey] || [];
  313. this.conversations[conversationKey].push({
  314. prompt: renderedJson || renderedPrompt,
  315. input: conversationLastInput || renderedJson || renderedPrompt,
  316. output: response.output || '',
  317. });
  318. if (!response.cached) {
  319. let sleep = provider.delay ?? delay;
  320. if (!sleep && process.env.PROMPTFOO_DELAY_MS) {
  321. sleep = parseInt(process.env.PROMPTFOO_DELAY_MS, 10) || 0;
  322. }
  323. if (sleep) {
  324. logger.debug(`Sleeping for ${sleep}ms`);
  325. await new Promise((resolve) => setTimeout(resolve, sleep));
  326. }
  327. }
  328. const ret: EvaluateResult = {
  329. ...setup,
  330. response,
  331. success: false,
  332. score: 0,
  333. namedScores: {},
  334. latencyMs,
  335. cost: response.cost,
  336. };
  337. if (response.error) {
  338. ret.error = response.error;
  339. } else if (response.output) {
  340. // Create a copy of response so we can potentially mutate it.
  341. let processedResponse = { ...response };
  342. const transform =
  343. test.options?.transform || test.options?.postprocess || provider.transform;
  344. if (transform) {
  345. processedResponse.output = await transformOutput(transform, processedResponse.output, {
  346. vars,
  347. prompt,
  348. });
  349. }
  350. invariant(processedResponse.output != null, 'Response output should not be null');
  351. const checkResult = await runAssertions({
  352. prompt: renderedPrompt,
  353. provider,
  354. test,
  355. output: processedResponse.output,
  356. latencyMs: response.cached ? undefined : latencyMs,
  357. logProbs: response.logProbs,
  358. cost: processedResponse.cost,
  359. });
  360. if (!checkResult.pass) {
  361. ret.error = checkResult.reason;
  362. }
  363. ret.success = checkResult.pass;
  364. ret.score = checkResult.score;
  365. ret.namedScores = checkResult.namedScores || {};
  366. if (checkResult.tokensUsed) {
  367. this.stats.tokenUsage.total += checkResult.tokensUsed.total;
  368. this.stats.tokenUsage.prompt += checkResult.tokensUsed.prompt;
  369. this.stats.tokenUsage.completion += checkResult.tokensUsed.completion;
  370. }
  371. ret.response = processedResponse;
  372. ret.gradingResult = checkResult;
  373. } else {
  374. ret.success = false;
  375. ret.score = 0;
  376. ret.error = 'No output';
  377. }
  378. // Update token usage stats
  379. if (response.tokenUsage) {
  380. this.stats.tokenUsage.total += response.tokenUsage.total || 0;
  381. this.stats.tokenUsage.prompt += response.tokenUsage.prompt || 0;
  382. this.stats.tokenUsage.completion += response.tokenUsage.completion || 0;
  383. this.stats.tokenUsage.cached += response.tokenUsage.cached || 0;
  384. }
  385. if (ret.success) {
  386. this.stats.successes++;
  387. } else {
  388. this.stats.failures++;
  389. }
  390. if (test.options?.storeOutputAs && ret.response?.output) {
  391. // Save the output in a register for later use
  392. this.registers[test.options.storeOutputAs] = ret.response.output;
  393. }
  394. return ret;
  395. } catch (err) {
  396. this.stats.failures++;
  397. return {
  398. ...setup,
  399. error: String(err) + '\n\n' + (err as Error).stack,
  400. success: false,
  401. score: 0,
  402. namedScores: {},
  403. latencyMs,
  404. };
  405. }
  406. }
  407. async evaluate(): Promise<EvaluateSummary> {
  408. const { testSuite, options } = this;
  409. const prompts: CompletedPrompt[] = [];
  410. if (options.generateSuggestions) {
  411. // TODO(ian): Move this into its own command/file
  412. logger.info(`Generating prompt variations...`);
  413. const { prompts: newPrompts, error } = await generatePrompts(testSuite.prompts[0].raw, 1);
  414. if (error || !newPrompts) {
  415. throw new Error(`Failed to generate prompts: ${error}`);
  416. }
  417. logger.info(chalk.blue('Generated prompts:'));
  418. let numAdded = 0;
  419. for (const prompt of newPrompts) {
  420. logger.info('--------------------------------------------------------');
  421. logger.info(`${prompt}`);
  422. logger.info('--------------------------------------------------------');
  423. // Ask the user if they want to continue
  424. await new Promise((resolve) => {
  425. const rl = readline.createInterface({
  426. input: process.stdin,
  427. output: process.stdout,
  428. });
  429. rl.question(
  430. `${chalk.blue('Do you want to test this prompt?')} (y/N): `,
  431. async (answer) => {
  432. rl.close();
  433. if (answer.toLowerCase().startsWith('y')) {
  434. testSuite.prompts.push({ raw: prompt, label: prompt });
  435. numAdded++;
  436. } else {
  437. logger.info('Skipping this prompt.');
  438. }
  439. resolve(true);
  440. },
  441. );
  442. });
  443. }
  444. if (numAdded < 1) {
  445. logger.info(chalk.red('No prompts selected. Aborting.'));
  446. process.exit(1);
  447. }
  448. }
  449. // Split prompts by provider
  450. for (const prompt of testSuite.prompts) {
  451. for (const provider of testSuite.providers) {
  452. // Check if providerPromptMap exists and if it contains the current prompt's label
  453. if (testSuite.providerPromptMap) {
  454. const allowedPrompts = testSuite.providerPromptMap[provider.id()];
  455. if (allowedPrompts && !allowedPrompts.includes(prompt.label)) {
  456. continue;
  457. }
  458. }
  459. const completedPrompt = {
  460. ...prompt,
  461. id: sha256(typeof prompt.raw === 'object' ? JSON.stringify(prompt.raw) : prompt.raw),
  462. provider: provider.label || provider.id(),
  463. label: prompt.label,
  464. metrics: {
  465. score: 0,
  466. testPassCount: 0,
  467. testFailCount: 0,
  468. assertPassCount: 0,
  469. assertFailCount: 0,
  470. totalLatencyMs: 0,
  471. tokenUsage: {
  472. total: 0,
  473. prompt: 0,
  474. completion: 0,
  475. cached: 0,
  476. },
  477. namedScores: {},
  478. cost: 0,
  479. },
  480. };
  481. prompts.push(completedPrompt);
  482. }
  483. }
  484. // Aggregate all vars across test cases
  485. let tests =
  486. testSuite.tests && testSuite.tests.length > 0
  487. ? testSuite.tests
  488. : testSuite.scenarios
  489. ? []
  490. : [
  491. {
  492. // Dummy test for cases when we're only comparing raw prompts.
  493. },
  494. ];
  495. // Build scenarios and add to tests
  496. if (testSuite.scenarios && testSuite.scenarios.length > 0) {
  497. for (const scenario of testSuite.scenarios) {
  498. for (const data of scenario.config) {
  499. // Merge defaultTest with scenario config
  500. const scenarioTests = (
  501. scenario.tests || [
  502. {
  503. // Dummy test for cases when we're only comparing raw prompts.
  504. },
  505. ]
  506. ).map((test) => {
  507. return {
  508. ...testSuite.defaultTest,
  509. ...data,
  510. ...test,
  511. vars: {
  512. ...testSuite.defaultTest?.vars,
  513. ...data.vars,
  514. ...test.vars,
  515. },
  516. options: {
  517. ...testSuite.defaultTest?.options,
  518. ...test.options,
  519. },
  520. };
  521. });
  522. // Add scenario tests to tests
  523. tests = tests.concat(scenarioTests);
  524. }
  525. }
  526. }
  527. maybeEmitAzureOpenAiWarning(testSuite, tests);
  528. // Prepare vars
  529. const varNames: Set<string> = new Set();
  530. const varsWithSpecialColsRemoved: Record<string, string | string[] | object>[] = [];
  531. for (const testCase of tests) {
  532. if (testCase.vars) {
  533. const varWithSpecialColsRemoved: Record<string, string | string[] | object> = {};
  534. for (const varName of Object.keys(testCase.vars)) {
  535. varNames.add(varName);
  536. varWithSpecialColsRemoved[varName] = testCase.vars[varName];
  537. }
  538. varsWithSpecialColsRemoved.push(varWithSpecialColsRemoved);
  539. }
  540. }
  541. // Set up eval cases
  542. let runEvalOptions: RunEvalOptions[] = [];
  543. let rowIndex = 0;
  544. for (let index = 0; index < tests.length; index++) {
  545. const testCase = tests[index];
  546. invariant(
  547. Array.isArray(testSuite.defaultTest?.assert || []),
  548. `defaultTest.assert is not an array in test case #${index + 1}`,
  549. );
  550. invariant(
  551. Array.isArray(testCase.assert || []),
  552. `testCase.assert is not an array in test case #${index + 1}`,
  553. );
  554. // Handle default properties
  555. testCase.vars = { ...testSuite.defaultTest?.vars, ...testCase.vars };
  556. testCase.assert = [...(testSuite.defaultTest?.assert || []), ...(testCase.assert || [])];
  557. testCase.threshold = testCase.threshold ?? testSuite.defaultTest?.threshold;
  558. testCase.options = { ...testSuite.defaultTest?.options, ...testCase.options };
  559. const prependToPrompt =
  560. testCase.options?.prefix || testSuite.defaultTest?.options?.prefix || '';
  561. const appendToPrompt =
  562. testCase.options?.suffix || testSuite.defaultTest?.options?.suffix || '';
  563. // Finalize test case eval
  564. const varCombinations =
  565. process.env.PROMPTFOO_DISABLE_VAR_EXPANSION || testCase.options.disableVarExpansion
  566. ? [testCase.vars]
  567. : generateVarCombinations(testCase.vars || {});
  568. const numRepeat = this.options.repeat || 1;
  569. for (let repeatIndex = 0; repeatIndex < numRepeat; repeatIndex++) {
  570. for (const vars of varCombinations) {
  571. let colIndex = 0;
  572. for (const prompt of testSuite.prompts) {
  573. for (const provider of testSuite.providers) {
  574. if (testSuite.providerPromptMap) {
  575. const allowedPrompts = testSuite.providerPromptMap[provider.id()];
  576. if (allowedPrompts && !allowedPrompts.includes(prompt.label)) {
  577. // This prompt should not be used with this provider.
  578. continue;
  579. }
  580. }
  581. runEvalOptions.push({
  582. delay: options.delay || 0,
  583. provider,
  584. prompt: {
  585. ...prompt,
  586. raw: prependToPrompt + prompt.raw + appendToPrompt,
  587. },
  588. test: { ...testCase, vars, options: testCase.options },
  589. nunjucksFilters: testSuite.nunjucksFilters,
  590. rowIndex,
  591. colIndex,
  592. repeatIndex,
  593. evaluateOptions: options,
  594. });
  595. colIndex++;
  596. }
  597. }
  598. rowIndex++;
  599. }
  600. }
  601. }
  602. // Set up table...
  603. const isTest = tests.some((t) => !!t.assert);
  604. const table: EvaluateTable = {
  605. head: {
  606. prompts,
  607. vars: Array.from(varNames).sort(),
  608. },
  609. body: [],
  610. };
  611. // Determine run parameters
  612. let concurrency = options.maxConcurrency || DEFAULT_MAX_CONCURRENCY;
  613. if (concurrency > 1) {
  614. const usesConversation = prompts.some((p) => p.raw.includes('_conversation'));
  615. const usesStoreOutputAs = tests.some((t) => t.options?.storeOutputAs);
  616. if (usesConversation) {
  617. logger.info(
  618. `Setting concurrency to 1 because the ${chalk.cyan('_conversation')} variable is used.`,
  619. );
  620. concurrency = 1;
  621. } else if (usesStoreOutputAs) {
  622. logger.info(
  623. `Setting concurrency to 1 because storeOutputAs is used.`,
  624. );
  625. concurrency = 1;
  626. }
  627. }
  628. // Actually run the eval
  629. const results: EvaluateResult[] = [];
  630. let numComplete = 0;
  631. const processEvalStep = async (evalStep: RunEvalOptions, index: number | string) => {
  632. if (typeof index !== 'number') {
  633. throw new Error('Expected index to be a number');
  634. }
  635. const row = await this.runEval(evalStep);
  636. results.push(row);
  637. numComplete++;
  638. if (options.progressCallback) {
  639. options.progressCallback(results.length, runEvalOptions.length, index, evalStep);
  640. }
  641. // Bookkeeping for table
  642. let resultText: string | undefined;
  643. const outputTextDisplay =
  644. typeof row.response?.output === 'object'
  645. ? JSON.stringify(row.response.output)
  646. : row.response?.output || null;
  647. if (isTest) {
  648. if (row.success) {
  649. resultText = `${outputTextDisplay || row.error || ''}`;
  650. } else {
  651. resultText = `${row.error}\n---\n${outputTextDisplay || ''}`;
  652. }
  653. } else if (row.error) {
  654. resultText = `${row.error}`;
  655. } else {
  656. resultText = outputTextDisplay || row.error || '';
  657. }
  658. const { rowIndex, colIndex } = evalStep;
  659. if (!table.body[rowIndex]) {
  660. table.body[rowIndex] = {
  661. description: evalStep.test.description,
  662. outputs: [],
  663. test: evalStep.test,
  664. vars: table.head.vars
  665. .map((varName) => {
  666. const varValue = evalStep.test.vars?.[varName] || '';
  667. if (typeof varValue === 'string') {
  668. return varValue;
  669. }
  670. return JSON.stringify(varValue);
  671. })
  672. .flat(),
  673. };
  674. }
  675. table.body[rowIndex].outputs[colIndex] = {
  676. pass: row.success,
  677. score: row.score,
  678. namedScores: row.namedScores,
  679. text: resultText,
  680. prompt: row.prompt.raw,
  681. provider: row.provider.label || row.provider.id,
  682. latencyMs: row.latencyMs,
  683. tokenUsage: row.response?.tokenUsage,
  684. gradingResult: row.gradingResult,
  685. cost: row.cost || 0,
  686. };
  687. const metrics = table.head.prompts[colIndex].metrics;
  688. invariant(metrics, 'Expected prompt.metrics to be set');
  689. metrics.score += row.score;
  690. for (const [key, value] of Object.entries(row.namedScores)) {
  691. metrics.namedScores[key] = (metrics.namedScores[key] || 0) + value;
  692. }
  693. if (testSuite.derivedMetrics) {
  694. const math = await import('mathjs');
  695. for (const metric of testSuite.derivedMetrics) {
  696. if (metrics.namedScores[metric.name] === undefined) {
  697. metrics.namedScores[metric.name] = 0;
  698. }
  699. try {
  700. if (typeof metric.value === 'function') {
  701. metrics.namedScores[metric.name] = metric.value(metrics.namedScores, evalStep);
  702. } else {
  703. const evaluatedValue = math.evaluate(metric.value, metrics.namedScores);
  704. metrics.namedScores[metric.name] = evaluatedValue;
  705. }
  706. } catch (error) {
  707. logger.debug(
  708. `Could not evaluate derived metric '${metric.name}': ${(error as Error).message}`,
  709. );
  710. }
  711. }
  712. }
  713. metrics.testPassCount += row.success ? 1 : 0;
  714. metrics.testFailCount += row.success ? 0 : 1;
  715. metrics.assertPassCount +=
  716. row.gradingResult?.componentResults?.filter((r) => r.pass).length || 0;
  717. metrics.assertFailCount +=
  718. row.gradingResult?.componentResults?.filter((r) => !r.pass).length || 0;
  719. metrics.totalLatencyMs += row.latencyMs || 0;
  720. metrics.tokenUsage.cached =
  721. (metrics.tokenUsage.cached || 0) + (row.response?.tokenUsage?.cached || 0);
  722. metrics.tokenUsage.completion += row.response?.tokenUsage?.completion || 0;
  723. metrics.tokenUsage.prompt += row.response?.tokenUsage?.prompt || 0;
  724. metrics.tokenUsage.total += row.response?.tokenUsage?.total || 0;
  725. metrics.cost += row.cost || 0;
  726. };
  727. // Set up main progress bars
  728. let multibar: MultiBar | undefined;
  729. let multiProgressBars: SingleBar[] = [];
  730. this.options.progressCallback = (completed, total, index, evalStep) => {
  731. if (multibar && evalStep) {
  732. const threadIndex = index % concurrency;
  733. const progressbar = multiProgressBars[threadIndex];
  734. progressbar.increment({
  735. provider: evalStep.provider.label || evalStep.provider.id(),
  736. prompt: evalStep.prompt.raw.slice(0, 10).replace(/\n/g, ' '),
  737. vars: Object.entries(evalStep.test.vars || {})
  738. .map(([k, v]) => `${k}=${v}`)
  739. .join(' ')
  740. .slice(0, 10)
  741. .replace(/\n/g, ' '),
  742. });
  743. } else {
  744. logger.debug(`Eval #${index + 1} complete (${numComplete} of ${runEvalOptions.length})`);
  745. }
  746. };
  747. const createMultiBars = async (evalOptions: RunEvalOptions[]) => {
  748. const cliProgress = await import('cli-progress');
  749. multibar = new cliProgress.MultiBar(
  750. {
  751. format:
  752. '[{bar}] {percentage}% | ETA: {eta}s | {value}/{total} | {provider} "{prompt}" {vars}',
  753. hideCursor: true,
  754. },
  755. cliProgress.Presets.shades_classic,
  756. );
  757. const stepsPerThread = Math.floor(evalOptions.length / concurrency);
  758. const remainingSteps = evalOptions.length % concurrency;
  759. multiProgressBars = [];
  760. for (let i = 0; i < concurrency; i++) {
  761. const totalSteps = i < remainingSteps ? stepsPerThread + 1 : stepsPerThread;
  762. if (totalSteps > 0) {
  763. const progressbar = multibar.create(totalSteps, 0, {
  764. provider: '',
  765. prompt: '',
  766. vars: '',
  767. });
  768. multiProgressBars.push(progressbar);
  769. }
  770. }
  771. };
  772. // Run the evals
  773. if (this.options.interactiveProviders) {
  774. runEvalOptions = runEvalOptions.sort((a, b) =>
  775. a.provider.id().localeCompare(b.provider.id()),
  776. );
  777. logger.warn('Providers are running in serial with user input.');
  778. // Group evalOptions by provider
  779. const groupedEvalOptions = runEvalOptions.reduce<Record<string, RunEvalOptions[]>>(
  780. (acc, evalOption) => {
  781. const providerId = evalOption.provider.id();
  782. if (!acc[providerId]) {
  783. acc[providerId] = [];
  784. }
  785. acc[providerId].push(evalOption);
  786. return acc;
  787. },
  788. {},
  789. );
  790. // Process each group
  791. for (const [providerId, providerEvalOptions] of Object.entries(groupedEvalOptions)) {
  792. logger.info(
  793. `Running ${providerEvalOptions.length} evaluations for provider ${providerId} with concurrency=${concurrency}...`,
  794. );
  795. if (this.options.showProgressBar) {
  796. await createMultiBars(providerEvalOptions);
  797. }
  798. await async.forEachOfLimit(providerEvalOptions, concurrency, processEvalStep);
  799. if (multibar) {
  800. multibar.stop();
  801. }
  802. // Prompt to continue to the next provider unless it's the last one
  803. if (
  804. Object.keys(groupedEvalOptions).indexOf(providerId) <
  805. Object.keys(groupedEvalOptions).length - 1
  806. ) {
  807. await new Promise((resolve) => {
  808. const rl = readline.createInterface({
  809. input: process.stdin,
  810. output: process.stdout,
  811. });
  812. rl.question(`\nReady to continue to the next provider? (Y/n) `, (answer) => {
  813. rl.close();
  814. if (answer.toLowerCase() === 'n') {
  815. logger.info('Aborting evaluation.');
  816. process.exit(1);
  817. }
  818. resolve(true);
  819. });
  820. });
  821. }
  822. }
  823. } else {
  824. if (this.options.showProgressBar) {
  825. await createMultiBars(runEvalOptions);
  826. }
  827. await async.forEachOfLimit(runEvalOptions, concurrency, processEvalStep);
  828. }
  829. // Do we have to run comparisons between row outputs?
  830. const compareRowsCount = table.body.reduce(
  831. (count, row) => count + (row.test.assert?.some((a) => a.type === 'select-best') ? 1 : 0),
  832. 0,
  833. );
  834. let progressBar;
  835. if (compareRowsCount > 0 && multibar) {
  836. progressBar = multibar.create(compareRowsCount, 0, {
  837. provider: 'Running model-graded comparisons',
  838. prompt: '',
  839. vars: '',
  840. });
  841. }
  842. for (let index = 0; index < table.body.length; index++) {
  843. const row = table.body[index];
  844. const compareAssertion = row.test.assert?.find((a) => a.type === 'select-best') as Assertion;
  845. if (compareAssertion) {
  846. const outputs = row.outputs.map((o) => o.text);
  847. const gradingResults = await runCompareAssertion(row.test, compareAssertion, outputs);
  848. row.outputs.forEach((output, index) => {
  849. const gradingResult = gradingResults[index];
  850. if (!output.gradingResult) {
  851. output.gradingResult = gradingResult;
  852. } else {
  853. output.gradingResult.tokensUsed = output.gradingResult.tokensUsed || {
  854. total: 0,
  855. prompt: 0,
  856. completion: 0,
  857. };
  858. output.gradingResult.tokensUsed.total += gradingResult.tokensUsed?.total || 0;
  859. output.gradingResult.tokensUsed.prompt += gradingResult.tokensUsed?.prompt || 0;
  860. output.gradingResult.tokensUsed.completion += gradingResult.tokensUsed?.completion || 0;
  861. output.pass = output.gradingResult.pass =
  862. output.gradingResult.pass && gradingResult.pass;
  863. if (!gradingResult.pass) {
  864. // Failure overrides the reason and the score
  865. output.gradingResult.reason = gradingResult.reason;
  866. output.score = output.gradingResult.score = gradingResult.score;
  867. output.text = `${gradingResult.reason}\n---\n${output.text}`;
  868. }
  869. if (!output.gradingResult.componentResults) {
  870. output.gradingResult.componentResults = [];
  871. }
  872. output.gradingResult.componentResults.push(gradingResult);
  873. }
  874. });
  875. if (progressBar) {
  876. progressBar.increment({
  877. prompt: row.outputs[0].text.slice(0, 10).replace(/\n/g, ''),
  878. });
  879. } else {
  880. logger.debug(`Model-graded comparison #${index + 1} of ${compareRowsCount} complete`);
  881. }
  882. }
  883. }
  884. // Finish up
  885. if (multibar) {
  886. multibar.stop();
  887. }
  888. if (progressBar) {
  889. progressBar.stop();
  890. }
  891. telemetry.record('eval_ran', {
  892. numPrompts: prompts.length,
  893. numTests: tests.length,
  894. numVars: varNames.size,
  895. numProviders: testSuite.providers.length,
  896. numRepeat: options.repeat || 1,
  897. providerPrefixes: Array.from(
  898. new Set(
  899. testSuite.providers.map((p) => {
  900. const idParts = p.id().split(':');
  901. return idParts.length > 1 ? idParts[0] : 'unknown';
  902. }),
  903. ),
  904. ).sort(),
  905. assertionTypes: Array.from(
  906. new Set(tests.flatMap((t) => t.assert || []).map((a) => a.type)),
  907. ).sort(),
  908. eventSource: options.eventSource || 'default',
  909. ci: Boolean(
  910. process.env.CI ||
  911. process.env.GITHUB_ACTIONS ||
  912. process.env.TRAVIS ||
  913. process.env.CIRCLECI ||
  914. process.env.JENKINS ||
  915. process.env.GITLAB_CI,
  916. ),
  917. hasAnyPass: results.some((r) => r.success),
  918. });
  919. return { version: 2, timestamp: new Date().toISOString(), results, stats: this.stats, table };
  920. }
  921. }
  922. export function evaluate(testSuite: TestSuite, options: EvaluateOptions) {
  923. const ev = new Evaluator(testSuite, options);
  924. return ev.evaluate();
  925. }
Tip!

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

Comments

Loading...