MCPcopy Index your code
hub / github.com/promptfoo/promptfoo / loadFunction

Function loadFunction

src/util/functions/loadFunction.ts:24–87  ·  view source on GitHub ↗
({
  filePath,
  functionName,
  defaultFunctionName = 'func',
  basePath = cliState.basePath,
  useCache = true,
}: LoadFunctionOptions)

Source from the content-addressed store, hash-verified

22 * @returns The loaded function
23 */
24export async function loadFunction<T extends Function>({
25 filePath,
26 functionName,
27 defaultFunctionName = 'func',
28 basePath = cliState.basePath,
29 useCache = true,
30}: LoadFunctionOptions): Promise<T> {
31 const resolvedPath = basePath ? path.resolve(basePath, filePath) : filePath;
32 const cacheKey = `${resolvedPath}:${
33 functionName ? `named:${functionName}` : `default:${defaultFunctionName}`
34 }`;
35
36 if (useCache && functionCache[cacheKey]) {
37 return functionCache[cacheKey] as T;
38 }
39
40 if (!isJavascriptFile(resolvedPath) && !resolvedPath.endsWith('.py')) {
41 throw new Error(
42 `File must be a JavaScript (${JAVASCRIPT_EXTENSIONS.join(', ')}) or Python (.py) file`,
43 );
44 }
45
46 try {
47 let func: T;
48 if (isJavascriptFile(resolvedPath)) {
49 const module = await importModule(resolvedPath, functionName);
50 let moduleFunc: any;
51
52 if (functionName) {
53 moduleFunc = module;
54 } else {
55 moduleFunc =
56 typeof module === 'function'
57 ? module
58 : module?.default?.default ||
59 module?.default ||
60 module?.[defaultFunctionName] ||
61 module;
62 }
63
64 if (typeof moduleFunc !== 'function') {
65 throw new Error(
66 functionName
67 ? `JavaScript file must export a "${functionName}" function`
68 : `JavaScript file must export a function (as default export or named export "${defaultFunctionName}")`,
69 );
70 }
71 func = moduleFunc as T;
72 } else {
73 const result = (...args: any[]) =>
74 runPython(resolvedPath, functionName || defaultFunctionName, args);
75 func = result as unknown as T;
76 }
77
78 if (useCache) {
79 functionCache[cacheKey] = func;
80 }
81

Callers 1

Calls 4

isJavascriptFileFunction · 0.90
importModuleFunction · 0.90
resolveMethod · 0.80
errorMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…