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
|
- import * as fs from 'fs';
- import dedent from 'dedent';
- import { globSync } from 'glob';
- import { importModule } from '../../src/esm';
- import { processPrompts, readPrompts, readProviderPromptMap } from '../../src/prompts';
- import { maybeFilePath } from '../../src/prompts/utils';
- import type { ApiProvider, Prompt, ProviderResponse, UnifiedConfig } from '../../src/types';
- jest.mock('proxy-agent', () => ({
- ProxyAgent: jest.fn().mockImplementation(() => ({})),
- }));
- jest.mock('glob', () => {
- const actual = jest.requireActual('glob');
- return {
- ...actual,
- globSync: jest.fn(actual.globSync),
- };
- });
- jest.mock('fs', () => {
- const actual = jest.requireActual('fs');
- return {
- ...actual,
- existsSync: jest.fn(actual.existsSync),
- mkdirSync: jest.fn(),
- readFileSync: jest.fn(),
- statSync: jest.fn(actual.statSync),
- writeFileSync: jest.fn(),
- };
- });
- jest.mock('python-shell');
- jest.mock('../../src/esm', () => {
- const actual = jest.requireActual('../../src/esm');
- return {
- ...actual,
- importModule: jest.fn(actual.importModule),
- };
- });
- jest.mock('../../src/python/wrapper');
- jest.mock('../../src/prompts/utils', () => {
- const actual = jest.requireActual('../../src/prompts/utils');
- return {
- ...actual,
- maybeFilePath: jest.fn(actual.maybeFilePath),
- };
- });
- describe('readPrompts', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- });
- afterEach(() => {
- delete process.env.PROMPTFOO_STRICT_FILES;
- jest.mocked(fs.readFileSync).mockReset();
- jest.mocked(fs.statSync).mockReset();
- jest.mocked(globSync).mockReset();
- jest.mocked(maybeFilePath).mockClear();
- });
- it('should throw an error for invalid inputs', async () => {
- await expect(readPrompts(null as any)).rejects.toThrow('Invalid input prompt: null');
- await expect(readPrompts(undefined as any)).rejects.toThrow('Invalid input prompt: undefined');
- await expect(readPrompts(1 as any)).rejects.toThrow('Invalid input prompt: 1');
- await expect(readPrompts(true as any)).rejects.toThrow('Invalid input prompt: true');
- await expect(readPrompts(false as any)).rejects.toThrow('Invalid input prompt: false');
- });
- it('should throw an error for empty inputs', async () => {
- await expect(readPrompts([])).rejects.toThrow('Invalid input prompt: []');
- await expect(readPrompts({} as any)).rejects.toThrow('Invalid input prompt: {}');
- await expect(readPrompts('')).rejects.toThrow('Invalid input prompt: ""');
- });
- it('should throw an error when PROMPTFOO_STRICT_FILES is true and the file does not exist', async () => {
- process.env.PROMPTFOO_STRICT_FILES = 'true';
- jest.mocked(fs.statSync).mockReturnValueOnce({ isDirectory: () => false } as fs.Stats);
- jest.mocked(fs.readFileSync).mockImplementationOnce(() => {
- throw new Error("ENOENT: no such file or directory, stat 'non-existent-file.txt'");
- });
- await expect(readPrompts('non-existent-file.txt')).rejects.toThrow(
- expect.objectContaining({
- message: expect.stringMatching(
- /ENOENT: no such file or directory, stat '.*non-existent-file.txt'/,
- ),
- }),
- );
- });
- it('should throw an error for a .txt file with no prompts', async () => {
- jest.mocked(fs.readFileSync).mockReturnValueOnce('');
- jest.mocked(fs.statSync).mockReturnValueOnce({ isDirectory: () => false } as fs.Stats);
- jest.mocked(maybeFilePath).mockReturnValueOnce(true);
- process.env.PROMPTFOO_STRICT_FILES = 'true';
- await expect(readPrompts(['prompts.txt'])).rejects.toThrow(
- 'There are no prompts in "prompts.txt"',
- );
- expect(fs.readFileSync).toHaveBeenCalledTimes(1);
- });
- it('should throw an error for an unsupported file format', async () => {
- jest.mocked(fs.statSync).mockReturnValueOnce({ isDirectory: () => false } as fs.Stats);
- jest.mocked(maybeFilePath).mockReturnValueOnce(true);
- process.env.PROMPTFOO_STRICT_FILES = 'true';
- await expect(readPrompts(['unsupported.for.mat'])).rejects.toThrow(
- 'There are no prompts in "unsupported.for.mat"',
- );
- expect(fs.readFileSync).toHaveBeenCalledTimes(0);
- });
- it('should read a single prompt', async () => {
- const prompt = 'This is a test prompt';
- await expect(readPrompts(prompt)).resolves.toEqual([
- {
- raw: prompt,
- label: prompt,
- },
- ]);
- });
- it('should read a list of prompts', async () => {
- const prompts = ['Sample prompt A', 'Sample prompt B'];
- await expect(readPrompts(prompts)).resolves.toEqual([
- {
- raw: 'Sample prompt A',
- label: 'Sample prompt A',
- },
- {
- raw: 'Sample prompt B',
- label: 'Sample prompt B',
- },
- ]);
- });
- it('should read a .txt file with a single prompt', async () => {
- jest.mocked(fs.readFileSync).mockReturnValueOnce('Sample Prompt');
- jest.mocked(fs.statSync).mockReturnValueOnce({ isDirectory: () => false } as fs.Stats);
- await expect(readPrompts('prompts.txt')).resolves.toEqual([
- {
- label: 'prompts.txt: Sample Prompt',
- raw: 'Sample Prompt',
- },
- ]);
- expect(fs.readFileSync).toHaveBeenCalledTimes(1);
- });
- it.each([['prompts.txt'], 'prompts.txt'])(
- `should read a single prompt file with input:%p`,
- async (promptPath) => {
- jest.mocked(fs.statSync).mockReturnValueOnce({ isDirectory: () => false } as fs.Stats);
- jest.mocked(fs.readFileSync).mockReturnValue('Test prompt 1\n---\nTest prompt 2');
- jest.mocked(globSync).mockImplementation((pathOrGlob) => [pathOrGlob.toString()]);
- await expect(readPrompts(promptPath)).resolves.toEqual([
- {
- label: 'prompts.txt: Test prompt 1',
- raw: 'Test prompt 1',
- },
- {
- label: 'prompts.txt: Test prompt 2',
- raw: 'Test prompt 2',
- },
- ]);
- expect(fs.readFileSync).toHaveBeenCalledTimes(1);
- },
- );
- it('should read multiple prompt files', async () => {
- jest.mocked(fs.readFileSync).mockImplementation((filePath) => {
- if (filePath.toString().endsWith('prompt1.txt')) {
- return 'Test prompt 1\n---\nTest prompt 2';
- } else if (filePath.toString().endsWith('prompt2.txt')) {
- return 'Test prompt 3\n---\nTest prompt 4\n---\nTest prompt 5';
- }
- throw new Error(`Unexpected file path in test: ${filePath}`);
- });
- jest.mocked(fs.statSync).mockReturnValue({ isDirectory: () => false } as fs.Stats);
- jest.mocked(globSync).mockImplementation((pathOrGlob) => [pathOrGlob.toString()]);
- await expect(readPrompts(['prompt1.txt', 'prompt2.txt'])).resolves.toEqual([
- {
- label: 'prompt1.txt: Test prompt 1',
- raw: 'Test prompt 1',
- },
- {
- label: 'prompt1.txt: Test prompt 2',
- raw: 'Test prompt 2',
- },
- {
- label: 'prompt2.txt: Test prompt 3',
- raw: 'Test prompt 3',
- },
- {
- label: 'prompt2.txt: Test prompt 4',
- raw: 'Test prompt 4',
- },
- {
- label: 'prompt2.txt: Test prompt 5',
- raw: 'Test prompt 5',
- },
- ]);
- expect(fs.readFileSync).toHaveBeenCalledTimes(2);
- });
- it('should read with map input', async () => {
- jest.mocked(fs.readFileSync).mockReturnValue('some raw text');
- jest.mocked(fs.statSync).mockReturnValue({ isDirectory: () => false } as fs.Stats);
- await expect(
- readPrompts({
- 'prompts.txt': 'foo1',
- 'prompts2.txt': 'foo2',
- }),
- ).resolves.toEqual([
- { raw: 'some raw text', label: 'foo1: prompts.txt: some raw text' },
- { raw: 'some raw text', label: 'foo2: prompts2.txt: some raw text' },
- ]);
- expect(fs.readFileSync).toHaveBeenCalledTimes(2);
- });
- it('should read a .json file', async () => {
- const mockJsonContent = JSON.stringify([
- { name: 'You are a helpful assistant', role: 'system' },
- { name: 'How do I get to the moon?', role: 'user' },
- ]);
- jest.mocked(fs.readFileSync).mockReturnValueOnce(mockJsonContent);
- jest.mocked(fs.statSync).mockReturnValueOnce({ isDirectory: () => false } as fs.Stats);
- const filePath = 'file://path/to/mock.json';
- await expect(readPrompts([filePath])).resolves.toEqual([
- {
- raw: mockJsonContent,
- label: expect.stringContaining(`mock.json: ${mockJsonContent}`),
- },
- ]);
- expect(fs.readFileSync).toHaveBeenCalledWith(expect.stringContaining('mock.json'), 'utf8');
- expect(fs.statSync).toHaveBeenCalledTimes(1);
- });
- it('should read a .jsonl file', async () => {
- const data = [
- [
- { role: 'system', content: 'You are a helpful assistant.' },
- { role: 'user', content: 'Who won the world series in {{ year }}?' },
- ],
- [
- { role: 'system', content: 'You are a helpful assistant.' },
- { role: 'user', content: 'Who won the superbowl in {{ year }}?' },
- ],
- ];
- jest.mocked(fs.readFileSync).mockReturnValueOnce(data.map((o) => JSON.stringify(o)).join('\n'));
- jest.mocked(fs.statSync).mockReturnValue({ isDirectory: () => false } as fs.Stats);
- await expect(readPrompts(['prompts.jsonl'])).resolves.toEqual([
- {
- raw: JSON.stringify(data[0]),
- label: `prompts.jsonl: ${JSON.stringify(data[0])}`,
- },
- {
- raw: JSON.stringify(data[1]),
- label: `prompts.jsonl: ${JSON.stringify(data[1])}`,
- },
- ]);
- expect(fs.readFileSync).toHaveBeenCalledTimes(1);
- });
- const yamlContent = dedent`
- - role: user
- content:
- - type: text
- text: "What's in this image?"
- - type: image_url
- image_url:
- url: "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"`;
- it('should read a .yaml file', async () => {
- const expectedJson = JSON.stringify([
- {
- role: 'user',
- content: [
- { type: 'text', text: "What's in this image?" },
- {
- type: 'image_url',
- image_url: {
- url: 'https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg',
- },
- },
- ],
- },
- ]);
- jest.mocked(fs.readFileSync).mockReturnValueOnce(yamlContent);
- jest.mocked(fs.statSync).mockReturnValueOnce({ isDirectory: () => false } as fs.Stats);
- await expect(readPrompts('prompts.yaml')).resolves.toEqual([
- {
- raw: expectedJson,
- label: expect.stringContaining(
- 'prompts.yaml: [{"role":"user","content":[{"type":"text","text":"What\'s in this image?"}',
- ),
- config: undefined,
- },
- ]);
- });
- it('should read a .yml file', async () => {
- const expectedJson = JSON.stringify([
- {
- role: 'user',
- content: [
- { type: 'text', text: "What's in this image?" },
- {
- type: 'image_url',
- image_url: {
- url: 'https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg',
- },
- },
- ],
- },
- ]);
- jest.mocked(fs.readFileSync).mockReturnValueOnce(yamlContent);
- jest.mocked(fs.statSync).mockReturnValueOnce({ isDirectory: () => false } as fs.Stats);
- await expect(readPrompts('image-summary.yml')).resolves.toEqual([
- {
- raw: expectedJson,
- label: expect.stringContaining(
- 'image-summary.yml: [{"role":"user","content":[{"type":"text","text":"What\'s in this image?"}',
- ),
- config: undefined,
- },
- ]);
- });
- it('should read a markdown file', async () => {
- const mdContent = '# Test Heading\n\nThis is a test markdown file.';
- jest.mocked(fs.readFileSync).mockReturnValueOnce(mdContent);
- jest.mocked(fs.statSync).mockReturnValueOnce({ isDirectory: () => false } as fs.Stats);
- jest.mocked(maybeFilePath).mockReturnValueOnce(true);
- await expect(readPrompts('test.md')).resolves.toEqual([
- {
- raw: mdContent,
- label: 'test.md: # Test Heading\n\nThis is a test markdown file....',
- },
- ]);
- expect(fs.readFileSync).toHaveBeenCalledTimes(1);
- expect(fs.readFileSync).toHaveBeenCalledWith('test.md', 'utf8');
- });
- it('should read a Jinja2 file', async () => {
- const jinjaContent =
- 'You are a helpful assistant.\nPlease answer the following question about {{ topic }}: {{ question }}';
- jest.mocked(fs.readFileSync).mockReturnValueOnce(jinjaContent);
- jest.mocked(fs.statSync).mockReturnValueOnce({ isDirectory: () => false } as fs.Stats);
- jest.mocked(maybeFilePath).mockReturnValueOnce(true);
- const result = await readPrompts('template.j2');
- // Check that we get a result with the right content
- expect(result).toHaveLength(1);
- expect(result[0].raw).toEqual(jinjaContent);
- expect(result[0].config).toBeUndefined();
- // Check that the label contains the expected text but don't test exact truncation
- expect(result[0].label).toContain('template.j2: You are a helpful assistant.');
- expect(fs.readFileSync).toHaveBeenCalledTimes(1);
- expect(fs.readFileSync).toHaveBeenCalledWith('template.j2', 'utf8');
- });
- it('should read a .py prompt object array', async () => {
- const prompts = [
- { id: 'prompts.py:prompt1', label: 'First prompt' },
- { id: 'prompts.py:prompt2', label: 'Second prompt' },
- ];
- const code = dedent`
- def prompt1:
- return 'First prompt'
- def prompt2:
- return 'Second prompt'
- `;
- jest.mocked(fs.readFileSync).mockReturnValue(code);
- await expect(readPrompts(prompts)).resolves.toEqual([
- {
- raw: code,
- label: 'First prompt',
- function: expect.any(Function),
- },
- {
- raw: code,
- label: 'Second prompt',
- function: expect.any(Function),
- },
- ]);
- expect(fs.readFileSync).toHaveBeenCalledTimes(2);
- });
- it('should read a .py file', async () => {
- const code = `print('dummy prompt')`;
- jest.mocked(fs.readFileSync).mockReturnValue(code);
- await expect(readPrompts('prompt.py')).resolves.toEqual([
- {
- function: expect.any(Function),
- label: `prompt.py: ${code}`,
- raw: code,
- },
- ]);
- expect(fs.readFileSync).toHaveBeenCalledTimes(1);
- });
- it('should read a .js file without named function', async () => {
- const promptPath = 'prompt.js';
- const mockFunction = () => console.log('dummy prompt');
- jest.mocked(importModule).mockResolvedValueOnce(mockFunction);
- jest.mocked(fs.statSync).mockReturnValue({ isDirectory: () => false } as fs.Stats);
- await expect(readPrompts(promptPath)).resolves.toEqual([
- {
- raw: "()=>console.log('dummy prompt')",
- label: 'prompt.js',
- function: expect.any(Function),
- config: {},
- },
- ]);
- expect(importModule).toHaveBeenCalledWith(promptPath, undefined);
- expect(fs.statSync).toHaveBeenCalledTimes(1);
- });
- it('should read a .js file with named function', async () => {
- const promptPath = 'prompt.js:functionName';
- const mockFunction = (context: {
- vars: Record<string, string | object>;
- provider?: ApiProvider;
- }) => 'dummy prompt result';
- jest.mocked(importModule).mockResolvedValueOnce(mockFunction);
- jest.mocked(fs.statSync).mockReturnValue({ isDirectory: () => false } as fs.Stats);
- const result = await readPrompts(promptPath);
- expect(result).toEqual([
- {
- raw: String(mockFunction),
- label: 'prompt.js:functionName',
- function: expect.any(Function),
- config: {},
- },
- ]);
- const promptFunction = result[0].function as unknown as (context: {
- vars: Record<string, string | object>;
- provider?: ApiProvider;
- }) => string;
- expect(promptFunction({ vars: {}, provider: { id: () => 'foo' } as ApiProvider })).toBe(
- 'dummy prompt result',
- );
- expect(importModule).toHaveBeenCalledWith('prompt.js', 'functionName');
- expect(fs.statSync).toHaveBeenCalledTimes(1);
- });
- it('should read a directory', async () => {
- jest.mocked(fs.statSync).mockImplementation((filePath) => {
- if (filePath.toString().endsWith('prompt1.txt')) {
- return { isDirectory: () => false } as fs.Stats;
- } else if (filePath.toString().endsWith('prompts')) {
- return { isDirectory: () => true } as fs.Stats;
- }
- throw new Error(`Unexpected file path in test: ${filePath}`);
- });
- jest.mocked(globSync).mockImplementation(() => ['prompt1.txt', 'prompt2.txt']);
- // The mocked paths here are an artifact of our globSync mock. In a real
- // world setting we would get back `prompts/prompt1.txt` instead of `prompts/*/prompt1.txt`
- // but for the sake of this test we are just going to pretend that the globSync
- // mock is doing the right thing and giving us back the right paths.
- jest.mocked(fs.readFileSync).mockImplementation((filePath) => {
- if (
- filePath.toString().endsWith('prompt1.txt') ||
- filePath.toString().endsWith('*/prompt1.txt')
- ) {
- return 'Test prompt 1\n---\nTest prompt 2';
- } else if (
- filePath.toString().endsWith('prompt2.txt') ||
- filePath.toString().endsWith('*/prompt2.txt')
- ) {
- return 'Test prompt 3\n---\nTest prompt 4\n---\nTest prompt 5';
- }
- throw new Error(`Unexpected file path in test: ${filePath}`);
- });
- await expect(readPrompts(['prompts/*'])).resolves.toEqual([
- {
- label: expect.stringMatching('prompt1.txt: Test prompt 1'),
- raw: 'Test prompt 1',
- },
- {
- label: expect.stringMatching('prompt1.txt: Test prompt 2'),
- raw: 'Test prompt 2',
- },
- {
- label: expect.stringMatching('prompt2.txt: Test prompt 3'),
- raw: 'Test prompt 3',
- },
- {
- label: expect.stringMatching('prompt2.txt: Test prompt 4'),
- raw: 'Test prompt 4',
- },
- {
- label: expect.stringMatching('prompt2.txt: Test prompt 5'),
- raw: 'Test prompt 5',
- },
- ]);
- expect(fs.readFileSync).toHaveBeenCalledTimes(2);
- expect(fs.statSync).toHaveBeenCalledTimes(3);
- });
- it('should fall back to a string if maybeFilePath is true but a file does not exist', async () => {
- jest.mocked(globSync).mockReturnValueOnce([]);
- jest.mocked(maybeFilePath).mockReturnValueOnce(true);
- await expect(readPrompts('non-existent-file.txt*')).resolves.toEqual([
- { raw: 'non-existent-file.txt*', label: 'non-existent-file.txt*' },
- ]);
- });
- it('should handle a prompt with a function', async () => {
- const promptWithFunction: Partial<Prompt> = {
- raw: 'dummy raw text',
- label: 'Function Prompt',
- function: jest.fn().mockResolvedValue('Hello, world!'),
- };
- await expect(readPrompts([promptWithFunction])).resolves.toEqual([
- {
- raw: 'dummy raw text',
- label: 'Function Prompt',
- function: expect.any(Function),
- },
- ]);
- expect(promptWithFunction.function).not.toHaveBeenCalled();
- });
- it('should read a single-column CSV file with header', async () => {
- const csvContent = dedent`
- prompt
- Tell me about {{topic}}
- Explain {{topic}} in simple terms
- Write a poem about {{topic}}
- `;
- jest.mocked(fs.readFileSync).mockReturnValueOnce(csvContent);
- jest.mocked(fs.statSync).mockReturnValueOnce({ isDirectory: () => false } as fs.Stats);
- const result = await readPrompts(['test.csv']);
- expect(result).toHaveLength(3);
- expect(result[0]).toEqual({
- raw: 'Tell me about {{topic}}',
- label: 'Prompt 1 - Tell me about {{topic}}',
- });
- expect(result[1]).toEqual({
- raw: 'Explain {{topic}} in simple terms',
- label: 'Prompt 2 - Explain {{topic}} in simple terms',
- });
- expect(result[2]).toEqual({
- raw: 'Write a poem about {{topic}}',
- label: 'Prompt 3 - Write a poem about {{topic}}',
- });
- });
- it('should read a single-column CSV file without header', async () => {
- const csvContent = dedent`
- Tell me about {{topic}}
- Explain {{topic}} in simple terms
- Write a poem about {{topic}}
- `;
- jest.mocked(fs.readFileSync).mockReturnValueOnce(csvContent);
- jest.mocked(fs.statSync).mockReturnValueOnce({ isDirectory: () => false } as fs.Stats);
- const result = await readPrompts(['test.csv']);
- expect(result).toHaveLength(3);
- expect(result[0]).toEqual({
- raw: 'Tell me about {{topic}}',
- label: 'Prompt 1 - Tell me about {{topic}}',
- });
- expect(result[1]).toEqual({
- raw: 'Explain {{topic}} in simple terms',
- label: 'Prompt 2 - Explain {{topic}} in simple terms',
- });
- expect(result[2]).toEqual({
- raw: 'Write a poem about {{topic}}',
- label: 'Prompt 3 - Write a poem about {{topic}}',
- });
- });
- it('should read a two-column CSV file with prompt and label', async () => {
- const csvContent = dedent`
- prompt,label
- Tell me about {{topic}},Basic Query
- Explain {{topic}} in simple terms,Simple Explanation
- Write a poem about {{topic}},Poetry Generator
- `;
- jest.mocked(fs.readFileSync).mockReturnValueOnce(csvContent);
- jest.mocked(fs.statSync).mockReturnValueOnce({ isDirectory: () => false } as fs.Stats);
- const result = await readPrompts(['test.csv']);
- expect(result).toHaveLength(3);
- expect(result[0]).toEqual({
- raw: 'Tell me about {{topic}}',
- label: 'Basic Query',
- });
- expect(result[1]).toEqual({
- raw: 'Explain {{topic}} in simple terms',
- label: 'Simple Explanation',
- });
- expect(result[2]).toEqual({
- raw: 'Write a poem about {{topic}}',
- label: 'Poetry Generator',
- });
- });
- });
- describe('readProviderPromptMap', () => {
- let config: Partial<UnifiedConfig>;
- let parsedPrompts: Prompt[];
- beforeEach(() => {
- jest.clearAllMocks();
- parsedPrompts = [
- { label: 'prompt1', raw: 'prompt1' },
- { label: 'prompt2', raw: 'prompt2' },
- ];
- });
- it('should return an empty object if config.providers is undefined', () => {
- config = {};
- expect(readProviderPromptMap(config, parsedPrompts)).toEqual({});
- });
- it('should return a map with all prompts if config.providers is a string', () => {
- config = { providers: 'provider1' };
- expect(readProviderPromptMap(config, parsedPrompts)).toEqual({
- provider1: ['prompt1', 'prompt2'],
- });
- });
- it('should return a map with all prompts if config.providers is a function', () => {
- config = {
- providers: () =>
- Promise.resolve({
- providerName: 'Custom function',
- prompts: ['prompt1', 'prompt2'],
- }) as Promise<ProviderResponse>,
- };
- expect(readProviderPromptMap(config, parsedPrompts)).toEqual({
- 'Custom function': ['prompt1', 'prompt2'],
- });
- });
- it('should handle provider objects with id and prompts', () => {
- config = {
- providers: [{ id: 'provider1', prompts: ['customPrompt1'] }],
- };
- expect(readProviderPromptMap(config, parsedPrompts)).toEqual({ provider1: ['customPrompt1'] });
- });
- it('should handle provider objects with id, label, and prompts', () => {
- config = {
- providers: [{ id: 'provider1', label: 'providerLabel', prompts: ['customPrompt1'] }],
- };
- expect(readProviderPromptMap(config, parsedPrompts)).toEqual({
- provider1: ['customPrompt1'],
- providerLabel: ['customPrompt1'],
- });
- });
- it('should handle provider options map with id and prompts', () => {
- config = {
- providers: [
- {
- originalProvider: {
- id: 'provider1',
- prompts: ['customPrompt1'],
- },
- },
- ],
- };
- expect(readProviderPromptMap(config, parsedPrompts)).toEqual({ provider1: ['customPrompt1'] });
- });
- it('should handle provider options map without id and use original id', () => {
- config = {
- providers: [
- {
- originalProvider: {
- prompts: ['customPrompt1'],
- },
- },
- ],
- };
- expect(readProviderPromptMap(config, parsedPrompts)).toEqual({
- originalProvider: ['customPrompt1'],
- });
- });
- it('should use rawProvider.prompts if provided for provider objects with id', () => {
- config = {
- providers: [{ id: 'provider1', prompts: ['customPrompt1'] }],
- };
- expect(readProviderPromptMap(config, parsedPrompts)).toEqual({ provider1: ['customPrompt1'] });
- });
- it('should fall back to allPrompts if no prompts provided for provider objects with id', () => {
- config = {
- providers: [{ id: 'provider1' }],
- };
- expect(readProviderPromptMap(config, parsedPrompts)).toEqual({
- provider1: ['prompt1', 'prompt2'],
- });
- });
- it('should use rawProvider.prompts for both id and label if provided', () => {
- config = {
- providers: [{ id: 'provider1', label: 'providerLabel', prompts: ['customPrompt1'] }],
- };
- expect(readProviderPromptMap(config, parsedPrompts)).toEqual({
- provider1: ['customPrompt1'],
- providerLabel: ['customPrompt1'],
- });
- });
- it('should fall back to allPrompts for both id and label if no prompts provided', () => {
- config = {
- providers: [{ id: 'provider1', label: 'providerLabel' }],
- };
- expect(readProviderPromptMap(config, parsedPrompts)).toEqual({
- provider1: ['prompt1', 'prompt2'],
- providerLabel: ['prompt1', 'prompt2'],
- });
- });
- it('should use providerObject.id from ProviderOptionsMap when provided', () => {
- config = {
- providers: [
- {
- originalProvider: {
- id: 'explicitId',
- prompts: ['customPrompt1'],
- },
- },
- ],
- };
- expect(readProviderPromptMap(config, parsedPrompts)).toEqual({ explicitId: ['customPrompt1'] });
- });
- it('should fallback to originalId when providerObject.id is not specified in ProviderOptionsMap', () => {
- config = {
- providers: [
- {
- originalProvider: {
- // 'originalProvider' is treated as originalId
- prompts: ['customPrompt1'],
- },
- },
- ],
- };
- expect(readProviderPromptMap(config, parsedPrompts)).toEqual({
- originalProvider: ['customPrompt1'],
- });
- });
- });
- describe('processPrompts', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- });
- it('should process function prompts', async () => {
- function testFunction(vars: any) {
- return `Hello ${vars.name}`;
- }
- const result = await processPrompts([testFunction]);
- expect(result).toEqual([
- {
- raw: testFunction.toString(),
- label: 'testFunction',
- function: testFunction,
- },
- ]);
- });
- it('should process function prompts with no name', async () => {
- function promptFn(vars: any) {
- return `Hello ${vars.name}`;
- }
- Object.defineProperty(promptFn, 'name', { value: '' });
- const result = await processPrompts([promptFn]);
- expect(result).toEqual([
- {
- raw: promptFn.toString(),
- label: '',
- function: expect.any(Function),
- },
- ]);
- expect(fs.readFileSync).toHaveBeenCalledTimes(0);
- });
- it('should process string prompts by calling readPrompts', async () => {
- jest.mocked(fs.readFileSync).mockReturnValueOnce('test prompt');
- jest.mocked(fs.statSync).mockReturnValueOnce({ isDirectory: () => false } as fs.Stats);
- const result = await processPrompts(['test.txt']);
- expect(result).toEqual([
- {
- raw: 'test prompt',
- label: 'test.txt: test prompt',
- },
- ]);
- });
- it('should process Jinja2 files', async () => {
- const jinjaContent =
- 'You are a helpful assistant for {{ user }}.\nPlease provide information about {{ topic }}.';
- jest.mocked(fs.readFileSync).mockReturnValueOnce(jinjaContent);
- jest.mocked(fs.statSync).mockReturnValueOnce({ isDirectory: () => false } as fs.Stats);
- jest.mocked(maybeFilePath).mockReturnValueOnce(true);
- const result = await processPrompts(['template.j2']);
- // Check that we get a result with the right content
- expect(result).toHaveLength(1);
- expect(result[0].raw).toEqual(jinjaContent);
- expect(result[0].config).toBeUndefined();
- // Check that the label contains the expected text but don't test exact truncation
- expect(result[0].label).toContain('template.j2: You are a helpful assistant for {{ user }}.');
- expect(fs.readFileSync).toHaveBeenCalledTimes(1);
- expect(fs.readFileSync).toHaveBeenCalledWith('template.j2', 'utf8');
- });
- it('should process valid prompt schema objects', async () => {
- const validPrompt = {
- raw: 'test prompt',
- label: 'test label',
- };
- const result = await processPrompts([validPrompt]);
- expect(result).toEqual([validPrompt]);
- });
- it('should fall back to JSON serialization for invalid prompt schema objects', async () => {
- const invalidPrompt = {
- invalidField: 'some value',
- anotherField: 123,
- };
- const result = await processPrompts([invalidPrompt]);
- expect(result).toEqual([
- {
- raw: JSON.stringify(invalidPrompt),
- label: JSON.stringify(invalidPrompt),
- },
- ]);
- });
- it('should process multiple prompts of different types', async () => {
- function testFunction(vars: any) {
- return `Hello ${vars.name}`;
- }
- const validPrompt = {
- raw: 'test prompt',
- label: 'test label',
- };
- jest.mocked(fs.readFileSync).mockReturnValueOnce('file prompt');
- jest.mocked(fs.statSync).mockReturnValueOnce({ isDirectory: () => false } as fs.Stats);
- const result = await processPrompts([testFunction, 'test.txt', validPrompt]);
- expect(result).toEqual([
- {
- raw: testFunction.toString(),
- label: 'testFunction',
- function: testFunction,
- },
- {
- raw: 'file prompt',
- label: 'test.txt: file prompt',
- },
- validPrompt,
- ]);
- });
- it('should process CSV files', async () => {
- const csvContent = `prompt,label
- Tell me about {{topic}},Basic Query
- Explain {{topic}} in simple terms,Simple Explanation`;
- jest.mocked(fs.readFileSync).mockReturnValueOnce(csvContent);
- jest.mocked(fs.statSync).mockReturnValueOnce({ isDirectory: () => false } as fs.Stats);
- const result = await processPrompts(['test.csv']);
- expect(result).toEqual([
- {
- raw: 'Tell me about {{topic}}',
- label: 'Basic Query',
- },
- {
- raw: 'Explain {{topic}} in simple terms',
- label: 'Simple Explanation',
- },
- ]);
- });
- it('should flatten array results from readPrompts', async () => {
- jest.mocked(fs.readFileSync).mockReturnValueOnce('prompt1\n---\nprompt2');
- jest.mocked(fs.statSync).mockReturnValueOnce({ isDirectory: () => false } as fs.Stats);
- const result = await processPrompts(['test.txt']);
- expect(result).toEqual([
- { raw: 'prompt1', label: 'test.txt: prompt1' },
- { raw: 'prompt2', label: 'test.txt: prompt2' },
- ]);
- expect(Array.isArray(result)).toBe(true);
- expect(result).toHaveLength(2);
- });
- });
|