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

evaluatorHelpers.test.ts 10 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
  1. import * as fs from 'fs';
  2. import { createRequire } from 'node:module';
  3. import * as path from 'path';
  4. import { renderPrompt, resolveVariables, runExtensionHook } from '../src/evaluatorHelpers';
  5. import type { Prompt } from '../src/types';
  6. import { transform } from '../src/util/transform';
  7. jest.mock('proxy-agent', () => ({
  8. ProxyAgent: jest.fn().mockImplementation(() => ({})),
  9. }));
  10. jest.mock('glob', () => ({
  11. globSync: jest.fn(),
  12. }));
  13. jest.mock('node:module', () => {
  14. const mockRequire: NodeJS.Require = {
  15. resolve: jest.fn() as unknown as NodeJS.RequireResolve,
  16. } as unknown as NodeJS.Require;
  17. return {
  18. createRequire: jest.fn().mockReturnValue(mockRequire),
  19. };
  20. });
  21. jest.mock('fs', () => ({
  22. readFileSync: jest.fn(),
  23. writeFileSync: jest.fn(),
  24. statSync: jest.fn(),
  25. readdirSync: jest.fn(),
  26. existsSync: jest.fn(),
  27. mkdirSync: jest.fn(),
  28. promises: {
  29. readFile: jest.fn(),
  30. },
  31. }));
  32. jest.mock('../src/esm');
  33. jest.mock('../src/database', () => ({
  34. getDb: jest.fn(),
  35. }));
  36. jest.mock('../src/util/transform', () => ({
  37. transform: jest.fn(),
  38. }));
  39. function toPrompt(text: string): Prompt {
  40. return { raw: text, label: text };
  41. }
  42. describe('renderPrompt', () => {
  43. it('should render a prompt with a single variable', async () => {
  44. const prompt = toPrompt('Test prompt {{ var1 }}');
  45. const renderedPrompt = await renderPrompt(prompt, { var1: 'value1' }, {});
  46. expect(renderedPrompt).toBe('Test prompt value1');
  47. });
  48. it('should render nested variables in non-JSON prompts', async () => {
  49. const prompt = toPrompt('Test {{ outer[inner] }}');
  50. const renderedPrompt = await renderPrompt(
  51. prompt,
  52. { outer: { key1: 'value1' }, inner: 'key1' },
  53. {},
  54. );
  55. expect(renderedPrompt).toBe('Test value1');
  56. });
  57. it('should handle complex variable substitutions in non-JSON prompts', async () => {
  58. const prompt = toPrompt('{{ var1[var2] }}');
  59. const renderedPrompt = await renderPrompt(
  60. prompt,
  61. {
  62. var1: { hello: 'world' },
  63. var2: 'hello',
  64. },
  65. {},
  66. );
  67. expect(renderedPrompt).toBe('world');
  68. });
  69. it('should render a JSON prompt', async () => {
  70. const prompt = toPrompt('[{"text": "Test prompt "}, {"text": "{{ var1 }}"}]');
  71. const renderedPrompt = await renderPrompt(prompt, { var1: 'value1' }, {});
  72. expect(renderedPrompt).toBe(
  73. JSON.stringify(JSON.parse('[{"text":"Test prompt "},{"text":"value1"}]'), null, 2),
  74. );
  75. });
  76. it('should render nested variables in JSON prompts', async () => {
  77. const prompt = toPrompt('{"text": "{{ outer[inner] }}"}');
  78. const renderedPrompt = await renderPrompt(
  79. prompt,
  80. { outer: { key1: 'value1' }, inner: 'key1' },
  81. {},
  82. );
  83. expect(renderedPrompt).toBe(JSON.stringify({ text: 'value1' }, null, 2));
  84. });
  85. it('should handle complex variable substitutions in JSON prompts', async () => {
  86. const prompt = toPrompt('{"message": "{{ var1[var2] }}"}');
  87. const renderedPrompt = await renderPrompt(
  88. prompt,
  89. {
  90. var1: { hello: 'world' },
  91. var2: 'hello',
  92. },
  93. {},
  94. );
  95. expect(renderedPrompt).toBe(JSON.stringify({ message: 'world' }, null, 2));
  96. });
  97. it('should render a JSON prompt and escape the var string', async () => {
  98. const prompt = toPrompt('[{"text": "Test prompt "}, {"text": "{{ var1 }}"}]');
  99. const renderedPrompt = await renderPrompt(prompt, { var1: 'He said "hello world!"' }, {});
  100. expect(renderedPrompt).toBe(
  101. JSON.stringify(
  102. JSON.parse('[{"text":"Test prompt "},{"text":"He said \\"hello world!\\""}]'),
  103. null,
  104. 2,
  105. ),
  106. );
  107. });
  108. it('should render a JSON prompt with nested JSON', async () => {
  109. const prompt = toPrompt('[{"text": "Test prompt "}, {"text": "{{ var1 }}"}]');
  110. const renderedPrompt = await renderPrompt(prompt, { var1: '{"nested": "value1"}' }, {});
  111. expect(renderedPrompt).toBe(
  112. JSON.stringify(
  113. JSON.parse('[{"text":"Test prompt "},{"text":"{\\"nested\\": \\"value1\\"}"}]'),
  114. null,
  115. 2,
  116. ),
  117. );
  118. });
  119. it('should load external yaml files in renderPrompt', async () => {
  120. const prompt = toPrompt('Test prompt with {{ var1 }}');
  121. const vars = { var1: 'file://test.txt' };
  122. const evaluateOptions = {};
  123. // Mock fs.readFileSync to simulate loading a YAML file
  124. jest.spyOn(fs, 'readFileSync').mockReturnValueOnce('loaded from file');
  125. const renderedPrompt = await renderPrompt(prompt, vars, evaluateOptions);
  126. expect(fs.readFileSync).toHaveBeenCalledWith(expect.stringContaining('test.txt'), 'utf8');
  127. expect(renderedPrompt).toBe('Test prompt with loaded from file');
  128. });
  129. it('should load external js files in renderPrompt and execute the exported function', async () => {
  130. const prompt = toPrompt('Test prompt with {{ var1 }} {{ var2 }} {{ var3 }}');
  131. const vars = {
  132. var1: 'file:///path/to/testFunction.js',
  133. var2: 'file:///path/to/testFunction.cjs',
  134. var3: 'file:///path/to/testFunction.mjs',
  135. };
  136. const evaluateOptions = {};
  137. jest.doMock(
  138. path.resolve('/path/to/testFunction.js'),
  139. () => (varName: any, prompt: any, vars: any) => ({ output: `Dynamic value for ${varName}` }),
  140. { virtual: true },
  141. );
  142. jest.doMock(
  143. path.resolve('/path/to/testFunction.cjs'),
  144. () => (varName: any, prompt: any, vars: any) => ({ output: `and ${varName}` }),
  145. { virtual: true },
  146. );
  147. jest.doMock(
  148. path.resolve('/path/to/testFunction.mjs'),
  149. () => (varName: any, prompt: any, vars: any) => ({ output: `and ${varName}` }),
  150. { virtual: true },
  151. );
  152. const renderedPrompt = await renderPrompt(prompt, vars, evaluateOptions);
  153. expect(renderedPrompt).toBe('Test prompt with Dynamic value for var1 and var2 and var3');
  154. });
  155. it('should load external js package in renderPrompt and execute the exported function', async () => {
  156. const prompt = toPrompt('Test prompt with {{ var1 }}');
  157. const vars = {
  158. var1: 'package:@promptfoo/fake:testFunction',
  159. };
  160. const evaluateOptions = {};
  161. const require = createRequire('');
  162. jest.spyOn(require, 'resolve').mockReturnValueOnce('/node_modules/@promptfoo/fake/index.js');
  163. jest.doMock(
  164. path.resolve('/node_modules/@promptfoo/fake/index.js'),
  165. () => {
  166. return {
  167. testFunction: (varName: any, prompt: any, vars: any) => ({
  168. output: `Dynamic value for ${varName}`,
  169. }),
  170. };
  171. },
  172. { virtual: true },
  173. );
  174. const renderedPrompt = await renderPrompt(prompt, vars, evaluateOptions);
  175. expect(renderedPrompt).toBe('Test prompt with Dynamic value for var1');
  176. });
  177. it('should load external json files in renderPrompt and parse the JSON content', async () => {
  178. const prompt = toPrompt('Test prompt with {{ var1 }}');
  179. const vars = { var1: 'file:///path/to/testData.json' };
  180. const evaluateOptions = {};
  181. jest.spyOn(fs, 'readFileSync').mockReturnValueOnce(JSON.stringify({ key: 'valueFromJson' }));
  182. const renderedPrompt = await renderPrompt(prompt, vars, evaluateOptions);
  183. expect(fs.readFileSync).toHaveBeenCalledWith(expect.stringContaining('testData.json'), 'utf8');
  184. expect(renderedPrompt).toBe('Test prompt with {"key":"valueFromJson"}');
  185. });
  186. it('should load external yaml files in renderPrompt and parse the YAML content', async () => {
  187. const prompt = toPrompt('Test prompt with {{ var1 }}');
  188. const vars = { var1: 'file:///path/to/testData.yaml' };
  189. const evaluateOptions = {};
  190. jest.spyOn(fs, 'readFileSync').mockReturnValueOnce('key: valueFromYaml');
  191. const renderedPrompt = await renderPrompt(prompt, vars, evaluateOptions);
  192. expect(fs.readFileSync).toHaveBeenCalledWith(expect.stringContaining('testData.yaml'), 'utf8');
  193. expect(renderedPrompt).toBe('Test prompt with {"key":"valueFromYaml"}');
  194. });
  195. });
  196. describe('resolveVariables', () => {
  197. it('should replace placeholders with corresponding variable values', () => {
  198. const variables = { final: '{{ my_greeting }}, {{name}}!', my_greeting: 'Hello', name: 'John' };
  199. const expected = { final: 'Hello, John!', my_greeting: 'Hello', name: 'John' };
  200. expect(resolveVariables(variables)).toEqual(expected);
  201. });
  202. it('should handle nested variable substitutions', () => {
  203. const variables = { first: '{{second}}', second: '{{third}}', third: 'value' };
  204. const expected = { first: 'value', second: 'value', third: 'value' };
  205. expect(resolveVariables(variables)).toEqual(expected);
  206. });
  207. it('should not modify variables without placeholders', () => {
  208. const variables = { greeting: 'Hello, world!', name: 'John' };
  209. const expected = { greeting: 'Hello, world!', name: 'John' };
  210. expect(resolveVariables(variables)).toEqual(expected);
  211. });
  212. it('should not fail if a variable is not found', () => {
  213. const variables = { greeting: 'Hello, {{name}}!' };
  214. expect(resolveVariables(variables)).toEqual({ greeting: 'Hello, {{name}}!' });
  215. });
  216. it('should not fail for unresolved placeholders', () => {
  217. const variables = { greeting: 'Hello, {{name}}!', name: '{{unknown}}' };
  218. expect(resolveVariables(variables)).toEqual({
  219. greeting: 'Hello, {{unknown}}!',
  220. name: '{{unknown}}',
  221. });
  222. });
  223. });
  224. describe('runExtensionHook', () => {
  225. beforeEach(() => {
  226. jest.clearAllMocks();
  227. });
  228. it('should not call transform if extensions array is empty', async () => {
  229. await runExtensionHook([], 'testHook', { data: 'test' });
  230. expect(transform).not.toHaveBeenCalled();
  231. });
  232. it('should not call transform if extensions is undefined', async () => {
  233. await runExtensionHook(undefined, 'testHook', { data: 'test' });
  234. expect(transform).not.toHaveBeenCalled();
  235. });
  236. it('should call transform for each extension', async () => {
  237. const extensions = ['ext1', 'ext2', 'ext3'];
  238. const hookName = 'testHook';
  239. const context = { data: 'test' };
  240. await runExtensionHook(extensions, hookName, context);
  241. expect(transform).toHaveBeenCalledTimes(3);
  242. expect(transform).toHaveBeenNthCalledWith(1, 'ext1', hookName, context, false);
  243. expect(transform).toHaveBeenNthCalledWith(2, 'ext2', hookName, context, false);
  244. expect(transform).toHaveBeenNthCalledWith(3, 'ext3', hookName, context, false);
  245. });
  246. it('should throw an error if an extension is not a string', async () => {
  247. const extensions = ['ext1', 123, 'ext3'] as string[];
  248. const hookName = 'testHook';
  249. const context = { data: 'test' };
  250. await expect(runExtensionHook(extensions, hookName, context)).rejects.toThrow(
  251. 'extension must be a string',
  252. );
  253. });
  254. });
Tip!

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

Comments

Loading...