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

util.ts 39 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
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
  1. import * as fs from 'fs';
  2. import * as path from 'path';
  3. import * as os from 'os';
  4. import { createHash } from 'crypto';
  5. import dotenv from 'dotenv';
  6. import $RefParser from '@apidevtools/json-schema-ref-parser';
  7. import invariant from 'tiny-invariant';
  8. import nunjucks from 'nunjucks';
  9. import yaml from 'js-yaml';
  10. import deepEqual from 'fast-deep-equal';
  11. import { stringify } from 'csv-stringify/sync';
  12. import { globSync } from 'glob';
  13. import { desc, eq } from 'drizzle-orm';
  14. import cliState from './cliState';
  15. import logger from './logger';
  16. import { getDirectory, importModule } from './esm';
  17. import { readTests } from './testCases';
  18. import {
  19. datasets,
  20. getDb,
  21. evals,
  22. evalsToDatasets,
  23. evalsToPrompts,
  24. prompts,
  25. getDbSignalPath,
  26. } from './database';
  27. import { runDbMigrations } from './migrate';
  28. import { runPython } from './python/wrapper';
  29. import {
  30. type EvalWithMetadata,
  31. type EvaluateResult,
  32. type EvaluateSummary,
  33. type EvaluateTable,
  34. type EvaluateTableOutput,
  35. type NunjucksFilterMap,
  36. type PromptWithMetadata,
  37. type ResultsFile,
  38. type TestCase,
  39. type TestCasesWithMetadata,
  40. type TestCasesWithMetadataPrompt,
  41. type UnifiedConfig,
  42. type OutputFile,
  43. type ProviderOptions,
  44. type Prompt,
  45. type CompletedPrompt,
  46. type CsvRow,
  47. isApiProvider,
  48. isProviderOptions,
  49. } from './types';
  50. import { writeCsvToGoogleSheet } from './googleSheets';
  51. const DEFAULT_QUERY_LIMIT = 100;
  52. let globalConfigCache: any = null;
  53. export function resetGlobalConfig(): void {
  54. globalConfigCache = null;
  55. }
  56. export function readGlobalConfig(): any {
  57. if (!globalConfigCache) {
  58. const configDir = getConfigDirectoryPath();
  59. const configFilePath = path.join(configDir, 'promptfoo.yaml');
  60. if (fs.existsSync(configFilePath)) {
  61. globalConfigCache = yaml.load(fs.readFileSync(configFilePath, 'utf-8'));
  62. } else {
  63. if (!fs.existsSync(configDir)) {
  64. fs.mkdirSync(configDir, { recursive: true });
  65. }
  66. globalConfigCache = { hasRun: false };
  67. fs.writeFileSync(configFilePath, yaml.dump(globalConfigCache));
  68. }
  69. }
  70. return globalConfigCache;
  71. }
  72. export function maybeRecordFirstRun(): boolean {
  73. // Return true if first run
  74. try {
  75. const config = readGlobalConfig();
  76. if (!config.hasRun) {
  77. config.hasRun = true;
  78. fs.writeFileSync(path.join(getConfigDirectoryPath(), 'promptfoo.yaml'), yaml.dump(config));
  79. return true;
  80. }
  81. return false;
  82. } catch (err) {
  83. return false;
  84. }
  85. }
  86. export async function maybeReadConfig(configPath: string): Promise<UnifiedConfig | undefined> {
  87. if (!fs.existsSync(configPath)) {
  88. return undefined;
  89. }
  90. return readConfig(configPath);
  91. }
  92. export async function dereferenceConfig(rawConfig: UnifiedConfig): Promise<UnifiedConfig> {
  93. if (process.env.PROMPTFOO_DISABLE_REF_PARSER) {
  94. return rawConfig;
  95. }
  96. // Track and delete tools[i].function for each tool, preserving the rest of the properties
  97. // https://github.com/promptfoo/promptfoo/issues/364
  98. // Remove parameters from functions and tools to prevent dereferencing
  99. const extractFunctionParameters = (functions: { parameters?: object }[]) => {
  100. return functions.map((func) => {
  101. const { parameters } = func;
  102. delete func.parameters;
  103. return { parameters };
  104. });
  105. };
  106. const extractToolParameters = (tools: { function?: { parameters?: object } }[]) => {
  107. return tools.map((tool) => {
  108. const { parameters } = tool.function || {};
  109. if (tool.function?.parameters) {
  110. delete tool.function.parameters;
  111. }
  112. return { parameters };
  113. });
  114. };
  115. // Restore parameters to functions and tools after dereferencing
  116. const restoreFunctionParameters = (
  117. functions: { parameters?: object }[],
  118. parametersList: { parameters?: object }[],
  119. ) => {
  120. functions.forEach((func, index) => {
  121. if (parametersList[index]?.parameters) {
  122. func.parameters = parametersList[index].parameters;
  123. }
  124. });
  125. };
  126. const restoreToolParameters = (
  127. tools: { function?: { parameters?: object } }[],
  128. parametersList: { parameters?: object }[],
  129. ) => {
  130. tools.forEach((tool, index) => {
  131. if (parametersList[index]?.parameters) {
  132. tool.function = tool.function || {};
  133. tool.function.parameters = parametersList[index].parameters;
  134. }
  135. });
  136. };
  137. let functionsParametersList: { parameters?: object }[][] = [];
  138. let toolsParametersList: { parameters?: object }[][] = [];
  139. if (Array.isArray(rawConfig.providers)) {
  140. rawConfig.providers.forEach((provider, providerIndex) => {
  141. if (typeof provider === 'string') return;
  142. if (!provider.config) {
  143. // Handle when provider is a map
  144. provider = Object.values(provider)[0] as ProviderOptions;
  145. }
  146. if (provider.config?.functions) {
  147. functionsParametersList[providerIndex] = extractFunctionParameters(
  148. provider.config.functions,
  149. );
  150. }
  151. if (provider.config?.tools) {
  152. toolsParametersList[providerIndex] = extractToolParameters(provider.config.tools);
  153. }
  154. });
  155. }
  156. // Dereference JSON
  157. const config = (await $RefParser.dereference(rawConfig)) as unknown as UnifiedConfig;
  158. // Restore functions and tools parameters
  159. if (Array.isArray(config.providers)) {
  160. config.providers.forEach((provider, index) => {
  161. if (typeof provider === 'string') return;
  162. if (!provider.config) {
  163. // Handle when provider is a map
  164. provider = Object.values(provider)[0] as ProviderOptions;
  165. }
  166. if (functionsParametersList[index]) {
  167. provider.config.functions = provider.config.functions || [];
  168. restoreFunctionParameters(provider.config.functions, functionsParametersList[index]);
  169. }
  170. if (toolsParametersList[index]) {
  171. provider.config.tools = provider.config.tools || [];
  172. restoreToolParameters(provider.config.tools, toolsParametersList[index]);
  173. }
  174. });
  175. }
  176. return config;
  177. }
  178. export async function readConfig(configPath: string): Promise<UnifiedConfig> {
  179. const ext = path.parse(configPath).ext;
  180. switch (ext) {
  181. case '.json':
  182. case '.yaml':
  183. case '.yml':
  184. let rawConfig = yaml.load(fs.readFileSync(configPath, 'utf-8')) as UnifiedConfig;
  185. return dereferenceConfig(rawConfig);
  186. case '.js':
  187. case '.cjs':
  188. case '.mjs':
  189. return (await importModule(configPath)) as UnifiedConfig;
  190. default:
  191. throw new Error(`Unsupported configuration file format: ${ext}`);
  192. }
  193. }
  194. /**
  195. * Reads multiple configuration files and combines them into a single UnifiedConfig.
  196. *
  197. * @param {string[]} configPaths - An array of paths to configuration files. Supports glob patterns.
  198. * @returns {Promise<UnifiedConfig>} A promise that resolves to a unified configuration object.
  199. */
  200. export async function readConfigs(configPaths: string[]): Promise<UnifiedConfig> {
  201. const configs: UnifiedConfig[] = [];
  202. for (const configPath of configPaths) {
  203. const globPaths = globSync(configPath, {
  204. windowsPathsNoEscape: true,
  205. });
  206. if (globPaths.length === 0) {
  207. throw new Error(`No configuration file found at ${configPath}`);
  208. }
  209. for (const globPath of globPaths) {
  210. const config = await readConfig(globPath);
  211. configs.push(config);
  212. }
  213. }
  214. const providers: UnifiedConfig['providers'] = [];
  215. const seenProviders = new Set<string>();
  216. configs.forEach((config) => {
  217. invariant(
  218. typeof config.providers !== 'function',
  219. 'Providers cannot be a function for multiple configs',
  220. );
  221. if (typeof config.providers === 'string') {
  222. if (!seenProviders.has(config.providers)) {
  223. providers.push(config.providers);
  224. seenProviders.add(config.providers);
  225. }
  226. } else if (Array.isArray(config.providers)) {
  227. config.providers.forEach((provider) => {
  228. if (!seenProviders.has(JSON.stringify(provider))) {
  229. providers.push(provider);
  230. seenProviders.add(JSON.stringify(provider));
  231. }
  232. });
  233. }
  234. });
  235. const tests: UnifiedConfig['tests'] = [];
  236. for (const config of configs) {
  237. if (typeof config.tests === 'string') {
  238. const newTests = await readTests(config.tests, path.dirname(configPaths[0]));
  239. tests.push(...newTests);
  240. } else if (Array.isArray(config.tests)) {
  241. tests.push(...config.tests);
  242. }
  243. }
  244. const configsAreStringOrArray = configs.every(
  245. (config) => typeof config.prompts === 'string' || Array.isArray(config.prompts),
  246. );
  247. const configsAreObjects = configs.every((config) => typeof config.prompts === 'object');
  248. let prompts: UnifiedConfig['prompts'] = configsAreStringOrArray ? [] : {};
  249. const makeAbsolute = (configPath: string, relativePath: string | Prompt) => {
  250. if (typeof relativePath === 'string') {
  251. if (relativePath.startsWith('file://')) {
  252. relativePath =
  253. 'file://' + path.resolve(path.dirname(configPath), relativePath.slice('file://'.length));
  254. }
  255. return relativePath;
  256. } else if (typeof relativePath === 'object' && relativePath.id) {
  257. if (relativePath.id.startsWith('file://')) {
  258. relativePath.id =
  259. 'file://' +
  260. path.resolve(path.dirname(configPath), relativePath.id.slice('file://'.length));
  261. }
  262. return relativePath;
  263. } else {
  264. throw new Error('Invalid prompt object');
  265. }
  266. };
  267. const seenPrompts = new Set<string>();
  268. const addSeenPrompt = (prompt: string | Prompt) => {
  269. if (typeof prompt === 'string') {
  270. seenPrompts.add(prompt);
  271. } else if (typeof prompt === 'object' && prompt.id) {
  272. seenPrompts.add(prompt.id);
  273. } else {
  274. throw new Error('Invalid prompt object');
  275. }
  276. };
  277. configs.forEach((config, idx) => {
  278. if (typeof config.prompts === 'string') {
  279. invariant(Array.isArray(prompts), 'Cannot mix string and map-type prompts');
  280. const absolutePrompt = makeAbsolute(configPaths[idx], config.prompts);
  281. addSeenPrompt(absolutePrompt);
  282. } else if (Array.isArray(config.prompts)) {
  283. invariant(Array.isArray(prompts), 'Cannot mix configs with map and array-type prompts');
  284. config.prompts
  285. .map((prompt) => makeAbsolute(configPaths[idx], prompt))
  286. .forEach((prompt) => addSeenPrompt(prompt));
  287. } else {
  288. // Object format such as { 'prompts/prompt1.txt': 'foo', 'prompts/prompt2.txt': 'bar' }
  289. invariant(typeof prompts === 'object', 'Cannot mix configs with map and array-type prompts');
  290. prompts = { ...prompts, ...config.prompts };
  291. }
  292. });
  293. if (Array.isArray(prompts)) {
  294. prompts.push(...Array.from(seenPrompts));
  295. }
  296. // Combine all configs into a single UnifiedConfig
  297. const combinedConfig: UnifiedConfig = {
  298. description: configs.map((config) => config.description).join(', '),
  299. providers,
  300. prompts,
  301. tests,
  302. scenarios: configs.flatMap((config) => config.scenarios || []),
  303. defaultTest: configs.reduce((prev: Partial<TestCase> | undefined, curr) => {
  304. return {
  305. ...prev,
  306. ...curr.defaultTest,
  307. vars: { ...prev?.vars, ...curr.defaultTest?.vars },
  308. assert: [...(prev?.assert || []), ...(curr.defaultTest?.assert || [])],
  309. options: { ...prev?.options, ...curr.defaultTest?.options },
  310. };
  311. }, {}),
  312. nunjucksFilters: configs.reduce((prev, curr) => ({ ...prev, ...curr.nunjucksFilters }), {}),
  313. env: configs.reduce((prev, curr) => ({ ...prev, ...curr.env }), {}),
  314. evaluateOptions: configs.reduce((prev, curr) => ({ ...prev, ...curr.evaluateOptions }), {}),
  315. commandLineOptions: configs.reduce(
  316. (prev, curr) => ({ ...prev, ...curr.commandLineOptions }),
  317. {},
  318. ),
  319. sharing: !configs.some((config) => config.sharing === false),
  320. };
  321. return combinedConfig;
  322. }
  323. export async function writeMultipleOutputs(
  324. outputPaths: string[],
  325. results: EvaluateSummary,
  326. config: Partial<UnifiedConfig>,
  327. shareableUrl: string | null,
  328. ) {
  329. await Promise.all(
  330. outputPaths.map((outputPath) => writeOutput(outputPath, results, config, shareableUrl)),
  331. );
  332. }
  333. export async function writeOutput(
  334. outputPath: string,
  335. results: EvaluateSummary,
  336. config: Partial<UnifiedConfig>,
  337. shareableUrl: string | null,
  338. ) {
  339. const outputExtension = outputPath.split('.').pop()?.toLowerCase();
  340. const outputToSimpleString = (output: EvaluateTableOutput) => {
  341. const passFailText = output.pass ? '[PASS]' : '[FAIL]';
  342. const namedScoresText = Object.entries(output.namedScores)
  343. .map(([name, value]) => `${name}: ${value.toFixed(2)}`)
  344. .join(', ');
  345. const scoreText =
  346. namedScoresText.length > 0
  347. ? `(${output.score.toFixed(2)}, ${namedScoresText})`
  348. : `(${output.score.toFixed(2)})`;
  349. const gradingResultText = output.gradingResult
  350. ? `${output.pass ? 'Pass' : 'Fail'} Reason: ${output.gradingResult.reason}`
  351. : '';
  352. return `${passFailText} ${scoreText}
  353. ${output.text}
  354. ${gradingResultText}`.trim();
  355. };
  356. if (outputPath.match(/^https:\/\/docs\.google\.com\/spreadsheets\//)) {
  357. const rows = results.table.body.map((row) => {
  358. const csvRow: CsvRow = {};
  359. results.table.head.vars.forEach((varName, index) => {
  360. csvRow[varName] = row.vars[index];
  361. });
  362. results.table.head.prompts.forEach((prompt, index) => {
  363. csvRow[prompt.label] = outputToSimpleString(row.outputs[index]);
  364. });
  365. return csvRow;
  366. });
  367. await writeCsvToGoogleSheet(rows, outputPath);
  368. } else {
  369. // Ensure the directory exists
  370. const outputDir = path.dirname(outputPath);
  371. if (!fs.existsSync(outputDir)) {
  372. fs.mkdirSync(outputDir, { recursive: true });
  373. }
  374. if (outputExtension === 'csv') {
  375. const csvOutput = stringify([
  376. [
  377. ...results.table.head.vars,
  378. ...results.table.head.prompts.map((prompt) => JSON.stringify(prompt)),
  379. ],
  380. ...results.table.body.map((row) => [...row.vars, ...row.outputs.map(outputToSimpleString)]),
  381. ]);
  382. fs.writeFileSync(outputPath, csvOutput);
  383. } else if (outputExtension === 'json') {
  384. fs.writeFileSync(
  385. outputPath,
  386. JSON.stringify({ results, config, shareableUrl } satisfies OutputFile, null, 2),
  387. );
  388. } else if (
  389. outputExtension === 'yaml' ||
  390. outputExtension === 'yml' ||
  391. outputExtension === 'txt'
  392. ) {
  393. fs.writeFileSync(outputPath, yaml.dump({ results, config, shareableUrl } as OutputFile));
  394. } else if (outputExtension === 'html') {
  395. const template = fs.readFileSync(`${getDirectory()}/tableOutput.html`, 'utf-8');
  396. const table = [
  397. [...results.table.head.vars, ...results.table.head.prompts.map((prompt) => prompt.label)],
  398. ...results.table.body.map((row) => [...row.vars, ...row.outputs.map(outputToSimpleString)]),
  399. ];
  400. const htmlOutput = getNunjucksEngine().renderString(template, {
  401. config,
  402. table,
  403. results: results.results,
  404. });
  405. fs.writeFileSync(outputPath, htmlOutput);
  406. } else {
  407. throw new Error(
  408. `Unsupported output file format ${outputExtension}, please use csv, txt, json, yaml, yml, html.`,
  409. );
  410. }
  411. }
  412. }
  413. export async function readOutput(outputPath: string): Promise<OutputFile> {
  414. const ext = path.parse(outputPath).ext.slice(1);
  415. switch (ext) {
  416. case 'json':
  417. return JSON.parse(fs.readFileSync(outputPath, 'utf-8')) as OutputFile;
  418. default:
  419. throw new Error(`Unsupported output file format: ${ext} currently only supports json`);
  420. }
  421. }
  422. let configDirectoryPath: string | undefined = process.env.PROMPTFOO_CONFIG_DIR;
  423. export function getConfigDirectoryPath(): string {
  424. return configDirectoryPath || path.join(os.homedir(), '.promptfoo');
  425. }
  426. export function setConfigDirectoryPath(newPath: string): void {
  427. configDirectoryPath = newPath;
  428. }
  429. /**
  430. * TODO(ian): Remove this
  431. * @deprecated Use readLatestResults directly instead.
  432. */
  433. export function getLatestResultsPath(): string {
  434. return path.join(getConfigDirectoryPath(), 'output', 'latest.json');
  435. }
  436. export async function writeResultsToDatabase(
  437. results: EvaluateSummary,
  438. config: Partial<UnifiedConfig>,
  439. createdAt?: Date,
  440. ): Promise<string> {
  441. createdAt = createdAt || (results.timestamp ? new Date(results.timestamp) : new Date());
  442. const evalId = `eval-${createdAt.toISOString().slice(0, 19)}`;
  443. const db = getDb();
  444. const promises = [];
  445. promises.push(
  446. db
  447. .insert(evals)
  448. .values({
  449. id: evalId,
  450. createdAt: createdAt.getTime(),
  451. description: config.description,
  452. config,
  453. results,
  454. })
  455. .onConflictDoNothing()
  456. .run(),
  457. );
  458. logger.debug(`Inserting eval ${evalId}`);
  459. // Record prompt relation
  460. for (const prompt of results.table.head.prompts) {
  461. const label = prompt.label || prompt.display || prompt.raw;
  462. const promptId = sha256(label);
  463. promises.push(
  464. db
  465. .insert(prompts)
  466. .values({
  467. id: promptId,
  468. prompt: label,
  469. })
  470. .onConflictDoNothing()
  471. .run(),
  472. );
  473. promises.push(
  474. db
  475. .insert(evalsToPrompts)
  476. .values({
  477. evalId,
  478. promptId,
  479. })
  480. .onConflictDoNothing()
  481. .run(),
  482. );
  483. logger.debug(`Inserting prompt ${promptId}`);
  484. }
  485. // Record dataset relation
  486. const datasetId = sha256(JSON.stringify(config.tests || []));
  487. promises.push(
  488. db
  489. .insert(datasets)
  490. .values({
  491. id: datasetId,
  492. tests: config.tests,
  493. })
  494. .onConflictDoNothing()
  495. .run(),
  496. );
  497. promises.push(
  498. db
  499. .insert(evalsToDatasets)
  500. .values({
  501. evalId,
  502. datasetId,
  503. })
  504. .onConflictDoNothing()
  505. .run(),
  506. );
  507. logger.debug(`Inserting dataset ${datasetId}`);
  508. logger.debug(`Awaiting ${promises.length} promises to database...`);
  509. await Promise.all(promises);
  510. // "touch" db signal path
  511. const filePath = getDbSignalPath();
  512. try {
  513. const now = new Date();
  514. fs.utimesSync(filePath, now, now);
  515. } catch (err) {
  516. fs.closeSync(fs.openSync(filePath, 'w'));
  517. }
  518. return evalId;
  519. }
  520. /**
  521. *
  522. * @returns Last n evals in descending order.
  523. */
  524. export function listPreviousResults(
  525. limit: number = DEFAULT_QUERY_LIMIT,
  526. filterDescription?: string,
  527. ): { evalId: string; description?: string | null }[] {
  528. const db = getDb();
  529. let results = db
  530. .select({
  531. name: evals.id,
  532. description: evals.description,
  533. })
  534. .from(evals)
  535. .orderBy(desc(evals.createdAt))
  536. .limit(limit)
  537. .all();
  538. if (filterDescription) {
  539. const regex = new RegExp(filterDescription, 'i');
  540. results = results.filter((result) => regex.test(result.description || ''));
  541. }
  542. return results.map((result) => ({
  543. evalId: result.name,
  544. description: result.description,
  545. }));
  546. }
  547. /**
  548. * @deprecated Used only for migration to sqlite
  549. */
  550. export function listPreviousResultFilenames_fileSystem(): string[] {
  551. const directory = path.join(getConfigDirectoryPath(), 'output');
  552. if (!fs.existsSync(directory)) {
  553. return [];
  554. }
  555. const files = fs.readdirSync(directory);
  556. const resultsFiles = files.filter((file) => file.startsWith('eval-') && file.endsWith('.json'));
  557. return resultsFiles.sort((a, b) => {
  558. const statA = fs.statSync(path.join(directory, a));
  559. const statB = fs.statSync(path.join(directory, b));
  560. return statA.birthtime.getTime() - statB.birthtime.getTime(); // sort in ascending order
  561. });
  562. }
  563. const resultsCache: { [fileName: string]: ResultsFile | undefined } = {};
  564. /**
  565. * @deprecated Used only for migration to sqlite
  566. */
  567. export function listPreviousResults_fileSystem(): { fileName: string; description?: string }[] {
  568. const directory = path.join(getConfigDirectoryPath(), 'output');
  569. if (!fs.existsSync(directory)) {
  570. return [];
  571. }
  572. const sortedFiles = listPreviousResultFilenames_fileSystem();
  573. return sortedFiles.map((fileName) => {
  574. if (!resultsCache[fileName]) {
  575. try {
  576. const fileContents = fs.readFileSync(path.join(directory, fileName), 'utf8');
  577. const data = yaml.load(fileContents) as ResultsFile;
  578. resultsCache[fileName] = data;
  579. } catch (error) {
  580. logger.warn(`Failed to read results from ${fileName}:\n${error}`);
  581. }
  582. }
  583. return {
  584. fileName,
  585. description: resultsCache[fileName]?.config.description,
  586. };
  587. });
  588. }
  589. let attemptedMigration = false;
  590. export async function migrateResultsFromFileSystemToDatabase() {
  591. if (attemptedMigration) {
  592. // TODO(ian): Record this bit in the database.
  593. return;
  594. }
  595. // First run db migrations
  596. logger.debug('Running db migrations...');
  597. await runDbMigrations();
  598. const fileNames = listPreviousResultFilenames_fileSystem();
  599. if (fileNames.length === 0) {
  600. return;
  601. }
  602. logger.info(`🔁 Migrating ${fileNames.length} flat files to local database.`);
  603. logger.info('This is a one-time operation and may take a minute...');
  604. attemptedMigration = true;
  605. const outputDir = path.join(getConfigDirectoryPath(), 'output');
  606. const backupDir = `${outputDir}-backup-${new Date()
  607. .toISOString()
  608. .slice(0, 10)
  609. .replace(/-/g, '')}`;
  610. try {
  611. fs.cpSync(outputDir, backupDir, { recursive: true });
  612. logger.info(`Backup of output directory created at ${backupDir}`);
  613. } catch (backupError) {
  614. logger.error(`Failed to create backup of output directory: ${backupError}`);
  615. return;
  616. }
  617. logger.info('Moving files into database...');
  618. const migrationPromises = fileNames.map(async (fileName) => {
  619. const fileData = readResult_fileSystem(fileName);
  620. if (fileData) {
  621. await writeResultsToDatabase(
  622. fileData.result.results,
  623. fileData.result.config,
  624. filenameToDate(fileName),
  625. );
  626. logger.debug(`Migrated ${fileName} to database.`);
  627. try {
  628. fs.unlinkSync(path.join(outputDir, fileName));
  629. } catch (err) {
  630. logger.warn(`Failed to delete ${fileName} after migration: ${err}`);
  631. }
  632. } else {
  633. logger.warn(`Failed to migrate result ${fileName} due to read error.`);
  634. }
  635. });
  636. await Promise.all(migrationPromises);
  637. try {
  638. fs.unlinkSync(getLatestResultsPath());
  639. } catch (err) {
  640. logger.warn(`Failed to delete latest.json: ${err}`);
  641. }
  642. logger.info('Migration complete. Please restart your web server if it is running.');
  643. }
  644. const RESULT_HISTORY_LENGTH =
  645. parseInt(process.env.RESULT_HISTORY_LENGTH || '', 10) || DEFAULT_QUERY_LIMIT;
  646. export function cleanupOldFileResults(remaining = RESULT_HISTORY_LENGTH) {
  647. const sortedFilenames = listPreviousResultFilenames_fileSystem();
  648. for (let i = 0; i < sortedFilenames.length - remaining; i++) {
  649. fs.unlinkSync(path.join(getConfigDirectoryPath(), 'output', sortedFilenames[i]));
  650. }
  651. }
  652. export function filenameToDate(filename: string) {
  653. const dateString = filename.slice('eval-'.length, filename.length - '.json'.length);
  654. // Replace hyphens with colons where necessary (Windows compatibility).
  655. const dateParts = dateString.split('T');
  656. const timePart = dateParts[1].replace(/-/g, ':');
  657. const formattedDateString = `${dateParts[0]}T${timePart}`;
  658. const date = new Date(formattedDateString);
  659. return date;
  660. /*
  661. return date.toLocaleDateString('en-US', {
  662. year: 'numeric',
  663. month: 'long',
  664. day: 'numeric',
  665. hour: '2-digit',
  666. minute: '2-digit',
  667. second: '2-digit',
  668. timeZoneName: 'short',
  669. });
  670. */
  671. }
  672. export function dateToFilename(date: Date) {
  673. return `eval-${date.toISOString().replace(/:/g, '-')}.json`;
  674. }
  675. export async function readResult(
  676. id: string,
  677. ): Promise<{ id: string; result: ResultsFile; createdAt: Date } | undefined> {
  678. const db = getDb();
  679. try {
  680. const evalResult = await db
  681. .select({
  682. id: evals.id,
  683. createdAt: evals.createdAt,
  684. results: evals.results,
  685. config: evals.config,
  686. })
  687. .from(evals)
  688. .where(eq(evals.id, id))
  689. .execute();
  690. if (evalResult.length === 0) {
  691. return undefined;
  692. }
  693. const { id: resultId, createdAt, results, config } = evalResult[0];
  694. const result: ResultsFile = {
  695. version: 3,
  696. createdAt: new Date(createdAt).toISOString().slice(0, 10),
  697. results,
  698. config,
  699. };
  700. return {
  701. id: resultId,
  702. result,
  703. createdAt: new Date(createdAt),
  704. };
  705. } catch (err) {
  706. logger.error(`Failed to read result with ID ${id} from database:\n${err}`);
  707. }
  708. }
  709. /**
  710. * @deprecated Used only for migration to sqlite
  711. */
  712. export function readResult_fileSystem(
  713. name: string,
  714. ): { id: string; result: ResultsFile; createdAt: Date } | undefined {
  715. const resultsDirectory = path.join(getConfigDirectoryPath(), 'output');
  716. const resultsPath = path.join(resultsDirectory, name);
  717. try {
  718. const result = JSON.parse(
  719. fs.readFileSync(fs.realpathSync(resultsPath), 'utf-8'),
  720. ) as ResultsFile;
  721. const createdAt = filenameToDate(name);
  722. return {
  723. id: sha256(JSON.stringify(result.config)),
  724. result,
  725. createdAt,
  726. };
  727. } catch (err) {
  728. logger.error(`Failed to read results from ${resultsPath}:\n${err}`);
  729. }
  730. }
  731. export async function updateResult(
  732. id: string,
  733. newConfig?: Partial<UnifiedConfig>,
  734. newTable?: EvaluateTable,
  735. ): Promise<void> {
  736. const db = getDb();
  737. try {
  738. // Fetch the existing eval data from the database
  739. const existingEval = await db
  740. .select({
  741. config: evals.config,
  742. results: evals.results,
  743. })
  744. .from(evals)
  745. .where(eq(evals.id, id))
  746. .limit(1)
  747. .all();
  748. if (existingEval.length === 0) {
  749. logger.error(`Eval with ID ${id} not found.`);
  750. return;
  751. }
  752. const evalData = existingEval[0];
  753. if (newConfig) {
  754. evalData.config = newConfig;
  755. }
  756. if (newTable) {
  757. evalData.results.table = newTable;
  758. }
  759. await db
  760. .update(evals)
  761. .set({
  762. description: evalData.config.description,
  763. config: evalData.config,
  764. results: evalData.results,
  765. })
  766. .where(eq(evals.id, id))
  767. .run();
  768. logger.info(`Updated eval with ID ${id}`);
  769. } catch (err) {
  770. logger.error(`Failed to update eval with ID ${id}:\n${err}`);
  771. }
  772. }
  773. export async function readLatestResults(
  774. filterDescription?: string,
  775. ): Promise<ResultsFile | undefined> {
  776. const db = getDb();
  777. let latestResults = await db
  778. .select({
  779. id: evals.id,
  780. createdAt: evals.createdAt,
  781. description: evals.description,
  782. results: evals.results,
  783. config: evals.config,
  784. })
  785. .from(evals)
  786. .orderBy(desc(evals.createdAt))
  787. .limit(1);
  788. if (filterDescription) {
  789. const regex = new RegExp(filterDescription, 'i');
  790. latestResults = latestResults.filter((result) => regex.test(result.description || ''));
  791. }
  792. if (!latestResults.length) {
  793. return undefined;
  794. }
  795. const latestResult = latestResults[0];
  796. return {
  797. version: 3,
  798. createdAt: new Date(latestResult.createdAt).toISOString(),
  799. results: latestResult.results,
  800. config: latestResult.config,
  801. };
  802. }
  803. export function getPromptsForTestCases(testCases: TestCase[]) {
  804. const testCasesJson = JSON.stringify(testCases);
  805. const testCasesSha256 = sha256(testCasesJson);
  806. return getPromptsForTestCasesHash(testCasesSha256);
  807. }
  808. export function getPromptsForTestCasesHash(
  809. testCasesSha256: string,
  810. limit: number = DEFAULT_QUERY_LIMIT,
  811. ) {
  812. return getPromptsWithPredicate((result) => {
  813. const testsJson = JSON.stringify(result.config.tests);
  814. const hash = sha256(testsJson);
  815. return hash === testCasesSha256;
  816. }, limit);
  817. }
  818. export function sha256(str: string) {
  819. return createHash('sha256').update(str).digest('hex');
  820. }
  821. export function getPrompts(limit: number = DEFAULT_QUERY_LIMIT) {
  822. return getPromptsWithPredicate(() => true, limit);
  823. }
  824. export async function getPromptsWithPredicate(
  825. predicate: (result: ResultsFile) => boolean,
  826. limit: number,
  827. ): Promise<PromptWithMetadata[]> {
  828. // TODO(ian): Make this use a proper database query
  829. const db = getDb();
  830. const evals_ = await db
  831. .select({
  832. id: evals.id,
  833. createdAt: evals.createdAt,
  834. results: evals.results,
  835. config: evals.config,
  836. })
  837. .from(evals)
  838. .limit(limit)
  839. .all();
  840. const groupedPrompts: { [hash: string]: PromptWithMetadata } = {};
  841. for (const eval_ of evals_) {
  842. const createdAt = new Date(eval_.createdAt).toISOString();
  843. const resultWrapper: ResultsFile = {
  844. version: 3,
  845. createdAt,
  846. results: eval_.results,
  847. config: eval_.config,
  848. };
  849. if (predicate(resultWrapper)) {
  850. for (const prompt of resultWrapper.results.table.head.prompts) {
  851. const promptId = sha256(prompt.raw);
  852. const datasetId = resultWrapper.config.tests
  853. ? sha256(JSON.stringify(resultWrapper.config.tests))
  854. : '-';
  855. if (promptId in groupedPrompts) {
  856. groupedPrompts[promptId].recentEvalDate = new Date(
  857. Math.max(
  858. groupedPrompts[promptId].recentEvalDate.getTime(),
  859. new Date(createdAt).getTime(),
  860. ),
  861. );
  862. groupedPrompts[promptId].count += 1;
  863. groupedPrompts[promptId].evals.push({
  864. id: eval_.id,
  865. datasetId,
  866. metrics: prompt.metrics,
  867. });
  868. } else {
  869. groupedPrompts[promptId] = {
  870. count: 1,
  871. id: promptId,
  872. prompt,
  873. recentEvalDate: new Date(createdAt),
  874. recentEvalId: eval_.id,
  875. evals: [
  876. {
  877. id: eval_.id,
  878. datasetId,
  879. metrics: prompt.metrics,
  880. },
  881. ],
  882. };
  883. }
  884. }
  885. }
  886. }
  887. return Object.values(groupedPrompts);
  888. }
  889. export async function getTestCases(limit: number = DEFAULT_QUERY_LIMIT) {
  890. return getTestCasesWithPredicate(() => true, limit);
  891. }
  892. export async function getTestCasesWithPredicate(
  893. predicate: (result: ResultsFile) => boolean,
  894. limit: number,
  895. ): Promise<TestCasesWithMetadata[]> {
  896. const db = getDb();
  897. const evals_ = await db
  898. .select({
  899. id: evals.id,
  900. createdAt: evals.createdAt,
  901. results: evals.results,
  902. config: evals.config,
  903. })
  904. .from(evals)
  905. .limit(limit)
  906. .all();
  907. const groupedTestCases: { [hash: string]: TestCasesWithMetadata } = {};
  908. for (const eval_ of evals_) {
  909. const createdAt = new Date(eval_.createdAt).toISOString();
  910. const resultWrapper: ResultsFile = {
  911. version: 3,
  912. createdAt,
  913. results: eval_.results,
  914. config: eval_.config,
  915. };
  916. const testCases = resultWrapper.config.tests;
  917. if (testCases && predicate(resultWrapper)) {
  918. const evalId = eval_.id;
  919. const datasetId = sha256(JSON.stringify(testCases));
  920. if (datasetId in groupedTestCases) {
  921. groupedTestCases[datasetId].recentEvalDate = new Date(
  922. Math.max(groupedTestCases[datasetId].recentEvalDate.getTime(), eval_.createdAt),
  923. );
  924. groupedTestCases[datasetId].count += 1;
  925. const newPrompts = resultWrapper.results.table.head.prompts.map((prompt) => ({
  926. id: sha256(prompt.raw),
  927. prompt,
  928. evalId,
  929. }));
  930. const promptsById: Record<string, TestCasesWithMetadataPrompt> = {};
  931. for (const prompt of groupedTestCases[datasetId].prompts.concat(newPrompts)) {
  932. if (!(prompt.id in promptsById)) {
  933. promptsById[prompt.id] = prompt;
  934. }
  935. }
  936. groupedTestCases[datasetId].prompts = Object.values(promptsById);
  937. } else {
  938. const newPrompts = resultWrapper.results.table.head.prompts.map((prompt) => ({
  939. id: sha256(prompt.raw),
  940. prompt,
  941. evalId,
  942. }));
  943. const promptsById: Record<string, TestCasesWithMetadataPrompt> = {};
  944. for (const prompt of newPrompts) {
  945. if (!(prompt.id in promptsById)) {
  946. promptsById[prompt.id] = prompt;
  947. }
  948. }
  949. groupedTestCases[datasetId] = {
  950. id: datasetId,
  951. count: 1,
  952. testCases,
  953. recentEvalDate: new Date(createdAt),
  954. recentEvalId: evalId,
  955. prompts: Object.values(promptsById),
  956. };
  957. }
  958. }
  959. }
  960. return Object.values(groupedTestCases);
  961. }
  962. export async function getPromptFromHash(hash: string) {
  963. const prompts = await getPrompts();
  964. for (const prompt of prompts) {
  965. if (prompt.id.startsWith(hash)) {
  966. return prompt;
  967. }
  968. }
  969. return undefined;
  970. }
  971. export async function getDatasetFromHash(hash: string) {
  972. const datasets = await getTestCases();
  973. for (const dataset of datasets) {
  974. if (dataset.id.startsWith(hash)) {
  975. return dataset;
  976. }
  977. }
  978. return undefined;
  979. }
  980. export async function getEvals(limit: number = DEFAULT_QUERY_LIMIT) {
  981. return getEvalsWithPredicate(() => true, limit);
  982. }
  983. export async function getEvalFromId(hash: string) {
  984. const evals_ = await getEvals();
  985. for (const eval_ of evals_) {
  986. if (eval_.id.startsWith(hash)) {
  987. return eval_;
  988. }
  989. }
  990. return undefined;
  991. }
  992. export async function getEvalsWithPredicate(
  993. predicate: (result: ResultsFile) => boolean,
  994. limit: number,
  995. ): Promise<EvalWithMetadata[]> {
  996. const db = getDb();
  997. const evals_ = await db
  998. .select({
  999. id: evals.id,
  1000. createdAt: evals.createdAt,
  1001. results: evals.results,
  1002. config: evals.config,
  1003. description: evals.description,
  1004. })
  1005. .from(evals)
  1006. .orderBy(desc(evals.createdAt))
  1007. .limit(limit)
  1008. .all();
  1009. const ret: EvalWithMetadata[] = [];
  1010. for (const eval_ of evals_) {
  1011. const createdAt = new Date(eval_.createdAt).toISOString();
  1012. const resultWrapper: ResultsFile = {
  1013. version: 3,
  1014. createdAt: createdAt,
  1015. results: eval_.results,
  1016. config: eval_.config,
  1017. };
  1018. if (predicate(resultWrapper)) {
  1019. const evalId = eval_.id;
  1020. ret.push({
  1021. id: evalId,
  1022. date: new Date(eval_.createdAt),
  1023. config: eval_.config,
  1024. results: eval_.results,
  1025. description: eval_.description || undefined,
  1026. });
  1027. }
  1028. }
  1029. return ret;
  1030. }
  1031. export async function deleteEval(evalId: string) {
  1032. const db = getDb();
  1033. await db.transaction(async () => {
  1034. // We need to clean up foreign keys first. We don't have onDelete: 'cascade' set on all these relationships.
  1035. await db.delete(evalsToPrompts).where(eq(evalsToPrompts.evalId, evalId)).run();
  1036. await db.delete(evalsToDatasets).where(eq(evalsToDatasets.evalId, evalId)).run();
  1037. // Finally, delete the eval record
  1038. const deletedIds = await db.delete(evals).where(eq(evals.id, evalId)).run();
  1039. if (deletedIds.changes === 0) {
  1040. throw new Error(`Eval with ID ${evalId} not found`);
  1041. }
  1042. });
  1043. }
  1044. export async function readFilters(filters: Record<string, string>): Promise<NunjucksFilterMap> {
  1045. const ret: NunjucksFilterMap = {};
  1046. const basePath = cliState.basePath || '';
  1047. for (const [name, filterPath] of Object.entries(filters)) {
  1048. const globPath = path.join(basePath, filterPath);
  1049. const filePaths = globSync(globPath, {
  1050. windowsPathsNoEscape: true,
  1051. });
  1052. for (const filePath of filePaths) {
  1053. const finalPath = path.resolve(filePath);
  1054. ret[name] = await importModule(finalPath);
  1055. }
  1056. }
  1057. return ret;
  1058. }
  1059. export function getNunjucksEngine(filters?: NunjucksFilterMap) {
  1060. if (process.env.PROMPTFOO_DISABLE_TEMPLATING) {
  1061. return {
  1062. renderString: (template: string) => template,
  1063. };
  1064. }
  1065. const env = nunjucks.configure({
  1066. autoescape: false,
  1067. });
  1068. if (filters) {
  1069. for (const [name, filter] of Object.entries(filters)) {
  1070. env.addFilter(name, filter);
  1071. }
  1072. }
  1073. return env;
  1074. }
  1075. export function printBorder() {
  1076. const border = '='.repeat((process.stdout.columns || 80) - 10);
  1077. logger.info(border);
  1078. }
  1079. export async function transformOutput(
  1080. codeOrFilepath: string,
  1081. output: string | object | undefined,
  1082. context: { vars?: Record<string, string | object | undefined>; prompt: Partial<Prompt> },
  1083. ) {
  1084. let postprocessFn;
  1085. if (codeOrFilepath.startsWith('file://')) {
  1086. const filePath = codeOrFilepath.slice('file://'.length);
  1087. if (
  1088. codeOrFilepath.endsWith('.js') ||
  1089. codeOrFilepath.endsWith('.cjs') ||
  1090. codeOrFilepath.endsWith('.mjs')
  1091. ) {
  1092. const requiredModule = await importModule(filePath);
  1093. if (typeof requiredModule === 'function') {
  1094. postprocessFn = requiredModule;
  1095. } else if (requiredModule.default && typeof requiredModule.default === 'function') {
  1096. postprocessFn = requiredModule.default;
  1097. } else {
  1098. throw new Error(
  1099. `Transform ${filePath} must export a function or have a default export as a function`,
  1100. );
  1101. }
  1102. } else if (codeOrFilepath.endsWith('.py')) {
  1103. postprocessFn = async (
  1104. output: string,
  1105. context: { vars: Record<string, string | object> },
  1106. ) => {
  1107. return runPython(filePath, 'get_transform', [output, context]);
  1108. };
  1109. } else {
  1110. throw new Error(`Unsupported transform file format: ${codeOrFilepath}`);
  1111. }
  1112. } else {
  1113. postprocessFn = new Function(
  1114. 'output',
  1115. 'context',
  1116. codeOrFilepath.includes('\n') ? codeOrFilepath : `return ${codeOrFilepath}`,
  1117. );
  1118. }
  1119. const ret = await Promise.resolve(postprocessFn(output, context));
  1120. if (ret == null) {
  1121. throw new Error(`Transform function did not return a value\n\n${codeOrFilepath}`);
  1122. }
  1123. return ret;
  1124. }
  1125. export function setupEnv(envPath: string | undefined) {
  1126. if (envPath) {
  1127. logger.info(`Loading environment variables from ${envPath}`);
  1128. dotenv.config({ path: envPath });
  1129. } else {
  1130. dotenv.config();
  1131. }
  1132. }
  1133. export type StandaloneEval = CompletedPrompt & {
  1134. evalId: string;
  1135. datasetId: string | null;
  1136. promptId: string | null;
  1137. };
  1138. export function getStandaloneEvals(limit: number = DEFAULT_QUERY_LIMIT): StandaloneEval[] {
  1139. const db = getDb();
  1140. const results = db
  1141. .select({
  1142. evalId: evals.id,
  1143. description: evals.description,
  1144. config: evals.config,
  1145. results: evals.results,
  1146. promptId: evalsToPrompts.promptId,
  1147. datasetId: evalsToDatasets.datasetId,
  1148. })
  1149. .from(evals)
  1150. .leftJoin(evalsToPrompts, eq(evals.id, evalsToPrompts.evalId))
  1151. .leftJoin(evalsToDatasets, eq(evals.id, evalsToDatasets.evalId))
  1152. .orderBy(desc(evals.createdAt))
  1153. .limit(limit)
  1154. .all();
  1155. const flatResults: StandaloneEval[] = [];
  1156. results.forEach((result) => {
  1157. const table = result.results.table;
  1158. table.head.prompts.forEach((col) => {
  1159. flatResults.push({
  1160. evalId: result.evalId,
  1161. promptId: result.promptId,
  1162. datasetId: result.datasetId,
  1163. ...col,
  1164. });
  1165. });
  1166. });
  1167. return flatResults;
  1168. }
  1169. export function providerToIdentifier(provider: TestCase['provider']): string | undefined {
  1170. if (isApiProvider(provider)) {
  1171. return provider.id();
  1172. } else if (isProviderOptions(provider)) {
  1173. return provider.id;
  1174. }
  1175. return provider;
  1176. }
  1177. export function varsMatch(
  1178. vars1: Record<string, string | string[] | object> | undefined,
  1179. vars2: Record<string, string | string[] | object> | undefined,
  1180. ) {
  1181. return deepEqual(vars1, vars2);
  1182. }
  1183. export function resultIsForTestCase(result: EvaluateResult, testCase: TestCase): boolean {
  1184. const providersMatch = testCase.provider
  1185. ? providerToIdentifier(testCase.provider) === providerToIdentifier(result.provider)
  1186. : true;
  1187. return varsMatch(testCase.vars, result.vars) && providersMatch;
  1188. }
  1189. export function safeJsonStringify(value: any, prettyPrint: boolean = false): string {
  1190. // Prevent circular references
  1191. const cache = new Set();
  1192. const space = prettyPrint ? 2 : undefined;
  1193. return JSON.stringify(
  1194. value,
  1195. (key, val) => {
  1196. if (typeof val === 'object' && val !== null) {
  1197. if (cache.has(val)) return;
  1198. cache.add(val);
  1199. }
  1200. return val;
  1201. },
  1202. space,
  1203. );
  1204. }
  1205. export function renderVarsInObject<T>(obj: T, vars?: Record<string, string | object>): T {
  1206. // Renders nunjucks template strings with context variables
  1207. if (!vars || process.env.PROMPTFOO_DISABLE_TEMPLATING) {
  1208. return obj;
  1209. }
  1210. if (typeof obj === 'string') {
  1211. return nunjucks.renderString(obj, vars) as unknown as T;
  1212. }
  1213. if (Array.isArray(obj)) {
  1214. return obj.map((item) => renderVarsInObject(item, vars)) as unknown as T;
  1215. }
  1216. if (typeof obj === 'object' && obj !== null) {
  1217. const result: Record<string, unknown> = {};
  1218. for (const key in obj) {
  1219. result[key] = renderVarsInObject((obj as Record<string, unknown>)[key], vars);
  1220. }
  1221. return result as T;
  1222. } else if (typeof obj === 'function') {
  1223. const fn = obj as Function;
  1224. return renderVarsInObject(fn({ vars }) as T);
  1225. }
  1226. return obj;
  1227. }
Tip!

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

Comments

Loading...