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

main.ts 32 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
  1. #!/usr/bin/env node
  2. import fs from 'fs';
  3. import path from 'path';
  4. import readline from 'readline';
  5. import chalk from 'chalk';
  6. import chokidar from 'chokidar';
  7. import yaml from 'js-yaml';
  8. import { Command } from 'commander';
  9. import cliState from './cliState';
  10. import telemetry from './telemetry';
  11. import logger, { getLogLevel, setLogLevel } from './logger';
  12. import { readAssertions } from './assertions';
  13. import { loadApiProvider, loadApiProviders } from './providers';
  14. import { evaluate, DEFAULT_MAX_CONCURRENCY } from './evaluator';
  15. import { readPrompts, readProviderPromptMap } from './prompts';
  16. import { readTest, readTests, synthesizeFromTestSuite } from './testCases';
  17. import { synthesizeFromTestSuite as redteamSynthesizeFromTestSuite } from './redteam';
  18. import {
  19. cleanupOldFileResults,
  20. maybeReadConfig,
  21. migrateResultsFromFileSystemToDatabase,
  22. printBorder,
  23. readConfigs,
  24. readFilters,
  25. readLatestResults,
  26. setConfigDirectoryPath,
  27. setupEnv,
  28. writeMultipleOutputs,
  29. writeOutput,
  30. writeResultsToDatabase,
  31. } from './util';
  32. import { DEFAULT_README, DEFAULT_YAML_CONFIG } from './onboarding';
  33. import { disableCache, clearCache } from './cache';
  34. import { getDirectory } from './esm';
  35. import { startServer } from './web/server';
  36. import { checkForUpdates } from './updates';
  37. import { gatherFeedback } from './feedback';
  38. import { listCommand } from './commands/list';
  39. import { showCommand } from './commands/show';
  40. import { deleteCommand } from './commands/delete';
  41. import { importCommand } from './commands/import';
  42. import { exportCommand } from './commands/export';
  43. import type {
  44. CommandLineOptions,
  45. EvaluateOptions,
  46. TestCase,
  47. TestSuite,
  48. UnifiedConfig,
  49. } from './types';
  50. import { generateTable } from './table';
  51. import { createShareableUrl } from './share';
  52. import { filterTests } from './commands/eval/filterTests';
  53. import { validateAssertions } from './assertions/validateAssertions';
  54. function createDummyFiles(directory: string | null) {
  55. if (directory) {
  56. // Make the directory if it doesn't exist
  57. if (!fs.existsSync(directory)) {
  58. fs.mkdirSync(directory);
  59. }
  60. }
  61. if (directory) {
  62. if (!fs.existsSync(directory)) {
  63. logger.info(`Creating directory ${directory} ...`);
  64. fs.mkdirSync(directory);
  65. }
  66. } else {
  67. directory = '.';
  68. }
  69. fs.writeFileSync(
  70. path.join(process.cwd(), directory, 'promptfooconfig.yaml'),
  71. DEFAULT_YAML_CONFIG,
  72. );
  73. fs.writeFileSync(path.join(process.cwd(), directory, 'README.md'), DEFAULT_README);
  74. const isNpx = process.env.npm_execpath?.includes('npx');
  75. const runCommand = isNpx ? 'npx promptfoo@latest eval' : 'promptfoo eval';
  76. if (directory === '.') {
  77. logger.info(
  78. chalk.green(
  79. `✅ Wrote promptfooconfig.yaml. Run \`${chalk.bold(runCommand)}\` to get started!`,
  80. ),
  81. );
  82. } else {
  83. logger.info(`✅ Wrote promptfooconfig.yaml to ./${directory}`);
  84. logger.info(
  85. chalk.green(
  86. `Run \`${chalk.bold(`cd ${directory}`)}\` and then \`${chalk.bold(
  87. runCommand,
  88. )}\` to get started!`,
  89. ),
  90. );
  91. }
  92. }
  93. async function resolveConfigs(
  94. cmdObj: Partial<CommandLineOptions>,
  95. defaultConfig: Partial<UnifiedConfig>,
  96. ): Promise<{ testSuite: TestSuite; config: Partial<UnifiedConfig>; basePath: string }> {
  97. // Config parsing
  98. let fileConfig: Partial<UnifiedConfig> = {};
  99. const configPaths = cmdObj.config;
  100. if (configPaths) {
  101. fileConfig = await readConfigs(configPaths);
  102. }
  103. // Standalone assertion mode
  104. if (cmdObj.assertions) {
  105. if (!cmdObj.modelOutputs) {
  106. logger.error(chalk.red('You must provide --model-outputs when using --assertions'));
  107. process.exit(1);
  108. }
  109. const modelOutputs = JSON.parse(
  110. fs.readFileSync(path.join(process.cwd(), cmdObj.modelOutputs), 'utf8'),
  111. ) as string[] | { output: string; tags?: string[] }[];
  112. const assertions = await readAssertions(cmdObj.assertions);
  113. fileConfig.prompts = ['{{output}}'];
  114. fileConfig.providers = ['echo'];
  115. fileConfig.tests = modelOutputs.map((output) => {
  116. if (typeof output === 'string') {
  117. return {
  118. vars: {
  119. output,
  120. },
  121. assert: assertions,
  122. };
  123. }
  124. return {
  125. vars: {
  126. output: output.output,
  127. ...(output.tags === undefined ? {} : { tags: output.tags.join(', ') }),
  128. },
  129. assert: assertions,
  130. };
  131. });
  132. }
  133. // Use basepath in cases where path was supplied in the config file
  134. const basePath = configPaths ? path.dirname(configPaths[0]) : '';
  135. const defaultTestRaw = fileConfig.defaultTest || defaultConfig.defaultTest;
  136. const config: Omit<UnifiedConfig, 'evaluateOptions' | 'commandLineOptions'> = {
  137. description: fileConfig.description || defaultConfig.description,
  138. prompts: cmdObj.prompts || fileConfig.prompts || defaultConfig.prompts || [],
  139. providers: cmdObj.providers || fileConfig.providers || defaultConfig.providers || [],
  140. tests: cmdObj.tests || cmdObj.vars || fileConfig.tests || defaultConfig.tests || [],
  141. scenarios: fileConfig.scenarios || defaultConfig.scenarios,
  142. env: fileConfig.env || defaultConfig.env,
  143. sharing:
  144. process.env.PROMPTFOO_DISABLE_SHARING === '1'
  145. ? false
  146. : fileConfig.sharing ?? defaultConfig.sharing ?? true,
  147. defaultTest: defaultTestRaw ? await readTest(defaultTestRaw, basePath) : undefined,
  148. outputPath: cmdObj.output || fileConfig.outputPath || defaultConfig.outputPath,
  149. };
  150. // Validation
  151. if (!config.prompts || config.prompts.length === 0) {
  152. logger.error(chalk.red('You must provide at least 1 prompt'));
  153. process.exit(1);
  154. }
  155. if (!config.providers || config.providers.length === 0) {
  156. logger.error(
  157. chalk.red('You must specify at least 1 provider (for example, openai:gpt-3.5-turbo)'),
  158. );
  159. process.exit(1);
  160. }
  161. // Parse prompts, providers, and tests
  162. const parsedPrompts = await readPrompts(config.prompts, cmdObj.prompts ? undefined : basePath);
  163. const parsedProviders = await loadApiProviders(config.providers, {
  164. env: config.env,
  165. basePath,
  166. });
  167. const parsedTests: TestCase[] = await readTests(
  168. config.tests || [],
  169. cmdObj.tests ? undefined : basePath,
  170. );
  171. // Parse testCases for each scenario
  172. if (fileConfig.scenarios) {
  173. for (const scenario of fileConfig.scenarios) {
  174. const parsedScenarioTests: TestCase[] = await readTests(
  175. scenario.tests,
  176. cmdObj.tests ? undefined : basePath,
  177. );
  178. scenario.tests = parsedScenarioTests;
  179. }
  180. }
  181. const parsedProviderPromptMap = readProviderPromptMap(config, parsedPrompts);
  182. if (parsedPrompts.length === 0) {
  183. logger.error(chalk.red('No prompts found'));
  184. process.exit(1);
  185. }
  186. const defaultTest: TestCase = {
  187. options: {
  188. prefix: cmdObj.promptPrefix,
  189. suffix: cmdObj.promptSuffix,
  190. provider: cmdObj.grader,
  191. // rubricPrompt
  192. ...(config.defaultTest?.options || {}),
  193. },
  194. ...config.defaultTest,
  195. };
  196. const testSuite: TestSuite = {
  197. description: config.description,
  198. prompts: parsedPrompts,
  199. providers: parsedProviders,
  200. providerPromptMap: parsedProviderPromptMap,
  201. tests: parsedTests,
  202. scenarios: config.scenarios,
  203. defaultTest,
  204. nunjucksFilters: await readFilters(
  205. fileConfig.nunjucksFilters || defaultConfig.nunjucksFilters || {},
  206. ),
  207. };
  208. if (testSuite.tests) {
  209. validateAssertions(testSuite.tests);
  210. }
  211. return { config, testSuite, basePath };
  212. }
  213. async function main() {
  214. await checkForUpdates();
  215. const pwd = process.cwd();
  216. const potentialPaths = [
  217. path.join(pwd, 'promptfooconfig.js'),
  218. path.join(pwd, 'promptfooconfig.json'),
  219. path.join(pwd, 'promptfooconfig.yaml'),
  220. ];
  221. let defaultConfig: Partial<UnifiedConfig> = {};
  222. let defaultConfigPath: string | undefined;
  223. for (const _path of potentialPaths) {
  224. const maybeConfig = await maybeReadConfig(_path);
  225. if (maybeConfig) {
  226. defaultConfig = maybeConfig;
  227. defaultConfigPath = _path;
  228. break;
  229. }
  230. }
  231. let evaluateOptions: EvaluateOptions = {};
  232. if (defaultConfig.evaluateOptions) {
  233. evaluateOptions.generateSuggestions = defaultConfig.evaluateOptions.generateSuggestions;
  234. evaluateOptions.maxConcurrency = defaultConfig.evaluateOptions.maxConcurrency;
  235. evaluateOptions.showProgressBar = defaultConfig.evaluateOptions.showProgressBar;
  236. evaluateOptions.interactiveProviders = defaultConfig.evaluateOptions.interactiveProviders;
  237. }
  238. const program = new Command();
  239. program.option('--version', 'Print version', () => {
  240. const packageJson = JSON.parse(
  241. fs.readFileSync(path.join(getDirectory(), '../package.json'), 'utf8'),
  242. );
  243. logger.info(packageJson.version);
  244. });
  245. program
  246. .command('init [directory]')
  247. .description('Initialize project with dummy files')
  248. .action(async (directory: string | null) => {
  249. telemetry.maybeShowNotice();
  250. createDummyFiles(directory);
  251. telemetry.record('command_used', {
  252. name: 'init',
  253. });
  254. await telemetry.send();
  255. });
  256. program
  257. .command('view [directory]')
  258. .description('Start browser ui')
  259. .option('-p, --port <number>', 'Port number', '15500')
  260. .option('-y, --yes', 'Skip confirmation and auto-open the URL')
  261. .option('--api-base-url <url>', 'Base URL for viewer API calls')
  262. .option('--filter-description <pattern>', 'Filter evals by description using a regex pattern')
  263. .option('--env-file <path>', 'Path to .env file')
  264. .action(
  265. async (
  266. directory: string | undefined,
  267. cmdObj: {
  268. port: number;
  269. yes: boolean;
  270. apiBaseUrl?: string;
  271. envFile?: string;
  272. filterDescription?: string;
  273. } & Command,
  274. ) => {
  275. setupEnv(cmdObj.envFile);
  276. telemetry.maybeShowNotice();
  277. telemetry.record('command_used', {
  278. name: 'view',
  279. });
  280. await telemetry.send();
  281. if (directory) {
  282. setConfigDirectoryPath(directory);
  283. }
  284. // Block indefinitely on server
  285. await startServer(cmdObj.port, cmdObj.apiBaseUrl, cmdObj.yes, cmdObj.filterDescription);
  286. },
  287. );
  288. program
  289. .command('share')
  290. .description('Create a shareable URL of your most recent eval')
  291. .option('-y, --yes', 'Skip confirmation')
  292. .option('--env-file <path>', 'Path to .env file')
  293. .action(async (cmdObj: { yes: boolean; envFile?: string } & Command) => {
  294. setupEnv(cmdObj.envFile);
  295. telemetry.maybeShowNotice();
  296. telemetry.record('command_used', {
  297. name: 'share',
  298. });
  299. await telemetry.send();
  300. const createPublicUrl = async () => {
  301. const latestResults = await readLatestResults();
  302. if (!latestResults) {
  303. logger.error('Could not load results. Do you need to run `promptfoo eval` first?');
  304. process.exit(1);
  305. }
  306. const url = await createShareableUrl(latestResults.results, latestResults.config);
  307. logger.info(`View results: ${chalk.greenBright.bold(url)}`);
  308. };
  309. if (cmdObj.yes || process.env.PROMPTFOO_DISABLE_SHARE_WARNING) {
  310. createPublicUrl();
  311. } else {
  312. const reader = readline.createInterface({
  313. input: process.stdin,
  314. output: process.stdout,
  315. });
  316. reader.question(
  317. 'Create a private shareable URL of your most recent eval?\n\nTo proceed, please confirm [Y/n] ',
  318. async function (answer: string) {
  319. if (answer.toLowerCase() !== 'yes' && answer.toLowerCase() !== 'y' && answer !== '') {
  320. reader.close();
  321. process.exit(1);
  322. }
  323. reader.close();
  324. createPublicUrl();
  325. },
  326. );
  327. }
  328. });
  329. program
  330. .command('cache')
  331. .description('Manage cache')
  332. .command('clear')
  333. .description('Clear cache')
  334. .option('--env-file <path>', 'Path to .env file')
  335. .action(async (cmdObj: { envFile?: string }) => {
  336. setupEnv(cmdObj.envFile);
  337. telemetry.maybeShowNotice();
  338. logger.info('Clearing cache...');
  339. await clearCache();
  340. cleanupOldFileResults(0);
  341. telemetry.record('command_used', {
  342. name: 'cache_clear',
  343. });
  344. await telemetry.send();
  345. });
  346. program
  347. .command('feedback [message]')
  348. .description('Send feedback to the promptfoo developers')
  349. .action((message?: string) => {
  350. gatherFeedback(message);
  351. });
  352. const generateCommand = program.command('generate').description('Generate synthetic data');
  353. generateCommand
  354. .command('dataset')
  355. .description('Generate test cases')
  356. .option(
  357. '-i, --instructions [instructions]',
  358. 'Additional instructions to follow while generating test cases',
  359. )
  360. .option('-c, --config [path]', 'Path to configuration file. Defaults to promptfooconfig.yaml')
  361. .option('-o, --output [path]', 'Path to output file')
  362. .option('-w, --write', 'Write results to promptfoo configuration file')
  363. .option('--numPersonas <number>', 'Number of personas to generate', '5')
  364. .option('--numTestCasesPerPersona <number>', 'Number of test cases per persona', '3')
  365. .option('--no-cache', 'Do not read or write results to disk cache', false)
  366. .option('--env-file <path>', 'Path to .env file')
  367. .action(
  368. async (options: {
  369. config?: string;
  370. instructions?: string;
  371. output?: string;
  372. numPersonas: string;
  373. numTestCasesPerPersona: string;
  374. write: boolean;
  375. cache: boolean;
  376. envFile?: string;
  377. }) => {
  378. setupEnv(options.envFile);
  379. if (!options.cache) {
  380. logger.info('Cache is disabled.');
  381. disableCache();
  382. }
  383. let testSuite: TestSuite;
  384. const configPath = options.config || defaultConfigPath;
  385. if (configPath) {
  386. const resolved = await resolveConfigs(
  387. {
  388. config: [configPath],
  389. },
  390. defaultConfig,
  391. );
  392. testSuite = resolved.testSuite;
  393. } else {
  394. throw new Error('Could not find config file. Please use `--config`');
  395. }
  396. const startTime = Date.now();
  397. telemetry.record('command_used', {
  398. name: 'generate_dataset - started',
  399. numPrompts: testSuite.prompts.length,
  400. numTestsExisting: (testSuite.tests || []).length,
  401. });
  402. await telemetry.send();
  403. const results = await synthesizeFromTestSuite(testSuite, {
  404. instructions: options.instructions,
  405. numPersonas: parseInt(options.numPersonas, 10),
  406. numTestCasesPerPersona: parseInt(options.numTestCasesPerPersona, 10),
  407. });
  408. const configAddition = { tests: results.map((result) => ({ vars: result })) };
  409. const yamlString = yaml.dump(configAddition);
  410. if (options.output) {
  411. fs.writeFileSync(options.output, yamlString);
  412. printBorder();
  413. logger.info(`Wrote ${results.length} new test cases to ${options.output}`);
  414. printBorder();
  415. } else {
  416. printBorder();
  417. logger.info('New test Cases');
  418. printBorder();
  419. logger.info(yamlString);
  420. }
  421. printBorder();
  422. if (options.write && configPath) {
  423. const existingConfig = yaml.load(
  424. fs.readFileSync(configPath, 'utf8'),
  425. ) as Partial<UnifiedConfig>;
  426. existingConfig.tests = [...(existingConfig.tests || []), ...configAddition.tests];
  427. fs.writeFileSync(configPath, yaml.dump(existingConfig));
  428. logger.info(`Wrote ${results.length} new test cases to ${configPath}`);
  429. } else {
  430. logger.info(
  431. `Copy the above test cases or run ${chalk.greenBright(
  432. 'promptfoo generate dataset --write',
  433. )} to write directly to the config`,
  434. );
  435. }
  436. telemetry.record('command_used', {
  437. name: 'generate_dataset',
  438. numPrompts: testSuite.prompts.length,
  439. numTestsExisting: (testSuite.tests || []).length,
  440. numTestsGenerated: results.length,
  441. duration: Math.round((Date.now() - startTime) / 1000),
  442. });
  443. await telemetry.send();
  444. },
  445. );
  446. interface RedteamCommandOptions {
  447. config?: string;
  448. output?: string;
  449. write: boolean;
  450. cache: boolean;
  451. envFile?: string;
  452. purpose?: string;
  453. injectVar?: string;
  454. plugins?: string[];
  455. }
  456. generateCommand
  457. .command('redteam')
  458. .description('Generate adversarial test cases')
  459. .option('-c, --config [path]', 'Path to configuration file. Defaults to promptfooconfig.yaml')
  460. .option('-o, --output [path]', 'Path to output file')
  461. .option('-w, --write', 'Write results to promptfoo configuration file')
  462. .option(
  463. '--purpose <purpose>',
  464. 'Set the system purpose. If not set, the system purpose will be inferred from the config file',
  465. )
  466. .option(
  467. '--injectVar <varname>',
  468. 'Override the variable to inject user input into the prompt. If not set, the variable will defalt to {{query}}',
  469. )
  470. .option('--plugins <plugins>', 'Comma-separated list of plugins to use', (val) =>
  471. val.split(',').map((x) => x.trim()),
  472. )
  473. .option('--no-cache', 'Do not read or write results to disk cache', false)
  474. .option('--env-file <path>', 'Path to .env file')
  475. .action(
  476. async ({
  477. config,
  478. output,
  479. write,
  480. cache,
  481. envFile,
  482. purpose,
  483. injectVar,
  484. plugins,
  485. }: RedteamCommandOptions) => {
  486. setupEnv(envFile);
  487. if (!cache) {
  488. logger.info('Cache is disabled.');
  489. disableCache();
  490. }
  491. let testSuite: TestSuite;
  492. const configPath = config || defaultConfigPath;
  493. if (configPath) {
  494. const resolved = await resolveConfigs(
  495. {
  496. config: [configPath],
  497. },
  498. defaultConfig,
  499. );
  500. testSuite = resolved.testSuite;
  501. } else {
  502. throw new Error('Could not find config file. Please use `--config`');
  503. }
  504. const startTime = Date.now();
  505. telemetry.record('command_used', {
  506. name: 'generate redteam - started',
  507. numPrompts: testSuite.prompts.length,
  508. numTestsExisting: (testSuite.tests || []).length,
  509. });
  510. await telemetry.send();
  511. const redteamTests = await redteamSynthesizeFromTestSuite(testSuite, {
  512. purpose,
  513. injectVar,
  514. plugins,
  515. });
  516. if (output) {
  517. const existingYaml = yaml.load(fs.readFileSync(configPath, 'utf8')) as object;
  518. const updatedYaml = {
  519. ...existingYaml,
  520. tests: redteamTests,
  521. };
  522. fs.writeFileSync(output, yaml.dump(updatedYaml, { skipInvalid: true }));
  523. printBorder();
  524. logger.info(`Wrote ${redteamTests.length} new test cases to ${output}`);
  525. printBorder();
  526. } else if (write && configPath) {
  527. const existingConfig = yaml.load(
  528. fs.readFileSync(configPath, 'utf8'),
  529. ) as Partial<UnifiedConfig>;
  530. existingConfig.tests = [...(existingConfig.tests || []), ...redteamTests];
  531. fs.writeFileSync(configPath, yaml.dump(existingConfig));
  532. logger.info(`Wrote ${redteamTests.length} new test cases to ${configPath}`);
  533. } else {
  534. logger.info(yaml.dump(redteamTests, { skipInvalid: true }));
  535. }
  536. telemetry.record('command_used', {
  537. name: 'generate redteam',
  538. numPrompts: testSuite.prompts.length,
  539. numTestsExisting: (testSuite.tests || []).length,
  540. numTestsGenerated: redteamTests.length,
  541. duration: Math.round((Date.now() - startTime) / 1000),
  542. });
  543. await telemetry.send();
  544. },
  545. );
  546. program
  547. .command('eval')
  548. .description('Evaluate prompts')
  549. .option('-p, --prompts <paths...>', 'Paths to prompt files (.txt)')
  550. .option(
  551. '-r, --providers <name or path...>',
  552. 'One of: openai:chat, openai:completion, openai:<model name>, or path to custom API caller module',
  553. )
  554. .option(
  555. '-c, --config <paths...>',
  556. 'Path to configuration file. Automatically loads promptfooconfig.js/json/yaml',
  557. )
  558. .option(
  559. // TODO(ian): Remove `vars` for v1
  560. '-v, --vars, -t, --tests <path>',
  561. 'Path to CSV with test cases',
  562. defaultConfig?.commandLineOptions?.vars,
  563. )
  564. .option('-a, --assertions <path>', 'Path to assertions file')
  565. .option('--model-outputs <path>', 'Path to JSON containing list of LLM output strings')
  566. .option('-t, --tests <path>', 'Path to CSV with test cases')
  567. .option('-o, --output <paths...>', 'Path to output file (csv, txt, json, yaml, yml, html)')
  568. .option(
  569. '-j, --max-concurrency <number>',
  570. 'Maximum number of concurrent API calls',
  571. defaultConfig.evaluateOptions?.maxConcurrency
  572. ? String(defaultConfig.evaluateOptions.maxConcurrency)
  573. : `${DEFAULT_MAX_CONCURRENCY}`,
  574. )
  575. .option(
  576. '--repeat <number>',
  577. 'Number of times to run each test',
  578. defaultConfig.evaluateOptions?.repeat ? String(defaultConfig.evaluateOptions.repeat) : '1',
  579. )
  580. .option(
  581. '--delay <number>',
  582. 'Delay between each test (in milliseconds)',
  583. defaultConfig.evaluateOptions?.delay ? String(defaultConfig.evaluateOptions.delay) : '0',
  584. )
  585. .option(
  586. '--table-cell-max-length <number>',
  587. 'Truncate console table cells to this length',
  588. '250',
  589. )
  590. .option(
  591. '--suggest-prompts <number>',
  592. 'Generate N new prompts and append them to the prompt list',
  593. )
  594. .option(
  595. '--prompt-prefix <path>',
  596. 'This prefix is prepended to every prompt',
  597. defaultConfig.defaultTest?.options?.prefix,
  598. )
  599. .option(
  600. '--prompt-suffix <path>',
  601. 'This suffix is append to every prompt',
  602. defaultConfig.defaultTest?.options?.suffix,
  603. )
  604. .option(
  605. '--no-write',
  606. 'Do not write results to promptfoo directory',
  607. defaultConfig?.commandLineOptions?.write,
  608. )
  609. .option(
  610. '--no-cache',
  611. 'Do not read or write results to disk cache',
  612. // TODO(ian): Remove commandLineOptions.cache in v1
  613. defaultConfig?.commandLineOptions?.cache ?? defaultConfig?.evaluateOptions?.cache,
  614. )
  615. .option('--no-progress-bar', 'Do not show progress bar')
  616. .option('--table', 'Output table in CLI', defaultConfig?.commandLineOptions?.table ?? true)
  617. .option('--no-table', 'Do not output table in CLI', defaultConfig?.commandLineOptions?.table)
  618. .option('--share', 'Create a shareable URL', defaultConfig?.commandLineOptions?.share)
  619. .option(
  620. '--grader <provider>',
  621. 'Model that will grade outputs',
  622. defaultConfig?.commandLineOptions?.grader,
  623. )
  624. .option('--verbose', 'Show debug logs', defaultConfig?.commandLineOptions?.verbose)
  625. .option('-w, --watch', 'Watch for changes in config and re-run')
  626. .option('--env-file <path>', 'Path to .env file')
  627. .option(
  628. '--interactive-providers',
  629. 'Run providers interactively, one at a time',
  630. defaultConfig?.evaluateOptions?.interactiveProviders,
  631. )
  632. .option('-n, --filter-first-n <number>', 'Only run the first N tests')
  633. .option(
  634. '--filter-pattern <pattern>',
  635. 'Only run tests whose description matches the regular expression pattern',
  636. )
  637. .option('--filter-failing <path>', 'Path to json output file')
  638. .option(
  639. '--var <key=value>',
  640. 'Set a variable in key=value format',
  641. (value, previous: Record<string, string> = {}) => {
  642. const [key, val] = value.split('=');
  643. if (!key || val === undefined) {
  644. throw new Error('--var must be specified in key=value format.');
  645. }
  646. previous[key] = val;
  647. return previous;
  648. },
  649. {},
  650. )
  651. .action(async (cmdObj: CommandLineOptions & Command) => {
  652. setupEnv(cmdObj.envFile);
  653. let config: Partial<UnifiedConfig> | undefined = undefined;
  654. let testSuite: TestSuite | undefined = undefined;
  655. let basePath: string | undefined = undefined;
  656. const runEvaluation = async (initialization?: boolean) => {
  657. const startTime = Date.now();
  658. telemetry.record('command_used', {
  659. name: 'eval - started',
  660. watch: Boolean(cmdObj.watch),
  661. });
  662. await telemetry.send();
  663. // Misc settings
  664. if (cmdObj.verbose) {
  665. setLogLevel('debug');
  666. }
  667. const iterations = parseInt(cmdObj.repeat || '', 10);
  668. const repeat = !isNaN(iterations) && iterations > 0 ? iterations : 1;
  669. if (!cmdObj.cache || repeat > 1) {
  670. logger.info('Cache is disabled.');
  671. disableCache();
  672. }
  673. ({ config, testSuite, basePath } = await resolveConfigs(cmdObj, defaultConfig));
  674. cliState.basePath = basePath;
  675. let maxConcurrency = parseInt(cmdObj.maxConcurrency || '', 10);
  676. const delay = parseInt(cmdObj.delay || '', 0);
  677. if (delay > 0) {
  678. maxConcurrency = 1;
  679. logger.info(
  680. `Running at concurrency=1 because ${delay}ms delay was requested between API calls`,
  681. );
  682. }
  683. testSuite.tests = await filterTests(testSuite, {
  684. firstN: cmdObj.filterFirstN,
  685. pattern: cmdObj.filterPattern,
  686. failing: cmdObj.filterFailing,
  687. });
  688. const options: EvaluateOptions = {
  689. showProgressBar: getLogLevel() === 'debug' ? false : cmdObj.progressBar,
  690. maxConcurrency: !isNaN(maxConcurrency) && maxConcurrency > 0 ? maxConcurrency : undefined,
  691. repeat,
  692. delay: !isNaN(delay) && delay > 0 ? delay : undefined,
  693. interactiveProviders: cmdObj.interactiveProviders,
  694. ...evaluateOptions,
  695. };
  696. if (cmdObj.grader) {
  697. testSuite.defaultTest = testSuite.defaultTest || {};
  698. testSuite.defaultTest.options = testSuite.defaultTest.options || {};
  699. testSuite.defaultTest.options.provider = await loadApiProvider(cmdObj.grader);
  700. }
  701. if (cmdObj.var) {
  702. testSuite.defaultTest = testSuite.defaultTest || {};
  703. testSuite.defaultTest.vars = { ...testSuite.defaultTest.vars, ...cmdObj.var };
  704. }
  705. if (cmdObj.generateSuggestions) {
  706. options.generateSuggestions = true;
  707. }
  708. const summary = await evaluate(testSuite, {
  709. ...options,
  710. eventSource: 'cli',
  711. });
  712. const shareableUrl =
  713. cmdObj.share && config.sharing ? await createShareableUrl(summary, config) : null;
  714. if (cmdObj.table && getLogLevel() !== 'debug') {
  715. // Output CLI table
  716. const table = generateTable(summary, parseInt(cmdObj.tableCellMaxLength || '', 10));
  717. logger.info('\n' + table.toString());
  718. if (summary.table.body.length > 25) {
  719. const rowsLeft = summary.table.body.length - 25;
  720. logger.info(`... ${rowsLeft} more row${rowsLeft === 1 ? '' : 's'} not shown ...\n`);
  721. }
  722. } else if (summary.stats.failures !== 0) {
  723. logger.debug(
  724. `At least one evaluation failure occurred. This might be caused by the underlying call to the provider, or a test failure. Context: \n${JSON.stringify(
  725. summary.results,
  726. )}`,
  727. );
  728. }
  729. const { outputPath } = config;
  730. if (outputPath) {
  731. // Write output to file
  732. if (typeof outputPath === 'string') {
  733. await writeOutput(outputPath, summary, config, shareableUrl);
  734. } else if (Array.isArray(outputPath)) {
  735. await writeMultipleOutputs(outputPath, summary, config, shareableUrl);
  736. }
  737. logger.info(chalk.yellow(`Writing output to ${outputPath}`));
  738. }
  739. telemetry.maybeShowNotice();
  740. await migrateResultsFromFileSystemToDatabase();
  741. printBorder();
  742. if (!cmdObj.write) {
  743. logger.info(`${chalk.green('✔')} Evaluation complete`);
  744. } else {
  745. await writeResultsToDatabase(summary, config);
  746. if (shareableUrl) {
  747. logger.info(`${chalk.green('✔')} Evaluation complete: ${shareableUrl}`);
  748. } else {
  749. logger.info(`${chalk.green('✔')} Evaluation complete.\n`);
  750. logger.info(
  751. `» Run ${chalk.greenBright.bold('promptfoo view')} to use the local web viewer`,
  752. );
  753. logger.info(
  754. `» Run ${chalk.greenBright.bold('promptfoo share')} to create a shareable URL`,
  755. );
  756. logger.info(
  757. `» This project needs your feedback. What's one thing we can improve? ${chalk.greenBright.bold(
  758. 'https://forms.gle/YFLgTe1dKJKNSCsU7',
  759. )}`,
  760. );
  761. }
  762. }
  763. printBorder();
  764. logger.info(chalk.green.bold(`Successes: ${summary.stats.successes}`));
  765. logger.info(chalk.red.bold(`Failures: ${summary.stats.failures}`));
  766. logger.info(
  767. `Token usage: Total ${summary.stats.tokenUsage.total}, Prompt ${summary.stats.tokenUsage.prompt}, Completion ${summary.stats.tokenUsage.completion}, Cached ${summary.stats.tokenUsage.cached}`,
  768. );
  769. telemetry.record('command_used', {
  770. name: 'eval',
  771. watch: Boolean(cmdObj.watch),
  772. duration: Math.round((Date.now() - startTime) / 1000),
  773. });
  774. await telemetry.send();
  775. if (cmdObj.watch) {
  776. if (initialization) {
  777. const configPaths = (cmdObj.config || [defaultConfigPath]).filter(Boolean) as string[];
  778. if (!configPaths.length) {
  779. logger.error('Could not locate config file(s) to watch');
  780. process.exit(1);
  781. }
  782. const basePath = path.dirname(configPaths[0]);
  783. const promptPaths = Array.isArray(config.prompts)
  784. ? (config.prompts
  785. .map((p) => {
  786. if (typeof p === 'string' && p.startsWith('file://')) {
  787. return path.resolve(basePath, p.slice('file://'.length));
  788. } else if (typeof p === 'object' && p.id && p.id.startsWith('file://')) {
  789. return path.resolve(basePath, p.id.slice('file://'.length));
  790. }
  791. return null;
  792. })
  793. .filter(Boolean) as string[])
  794. : [];
  795. const providerPaths = Array.isArray(config.providers)
  796. ? (config.providers
  797. .map((p) =>
  798. typeof p === 'string' && p.startsWith('file://')
  799. ? path.resolve(basePath, p.slice('file://'.length))
  800. : null,
  801. )
  802. .filter(Boolean) as string[])
  803. : [];
  804. const varPaths = Array.isArray(config.tests)
  805. ? config.tests
  806. .flatMap((t) => {
  807. if (typeof t === 'string' && t.startsWith('file://')) {
  808. return path.resolve(basePath, t.slice('file://'.length));
  809. } else if (typeof t !== 'string' && t.vars) {
  810. return Object.values(t.vars).flatMap((v) => {
  811. if (typeof v === 'string' && v.startsWith('file://')) {
  812. return path.resolve(basePath, v.slice('file://'.length));
  813. }
  814. return [];
  815. });
  816. }
  817. return [];
  818. })
  819. .filter(Boolean)
  820. : [];
  821. const watchPaths = Array.from(
  822. new Set([...configPaths, ...promptPaths, ...providerPaths, ...varPaths]),
  823. );
  824. const watcher = chokidar.watch(watchPaths, { ignored: /^\./, persistent: true });
  825. watcher
  826. .on('change', async (path) => {
  827. printBorder();
  828. logger.info(`File change detected: ${path}`);
  829. printBorder();
  830. await runEvaluation();
  831. })
  832. .on('error', (error) => logger.error(`Watcher error: ${error}`))
  833. .on('ready', () =>
  834. watchPaths.forEach((watchPath) =>
  835. logger.info(`Watching for file changes on ${watchPath} ...`),
  836. ),
  837. );
  838. }
  839. } else {
  840. logger.info('Done.');
  841. if (summary.stats.failures > 0) {
  842. const exitCode = Number(process.env.PROMPTFOO_FAILED_TEST_EXIT_CODE);
  843. process.exit(isNaN(exitCode) ? 100 : exitCode);
  844. }
  845. }
  846. };
  847. await runEvaluation(true /* initialization */);
  848. });
  849. listCommand(program);
  850. showCommand(program);
  851. deleteCommand(program);
  852. importCommand(program);
  853. exportCommand(program);
  854. program.parse(process.argv);
  855. if (!process.argv.slice(2).length) {
  856. program.outputHelp();
  857. }
  858. }
  859. main();
Tip!

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

Comments

Loading...