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
|
- import fs from 'fs';
- import path from 'path';
- import { getCache, isCacheEnabled } from '../../src/cache';
- import { PythonProvider } from '../../src/providers/pythonCompletion';
- import { runPython } from '../../src/python/pythonUtils';
- jest.mock('../../src/python/pythonUtils');
- jest.mock('../../src/cache');
- jest.mock('fs');
- jest.mock('path');
- jest.mock('../../src/util', () => ({
- ...jest.requireActual('../../src/util'),
- parsePathOrGlob: jest.fn((basePath, runPath) => {
- // Handle the special case for testing function names
- if (runPath === 'script.py:custom_function') {
- return {
- filePath: 'script.py',
- functionName: 'custom_function',
- isPathPattern: false,
- extension: '.py',
- };
- }
- // Default case
- return {
- filePath: runPath,
- functionName: undefined,
- isPathPattern: false,
- extension: path.extname(runPath),
- };
- }),
- }));
- describe('PythonProvider', () => {
- const mockRunPython = jest.mocked(runPython);
- const mockGetCache = jest.mocked(jest.mocked(getCache));
- const mockIsCacheEnabled = jest.mocked(isCacheEnabled);
- const mockReadFileSync = jest.mocked(fs.readFileSync);
- const mockResolve = jest.mocked(path.resolve);
- beforeEach(() => {
- jest.clearAllMocks();
- mockGetCache.mockResolvedValue({
- get: jest.fn(),
- set: jest.fn(),
- } as never);
- mockIsCacheEnabled.mockReturnValue(false);
- mockReadFileSync.mockReturnValue('mock file content');
- mockResolve.mockReturnValue('/absolute/path/to/script.py');
- });
- describe('constructor', () => {
- it('should initialize with correct properties', () => {
- const provider = new PythonProvider('script.py', {
- id: 'testId',
- config: { basePath: '/base' },
- });
- expect(provider.id()).toBe('testId');
- });
- it('should initialize with python: syntax', () => {
- const provider = new PythonProvider('python:script.py', {
- id: 'testId',
- config: { basePath: '/base' },
- });
- expect(provider.id()).toBe('testId');
- });
- it('should initialize with file:// prefix', () => {
- const provider = new PythonProvider('file://script.py', {
- id: 'testId',
- config: { basePath: '/base' },
- });
- expect(provider.id()).toBe('testId');
- });
- it('should initialize with file:// prefix and function name', () => {
- const provider = new PythonProvider('file://script.py:function_name', {
- id: 'testId',
- config: { basePath: '/base' },
- });
- expect(provider.id()).toBe('testId');
- });
- });
- describe('callApi', () => {
- it('should call executePythonScript with correct parameters', async () => {
- const provider = new PythonProvider('script.py');
- mockRunPython.mockResolvedValue({ output: 'test output' });
- const result = await provider.callApi('test prompt', { someContext: true } as any);
- expect(mockRunPython).toHaveBeenCalledWith(
- expect.any(String),
- 'call_api',
- ['test prompt', { config: {} }, { someContext: true }],
- { pythonExecutable: undefined },
- );
- expect(result).toEqual({ output: 'test output', cached: false });
- });
- describe('error handling', () => {
- it('should throw a specific error when Python script returns invalid result', async () => {
- const provider = new PythonProvider('script.py');
- mockRunPython.mockResolvedValue({ invalidKey: 'invalid value' });
- await expect(provider.callApi('test prompt')).rejects.toThrow(
- 'The Python script `call_api` function must return a dict with an `output` string/object or `error` string, instead got: {"invalidKey":"invalid value"}',
- );
- });
- it('should not throw an error when Python script returns a valid error', async () => {
- const provider = new PythonProvider('script.py');
- mockRunPython.mockResolvedValue({ error: 'valid error message' });
- await expect(provider.callApi('test prompt')).resolves.not.toThrow();
- });
- it('should throw an error when Python script returns null', async () => {
- const provider = new PythonProvider('script.py');
- mockRunPython.mockResolvedValue(null as never);
- await expect(provider.callApi('test prompt')).rejects.toThrow(
- 'The Python script `call_api` function must return a dict with an `output` string/object or `error` string, instead got: null',
- );
- });
- it('should throw an error when Python script returns a non-object', async () => {
- const provider = new PythonProvider('script.py');
- mockRunPython.mockResolvedValue('string result');
- await expect(provider.callApi('test prompt')).rejects.toThrow(
- "Cannot use 'in' operator to search for 'output' in string result",
- );
- });
- it('should not throw an error when Python script returns a valid output', async () => {
- const provider = new PythonProvider('script.py');
- mockRunPython.mockResolvedValue({ output: 'valid output' });
- await expect(provider.callApi('test prompt')).resolves.not.toThrow();
- });
- });
- });
- describe('callEmbeddingApi', () => {
- it('should call executePythonScript with correct parameters', async () => {
- const provider = new PythonProvider('script.py');
- mockRunPython.mockResolvedValue({ embedding: [0.1, 0.2, 0.3] });
- const result = await provider.callEmbeddingApi('test prompt');
- expect(mockRunPython).toHaveBeenCalledWith(
- expect.any(String),
- 'call_embedding_api',
- ['test prompt', { config: {} }],
- { pythonExecutable: undefined },
- );
- expect(result).toEqual({ embedding: [0.1, 0.2, 0.3] });
- });
- it('should throw an error if Python script returns invalid result', async () => {
- const provider = new PythonProvider('script.py');
- mockRunPython.mockResolvedValue({ invalidKey: 'invalid value' });
- await expect(provider.callEmbeddingApi('test prompt')).rejects.toThrow(
- 'The Python script `call_embedding_api` function must return a dict with an `embedding` array or `error` string, instead got {"invalidKey":"invalid value"}',
- );
- });
- });
- describe('callClassificationApi', () => {
- it('should call executePythonScript with correct parameters', async () => {
- const provider = new PythonProvider('script.py');
- mockRunPython.mockResolvedValue({ classification: { label: 'test', score: 0.9 } });
- const result = await provider.callClassificationApi('test prompt');
- expect(mockRunPython).toHaveBeenCalledWith(
- expect.any(String),
- 'call_classification_api',
- ['test prompt', { config: {} }],
- { pythonExecutable: undefined },
- );
- expect(result).toEqual({ classification: { label: 'test', score: 0.9 } });
- });
- it('should throw an error if Python script returns invalid result', async () => {
- const provider = new PythonProvider('script.py');
- mockRunPython.mockResolvedValue({ invalidKey: 'invalid value' });
- await expect(provider.callClassificationApi('test prompt')).rejects.toThrow(
- 'The Python script `call_classification_api` function must return a dict with a `classification` object or `error` string, instead of {"invalidKey":"invalid value"}',
- );
- });
- });
- describe('caching', () => {
- it('should use cached result when available', async () => {
- const provider = new PythonProvider('script.py');
- mockIsCacheEnabled.mockReturnValue(true);
- const mockCache = {
- get: jest.fn().mockResolvedValue(JSON.stringify({ output: 'cached result' })),
- set: jest.fn(),
- };
- jest.mocked(mockGetCache).mockResolvedValue(mockCache as never);
- const result = await provider.callApi('test prompt');
- expect(mockCache.get).toHaveBeenCalledWith(
- 'python:undefined:default:call_api:5633d479dfae75ba7a78914ee380fa202bd6126e7c6b7c22e3ebc9e1a6ddc871:test prompt:undefined:undefined',
- );
- expect(mockRunPython).not.toHaveBeenCalled();
- expect(result).toEqual({ output: 'cached result', cached: true });
- });
- it('should cache result when cache is enabled', async () => {
- const provider = new PythonProvider('script.py');
- mockIsCacheEnabled.mockReturnValue(true);
- const mockCache = {
- get: jest.fn().mockResolvedValue(null),
- set: jest.fn(),
- };
- mockGetCache.mockResolvedValue(mockCache as never);
- mockRunPython.mockResolvedValue({ output: 'new result' });
- await provider.callApi('test prompt');
- expect(mockCache.set).toHaveBeenCalledWith(
- 'python:undefined:default:call_api:5633d479dfae75ba7a78914ee380fa202bd6126e7c6b7c22e3ebc9e1a6ddc871:test prompt:undefined:undefined',
- '{"output":"new result"}',
- );
- });
- it('should properly transform token usage in cached results', async () => {
- const provider = new PythonProvider('script.py');
- mockIsCacheEnabled.mockReturnValue(true);
- const mockCache = {
- get: jest.fn().mockResolvedValue(
- JSON.stringify({
- output: 'cached result with token usage',
- tokenUsage: {
- prompt: 10,
- completion: 15,
- total: 25,
- },
- }),
- ),
- set: jest.fn(),
- };
- jest.mocked(mockGetCache).mockResolvedValue(mockCache as never);
- const result = await provider.callApi('test prompt');
- expect(mockRunPython).not.toHaveBeenCalled();
- expect(result).toEqual({
- output: 'cached result with token usage',
- cached: true,
- tokenUsage: {
- cached: 25,
- total: 25,
- },
- });
- });
- it('should preserve cached=false for fresh results with token usage', async () => {
- const provider = new PythonProvider('script.py');
- mockIsCacheEnabled.mockReturnValue(true);
- const mockCache = {
- get: jest.fn().mockResolvedValue(null),
- set: jest.fn(),
- };
- mockGetCache.mockResolvedValue(mockCache as never);
- mockRunPython.mockResolvedValue({
- output: 'fresh result with token usage',
- tokenUsage: {
- prompt: 12,
- completion: 18,
- total: 30,
- },
- });
- const result = await provider.callApi('test prompt');
- expect(result).toEqual({
- output: 'fresh result with token usage',
- cached: false,
- tokenUsage: {
- prompt: 12,
- completion: 18,
- total: 30,
- },
- });
- });
- it('should handle missing token usage in cached results', async () => {
- const provider = new PythonProvider('script.py');
- mockIsCacheEnabled.mockReturnValue(true);
- const mockCache = {
- get: jest.fn().mockResolvedValue(
- JSON.stringify({
- output: 'cached result with no token usage',
- }),
- ),
- set: jest.fn(),
- };
- jest.mocked(mockGetCache).mockResolvedValue(mockCache as never);
- const result = await provider.callApi('test prompt');
- expect(mockRunPython).not.toHaveBeenCalled();
- expect(result.tokenUsage).toBeUndefined();
- expect(result.cached).toBe(true);
- });
- it('should handle zero token usage in cached results', async () => {
- const provider = new PythonProvider('script.py');
- mockIsCacheEnabled.mockReturnValue(true);
- const mockCache = {
- get: jest.fn().mockResolvedValue(
- JSON.stringify({
- output: 'cached result with zero token usage',
- tokenUsage: {
- prompt: 0,
- completion: 0,
- total: 0,
- },
- }),
- ),
- set: jest.fn(),
- };
- jest.mocked(mockGetCache).mockResolvedValue(mockCache as never);
- const result = await provider.callApi('test prompt');
- expect(mockRunPython).not.toHaveBeenCalled();
- expect(result.tokenUsage).toEqual({
- cached: 0,
- total: 0,
- });
- expect(result.cached).toBe(true);
- });
- it('should not cache results with errors', async () => {
- const provider = new PythonProvider('script.py');
- mockIsCacheEnabled.mockReturnValue(true);
- const mockCache = {
- get: jest.fn().mockResolvedValue(null),
- set: jest.fn(),
- };
- mockGetCache.mockResolvedValue(mockCache as never);
- mockRunPython.mockResolvedValue({
- error: 'This is an error message',
- output: null,
- });
- await provider.callApi('test prompt');
- expect(mockCache.set).not.toHaveBeenCalled();
- });
- it('should properly use different cache keys for different function names', async () => {
- mockIsCacheEnabled.mockReturnValue(true);
- const mockCache = {
- get: jest.fn().mockResolvedValue(null),
- set: jest.fn(),
- };
- mockGetCache.mockResolvedValue(mockCache as never);
- mockRunPython.mockResolvedValue({ output: 'test output' });
- // Create providers with different function names
- const defaultProvider = new PythonProvider('script.py');
- const customProvider = new PythonProvider('script.py:custom_function');
- // Call the APIs with the same prompt
- await defaultProvider.callApi('test prompt');
- await customProvider.callApi('test prompt');
- // Verify different cache keys were used
- const cacheSetCalls = mockCache.set.mock.calls;
- expect(cacheSetCalls).toHaveLength(2);
- // The first call should contain 'default' in the cache key
- expect(cacheSetCalls[0][0]).toContain(':default:');
- // The second call should contain the custom function name
- expect(cacheSetCalls[1][0]).toContain(':custom_function:');
- });
- });
- });
|