@use-lattice/litmus 0.121.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +19 -0
- package/dist/src/accounts-Bt1oJb1Z.cjs +219 -0
- package/dist/src/accounts-DjOU8Rm3.js +178 -0
- package/dist/src/agentic-utils-D03IiXQc.js +153 -0
- package/dist/src/agentic-utils-Dh7xaMQM.cjs +180 -0
- package/dist/src/agents-C6BIMlZa.js +231 -0
- package/dist/src/agents-DvIpNX1L.cjs +666 -0
- package/dist/src/agents-ZP0RP9vV.cjs +231 -0
- package/dist/src/agents-maJXdjbR.js +665 -0
- package/dist/src/aimlapi-BTbQjG2E.cjs +30 -0
- package/dist/src/aimlapi-CwMxqfXP.js +30 -0
- package/dist/src/audio-BBUdvsde.cjs +97 -0
- package/dist/src/audio-D5DPZ7I-.js +97 -0
- package/dist/src/base-BEysXrkq.cjs +222 -0
- package/dist/src/base-C451JQfq.js +193 -0
- package/dist/src/blobs-BY8MDmpo.js +230 -0
- package/dist/src/blobs-BgcNn97m.cjs +256 -0
- package/dist/src/cache-BBE_lsTA.cjs +4 -0
- package/dist/src/cache-BkrqU5Ba.js +237 -0
- package/dist/src/cache-DsCxFlsZ.cjs +297 -0
- package/dist/src/chat-CPJWDP6a.cjs +289 -0
- package/dist/src/chat-CXX3xzkk.cjs +811 -0
- package/dist/src/chat-CcDgZFJ4.js +787 -0
- package/dist/src/chat-Dz5ZeGO2.js +289 -0
- package/dist/src/chatkit-Dw0mKkML.cjs +1158 -0
- package/dist/src/chatkit-swAIVuea.js +1157 -0
- package/dist/src/chunk-DEq-mXcV.js +15 -0
- package/dist/src/claude-agent-sdk-BXZJtOg6.js +379 -0
- package/dist/src/claude-agent-sdk-CkfyjDoG.cjs +383 -0
- package/dist/src/cloudflare-ai-BzpJcqUH.js +161 -0
- package/dist/src/cloudflare-ai-Cmy_R1y2.cjs +161 -0
- package/dist/src/cloudflare-gateway-B9tVQKok.cjs +272 -0
- package/dist/src/cloudflare-gateway-DrD3ew3H.js +272 -0
- package/dist/src/codex-sdk-Dezj9Nwm.js +1056 -0
- package/dist/src/codex-sdk-Dl9D4k5B.cjs +1060 -0
- package/dist/src/cometapi-C-9YvCHC.js +54 -0
- package/dist/src/cometapi-DHgDKoO2.cjs +54 -0
- package/dist/src/completion-B8Ctyxpr.js +120 -0
- package/dist/src/completion-Cxrt08sj.cjs +131 -0
- package/dist/src/createHash-BwgE13yv.cjs +27 -0
- package/dist/src/createHash-DmPQkvBh.js +15 -0
- package/dist/src/docker-BiqcTwLv.js +80 -0
- package/dist/src/docker-C7tEJnP-.cjs +80 -0
- package/dist/src/esm-C62Zofr1.cjs +409 -0
- package/dist/src/esm-DMVc93eh.js +379 -0
- package/dist/src/evalResult-C3NJPQOo.cjs +301 -0
- package/dist/src/evalResult-C7JJAPBb.js +295 -0
- package/dist/src/evalResult-DoVTZZWI.cjs +2 -0
- package/dist/src/extractor-DnMD3fwt.cjs +391 -0
- package/dist/src/extractor-DtlL28vL.js +374 -0
- package/dist/src/fetch-BTxakTSg.cjs +1133 -0
- package/dist/src/fetch-DQckpUFz.js +928 -0
- package/dist/src/fileExtensions-DnqA1y9x.js +85 -0
- package/dist/src/fileExtensions-bYh77CN8.cjs +114 -0
- package/dist/src/genaiTracer-CyZrmaK0.cjs +268 -0
- package/dist/src/genaiTracer-D3fD9dNV.js +256 -0
- package/dist/src/graders-BNscxFrU.js +13644 -0
- package/dist/src/graders-D2oE9Msq.js +2 -0
- package/dist/src/graders-c0Ez_w-9.cjs +2 -0
- package/dist/src/graders-d0F2M3e9.cjs +14056 -0
- package/dist/src/image-0ZhE0VlR.cjs +280 -0
- package/dist/src/image-CWE1pdNv.js +257 -0
- package/dist/src/image-D9ZK6hwL.js +163 -0
- package/dist/src/image-DKZgZITg.cjs +163 -0
- package/dist/src/index.cjs +11366 -0
- package/dist/src/index.d.cts +19640 -0
- package/dist/src/index.d.ts +19641 -0
- package/dist/src/index.js +11306 -0
- package/dist/src/invariant-Ddh24eXh.js +25 -0
- package/dist/src/invariant-kfQ8Bu82.cjs +30 -0
- package/dist/src/knowledgeBase-BgPyGFUd.cjs +122 -0
- package/dist/src/knowledgeBase-DyHilYaP.js +122 -0
- package/dist/src/litellm-CyMeneHS.js +135 -0
- package/dist/src/litellm-DWDF73yF.cjs +135 -0
- package/dist/src/logger-C40ZGil9.js +717 -0
- package/dist/src/logger-DyfK9PBt.cjs +917 -0
- package/dist/src/luma-ray-BAU9X_ep.cjs +315 -0
- package/dist/src/luma-ray-nwVseBbv.js +313 -0
- package/dist/src/messages-B5ADWTTv.js +245 -0
- package/dist/src/messages-BCnZfqrS.cjs +257 -0
- package/dist/src/meteor-DLZZ3osF.cjs +134 -0
- package/dist/src/meteor-DUiCJRC-.js +134 -0
- package/dist/src/modelslab-00cveB8L.cjs +163 -0
- package/dist/src/modelslab-D9sCU_L7.js +163 -0
- package/dist/src/nova-reel-CTapvqYH.js +276 -0
- package/dist/src/nova-reel-DlWuuroF.cjs +278 -0
- package/dist/src/nova-sonic-5UPWfeMv.cjs +363 -0
- package/dist/src/nova-sonic-BhSwQNym.js +363 -0
- package/dist/src/openai-BWrJK9d8.cjs +52 -0
- package/dist/src/openai-DumO8WQn.js +47 -0
- package/dist/src/openclaw-B8brrjC_.cjs +577 -0
- package/dist/src/openclaw-Bkayww9q.js +571 -0
- package/dist/src/opencode-sdk-7xjoDNiM.cjs +562 -0
- package/dist/src/opencode-sdk-SGwAPxht.js +558 -0
- package/dist/src/otlpReceiver-CoAHfAN9.cjs +15 -0
- package/dist/src/otlpReceiver-oO3EQwI9.js +14 -0
- package/dist/src/providerRegistry-4yjhaEM8.js +45 -0
- package/dist/src/providerRegistry-DhV4rJIc.cjs +50 -0
- package/dist/src/providers-B5RJVG-7.cjs +33609 -0
- package/dist/src/providers-BdmZCLzV.js +33262 -0
- package/dist/src/providers-CxtRxn8e.js +2 -0
- package/dist/src/providers-DnQLNbx1.cjs +3 -0
- package/dist/src/pythonUtils-BD0druiM.cjs +275 -0
- package/dist/src/pythonUtils-IBhn5YGR.js +249 -0
- package/dist/src/quiverai-BDOwZBsM.cjs +213 -0
- package/dist/src/quiverai-D3JTF5lD.js +213 -0
- package/dist/src/responses-B2LCDCXZ.js +667 -0
- package/dist/src/responses-BvNm4Xv9.cjs +685 -0
- package/dist/src/rubyUtils-B0NwnfpY.cjs +245 -0
- package/dist/src/rubyUtils-BroxzZ7c.cjs +2 -0
- package/dist/src/rubyUtils-hqVw5UvJ.js +222 -0
- package/dist/src/sagemaker-Cno2V-Sx.js +689 -0
- package/dist/src/sagemaker-fV_KUgs5.cjs +691 -0
- package/dist/src/server-BOuAXb06.cjs +238 -0
- package/dist/src/server-CtI-EWzm.cjs +2 -0
- package/dist/src/server-Cy3DZymt.js +189 -0
- package/dist/src/slack-CP8xBePa.js +135 -0
- package/dist/src/slack-DSQ1yXVb.cjs +135 -0
- package/dist/src/store-BwDDaBjb.cjs +246 -0
- package/dist/src/store-DcbLC593.cjs +2 -0
- package/dist/src/store-IGpqMIkv.js +240 -0
- package/dist/src/tables-3Q2cL7So.cjs +373 -0
- package/dist/src/tables-Bi2fjr4W.js +288 -0
- package/dist/src/telemetry-Bg2WqF79.js +161 -0
- package/dist/src/telemetry-D0x6u5kX.cjs +166 -0
- package/dist/src/telemetry-DXNimrI0.cjs +2 -0
- package/dist/src/text-B_UCRPp2.js +22 -0
- package/dist/src/text-CW1cyrwj.cjs +33 -0
- package/dist/src/tokenUsageUtils-NYT-WKS6.js +138 -0
- package/dist/src/tokenUsageUtils-bVa1ga6f.cjs +173 -0
- package/dist/src/transcription-Cl_W16Pr.js +122 -0
- package/dist/src/transcription-yt1EecY8.cjs +124 -0
- package/dist/src/transform-BCtGrl_W.cjs +228 -0
- package/dist/src/transform-Bv6gG2MJ.cjs +1688 -0
- package/dist/src/transform-CY1wbpRy.js +1507 -0
- package/dist/src/transform-DU8rUL9P.cjs +2 -0
- package/dist/src/transform-yWaShiKr.js +216 -0
- package/dist/src/transformersAvailability-BGkzavwb.js +35 -0
- package/dist/src/transformersAvailability-DKoRtQLy.cjs +35 -0
- package/dist/src/types-5aqHpBwE.cjs +3769 -0
- package/dist/src/types-Bn6D9c4U.js +3300 -0
- package/dist/src/util-BkKlTkI2.js +293 -0
- package/dist/src/util-CTh0bfOm.cjs +1119 -0
- package/dist/src/util-D17oBwo7.cjs +328 -0
- package/dist/src/util-DsS_-v4p.js +613 -0
- package/dist/src/util-DuntT1Ga.js +951 -0
- package/dist/src/util-aWjdCYMI.cjs +667 -0
- package/dist/src/utils-CisQwpjA.js +94 -0
- package/dist/src/utils-yWamDvmz.cjs +123 -0
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/drizzle/0000_lush_hellion.sql +36 -0
- package/drizzle/0001_wide_calypso.sql +3 -0
- package/drizzle/0002_tidy_juggernaut.sql +1 -0
- package/drizzle/0003_lively_naoko.sql +8 -0
- package/drizzle/0004_minor_peter_quill.sql +19 -0
- package/drizzle/0005_silky_millenium_guard.sql +2 -0
- package/drizzle/0006_harsh_caretaker.sql +42 -0
- package/drizzle/0007_cloudy_wong.sql +1 -0
- package/drizzle/0008_broad_boomer.sql +2 -0
- package/drizzle/0009_strong_marten_broadcloak.sql +19 -0
- package/drizzle/0010_needy_bishop.sql +11 -0
- package/drizzle/0011_moaning_millenium_guard.sql +1 -0
- package/drizzle/0012_late_marten_broadcloak.sql +2 -0
- package/drizzle/0013_previous_dormammu.sql +9 -0
- package/drizzle/0014_lazy_captain_universe.sql +2 -0
- package/drizzle/0015_zippy_wallop.sql +29 -0
- package/drizzle/0016_jazzy_zemo.sql +2 -0
- package/drizzle/0017_reflective_praxagora.sql +4 -0
- package/drizzle/0018_fat_vanisher.sql +22 -0
- package/drizzle/0019_new_clint_barton.sql +8 -0
- package/drizzle/0020_skinny_maverick.sql +1 -0
- package/drizzle/0021_mysterious_madelyne_pryor.sql +13 -0
- package/drizzle/0022_sleepy_ultimo.sql +25 -0
- package/drizzle/0023_wooden_mandrill.sql +2 -0
- package/drizzle/AGENTS.md +68 -0
- package/drizzle/CLAUDE.md +1 -0
- package/drizzle/meta/0000_snapshot.json +221 -0
- package/drizzle/meta/0001_snapshot.json +214 -0
- package/drizzle/meta/0002_snapshot.json +221 -0
- package/drizzle/meta/0005_snapshot.json +369 -0
- package/drizzle/meta/0006_snapshot.json +638 -0
- package/drizzle/meta/0007_snapshot.json +640 -0
- package/drizzle/meta/0008_snapshot.json +649 -0
- package/drizzle/meta/0009_snapshot.json +554 -0
- package/drizzle/meta/0010_snapshot.json +619 -0
- package/drizzle/meta/0011_snapshot.json +627 -0
- package/drizzle/meta/0012_snapshot.json +639 -0
- package/drizzle/meta/0013_snapshot.json +717 -0
- package/drizzle/meta/0014_snapshot.json +717 -0
- package/drizzle/meta/0015_snapshot.json +897 -0
- package/drizzle/meta/0016_snapshot.json +1031 -0
- package/drizzle/meta/0018_snapshot.json +1210 -0
- package/drizzle/meta/0019_snapshot.json +1165 -0
- package/drizzle/meta/0020_snapshot.json +1232 -0
- package/drizzle/meta/0021_snapshot.json +1311 -0
- package/drizzle/meta/0022_snapshot.json +1481 -0
- package/drizzle/meta/0023_snapshot.json +1496 -0
- package/drizzle/meta/_journal.json +174 -0
- package/package.json +240 -0
|
@@ -0,0 +1,1119 @@
|
|
|
1
|
+
const require_logger = require("./logger-DyfK9PBt.cjs");
|
|
2
|
+
const require_invariant = require("./invariant-kfQ8Bu82.cjs");
|
|
3
|
+
const require_esm = require("./esm-C62Zofr1.cjs");
|
|
4
|
+
const require_pythonUtils = require("./pythonUtils-BD0druiM.cjs");
|
|
5
|
+
const require_fileExtensions = require("./fileExtensions-bYh77CN8.cjs");
|
|
6
|
+
const require_types = require("./types-5aqHpBwE.cjs");
|
|
7
|
+
const require_fetch = require("./fetch-BTxakTSg.cjs");
|
|
8
|
+
let fs = require("fs");
|
|
9
|
+
fs = require_logger.__toESM(fs);
|
|
10
|
+
let path = require("path");
|
|
11
|
+
path = require_logger.__toESM(path);
|
|
12
|
+
let js_yaml = require("js-yaml");
|
|
13
|
+
js_yaml = require_logger.__toESM(js_yaml);
|
|
14
|
+
let dotenv = require("dotenv");
|
|
15
|
+
dotenv = require_logger.__toESM(dotenv);
|
|
16
|
+
let os = require("os");
|
|
17
|
+
os = require_logger.__toESM(os);
|
|
18
|
+
let dedent = require("dedent");
|
|
19
|
+
dedent = require_logger.__toESM(dedent);
|
|
20
|
+
let fs_promises = require("fs/promises");
|
|
21
|
+
fs_promises = require_logger.__toESM(fs_promises);
|
|
22
|
+
let glob = require("glob");
|
|
23
|
+
require("fast-deep-equal");
|
|
24
|
+
let csv_parse_sync = require("csv-parse/sync");
|
|
25
|
+
let nunjucks = require("nunjucks");
|
|
26
|
+
nunjucks = require_logger.__toESM(nunjucks);
|
|
27
|
+
let fast_xml_parser = require("fast-xml-parser");
|
|
28
|
+
//#region src/util/provider.ts
|
|
29
|
+
function canonicalizeProviderId(id) {
|
|
30
|
+
if (id.startsWith("file://")) {
|
|
31
|
+
const filePath = id.slice(7);
|
|
32
|
+
return path.isAbsolute(filePath) ? id : `file://${path.resolve(filePath)}`;
|
|
33
|
+
}
|
|
34
|
+
for (const prefix of [
|
|
35
|
+
"exec:",
|
|
36
|
+
"python:",
|
|
37
|
+
"golang:"
|
|
38
|
+
]) if (id.startsWith(prefix)) {
|
|
39
|
+
const filePath = id.slice(prefix.length);
|
|
40
|
+
if (filePath.includes("/") || filePath.includes("\\")) return `${prefix}${path.resolve(filePath)}`;
|
|
41
|
+
return id;
|
|
42
|
+
}
|
|
43
|
+
if ((id.endsWith(".js") || id.endsWith(".ts") || id.endsWith(".mjs")) && (id.includes("/") || id.includes("\\"))) return `file://${path.resolve(id)}`;
|
|
44
|
+
return id;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Gets a descriptive identifier string for a provider, showing both label and ID when both exist.
|
|
48
|
+
* Useful for error messages to help users debug provider reference issues.
|
|
49
|
+
*/
|
|
50
|
+
function getProviderDescription(provider) {
|
|
51
|
+
const label = provider.label;
|
|
52
|
+
const id = provider.id();
|
|
53
|
+
if (label && label !== id) return `${label} (${id})`;
|
|
54
|
+
return id;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Checks if a provider reference matches a given provider.
|
|
58
|
+
* Supports exact matching and wildcard patterns.
|
|
59
|
+
*/
|
|
60
|
+
function doesProviderRefMatch(ref, provider) {
|
|
61
|
+
const label = provider.label;
|
|
62
|
+
const id = provider.id();
|
|
63
|
+
const canonicalRef = canonicalizeProviderId(ref);
|
|
64
|
+
const canonicalId = canonicalizeProviderId(id);
|
|
65
|
+
if (label && label === ref) return true;
|
|
66
|
+
if (id === ref || canonicalId === canonicalRef) return true;
|
|
67
|
+
if (ref.endsWith("*")) {
|
|
68
|
+
const prefix = ref.slice(0, -1);
|
|
69
|
+
if (label?.startsWith(prefix) || id.startsWith(prefix) || canonicalId.startsWith(prefix)) return true;
|
|
70
|
+
}
|
|
71
|
+
if (label?.startsWith(`${ref}:`) || id.startsWith(`${ref}:`) || canonicalId.startsWith(`${ref}:`)) return true;
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Checks if a provider is allowed based on a list of allowed references.
|
|
76
|
+
*/
|
|
77
|
+
function isProviderAllowed(provider, allowedProviders) {
|
|
78
|
+
if (!Array.isArray(allowedProviders)) return true;
|
|
79
|
+
if (allowedProviders.length === 0) return false;
|
|
80
|
+
return allowedProviders.some((ref) => doesProviderRefMatch(ref, provider));
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Detects if a provider uses OpenAI models.
|
|
84
|
+
* This includes direct OpenAI providers and Azure OpenAI.
|
|
85
|
+
*/
|
|
86
|
+
function isOpenAiProvider(providerId) {
|
|
87
|
+
const lowerProviderId = providerId.toLowerCase();
|
|
88
|
+
if (lowerProviderId.startsWith("openai:")) return true;
|
|
89
|
+
if (lowerProviderId.startsWith("azureopenai:")) return true;
|
|
90
|
+
if (lowerProviderId.startsWith("azure:")) {
|
|
91
|
+
if ([
|
|
92
|
+
"gpt",
|
|
93
|
+
"openai",
|
|
94
|
+
"davinci",
|
|
95
|
+
"curie",
|
|
96
|
+
"babbage",
|
|
97
|
+
"ada",
|
|
98
|
+
"text-embedding",
|
|
99
|
+
"whisper",
|
|
100
|
+
"dall-e",
|
|
101
|
+
"tts"
|
|
102
|
+
].some((indicator) => lowerProviderId.includes(indicator))) return true;
|
|
103
|
+
}
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Detects if a provider uses Anthropic/Claude models.
|
|
108
|
+
* This includes direct Anthropic providers, Bedrock with Claude, and Vertex with Claude.
|
|
109
|
+
*/
|
|
110
|
+
function isAnthropicProvider(providerId) {
|
|
111
|
+
const lowerProviderId = providerId.toLowerCase();
|
|
112
|
+
if (lowerProviderId.startsWith("anthropic:")) return true;
|
|
113
|
+
if (lowerProviderId.startsWith("bedrock:")) {
|
|
114
|
+
if (lowerProviderId.includes("claude") || lowerProviderId.includes("anthropic")) return true;
|
|
115
|
+
}
|
|
116
|
+
if (lowerProviderId.startsWith("vertex:")) {
|
|
117
|
+
if (lowerProviderId.includes("claude")) return true;
|
|
118
|
+
}
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Detects if a provider uses Google models.
|
|
123
|
+
* This includes direct Google/Vertex providers with Gemini and other Google models.
|
|
124
|
+
* Note: Vertex with Claude models is NOT counted as Google (it's Anthropic).
|
|
125
|
+
*/
|
|
126
|
+
function isGoogleProvider(providerId) {
|
|
127
|
+
const lowerProviderId = providerId.toLowerCase();
|
|
128
|
+
if (lowerProviderId.startsWith("google:")) return true;
|
|
129
|
+
if (lowerProviderId.startsWith("vertex:")) {
|
|
130
|
+
if (!lowerProviderId.includes("claude")) return true;
|
|
131
|
+
}
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
//#endregion
|
|
135
|
+
//#region src/util/env.ts
|
|
136
|
+
/**
|
|
137
|
+
* Load environment variables from .env file(s).
|
|
138
|
+
* @param envPath - Single path, array of paths, or undefined for default .env loading.
|
|
139
|
+
* When paths are explicitly specified, all files must exist or an error is thrown.
|
|
140
|
+
* When multiple files are provided, later files override values from earlier files.
|
|
141
|
+
*/
|
|
142
|
+
function setupEnv(envPath) {
|
|
143
|
+
if (envPath) {
|
|
144
|
+
const paths = (Array.isArray(envPath) ? envPath : [envPath]).flatMap((p) => p.includes(",") ? p.split(",").map((s) => s.trim()) : p.trim()).filter((p) => p.length > 0);
|
|
145
|
+
if (paths.length === 0) {
|
|
146
|
+
dotenv.default.config({ quiet: true });
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
for (const p of paths) if (!fs.existsSync(p)) throw new Error(`Environment file not found: ${p}`);
|
|
150
|
+
if (paths.length === 1) require_logger.logger.info(`Loading environment variables from ${paths[0]}`);
|
|
151
|
+
else require_logger.logger.info(`Loading environment variables from: ${paths.join(", ")}`);
|
|
152
|
+
const pathArg = paths.length === 1 ? paths[0] : paths;
|
|
153
|
+
dotenv.default.config({
|
|
154
|
+
path: pathArg,
|
|
155
|
+
override: true,
|
|
156
|
+
quiet: true
|
|
157
|
+
});
|
|
158
|
+
} else dotenv.default.config({ quiet: true });
|
|
159
|
+
}
|
|
160
|
+
//#endregion
|
|
161
|
+
//#region src/util/functions/loadFunction.ts
|
|
162
|
+
const functionCache = {};
|
|
163
|
+
/**
|
|
164
|
+
* Loads a function from a JavaScript or Python file
|
|
165
|
+
* @param options Options for loading the function
|
|
166
|
+
* @returns The loaded function
|
|
167
|
+
*/
|
|
168
|
+
async function loadFunction({ filePath, functionName, defaultFunctionName = "func", basePath = require_logger.state.basePath, useCache = true }) {
|
|
169
|
+
const cacheKey = `${filePath}${functionName ? `:${functionName}` : ""}`;
|
|
170
|
+
if (useCache && functionCache[cacheKey]) return functionCache[cacheKey];
|
|
171
|
+
const resolvedPath = basePath ? path.default.resolve(basePath, filePath) : filePath;
|
|
172
|
+
if (!require_fileExtensions.isJavascriptFile(resolvedPath) && !resolvedPath.endsWith(".py")) throw new Error(`File must be a JavaScript (${require_fileExtensions.JAVASCRIPT_EXTENSIONS.join(", ")}) or Python (.py) file`);
|
|
173
|
+
try {
|
|
174
|
+
let func;
|
|
175
|
+
if (require_fileExtensions.isJavascriptFile(resolvedPath)) {
|
|
176
|
+
const module = await require_esm.importModule(resolvedPath, functionName);
|
|
177
|
+
let moduleFunc;
|
|
178
|
+
if (functionName) moduleFunc = module;
|
|
179
|
+
else moduleFunc = typeof module === "function" ? module : module?.default?.default || module?.default || module?.[defaultFunctionName] || module;
|
|
180
|
+
if (typeof moduleFunc !== "function") throw new Error(functionName ? `JavaScript file must export a "${functionName}" function` : `JavaScript file must export a function (as default export or named export "${defaultFunctionName}")`);
|
|
181
|
+
func = moduleFunc;
|
|
182
|
+
} else {
|
|
183
|
+
const result = (...args) => require_pythonUtils.runPython(resolvedPath, functionName || defaultFunctionName, args);
|
|
184
|
+
func = result;
|
|
185
|
+
}
|
|
186
|
+
if (useCache) functionCache[cacheKey] = func;
|
|
187
|
+
return func;
|
|
188
|
+
} catch (err) {
|
|
189
|
+
require_logger.logger.error(`Failed to load function: ${err.message}`);
|
|
190
|
+
throw err;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Extracts the file path and function name from a file:// URL
|
|
195
|
+
* @param fileUrl The file:// URL (e.g., "file://path/to/file.js:functionName")
|
|
196
|
+
* @returns The file path and optional function name
|
|
197
|
+
*/
|
|
198
|
+
function parseFileUrl(fileUrl) {
|
|
199
|
+
if (!fileUrl.startsWith("file://")) throw new Error("URL must start with file://");
|
|
200
|
+
const urlWithoutProtocol = fileUrl.slice(7);
|
|
201
|
+
const lastColonIndex = urlWithoutProtocol.lastIndexOf(":");
|
|
202
|
+
if (lastColonIndex > 1) return {
|
|
203
|
+
filePath: urlWithoutProtocol.slice(0, lastColonIndex),
|
|
204
|
+
functionName: urlWithoutProtocol.slice(lastColonIndex + 1)
|
|
205
|
+
};
|
|
206
|
+
return { filePath: urlWithoutProtocol };
|
|
207
|
+
}
|
|
208
|
+
//#endregion
|
|
209
|
+
//#region src/util/templates.ts
|
|
210
|
+
/**
|
|
211
|
+
* Get a Nunjucks engine instance with optional filters and configuration.
|
|
212
|
+
* @param filters - Optional map of custom Nunjucks filters.
|
|
213
|
+
* @param throwOnUndefined - Whether to throw an error on undefined variables.
|
|
214
|
+
* @param isGrader - Whether this engine is being used in a grader context.
|
|
215
|
+
* Nunjucks is always enabled in grader mode.
|
|
216
|
+
* @returns A configured Nunjucks environment.
|
|
217
|
+
*/
|
|
218
|
+
function getNunjucksEngine(filters, throwOnUndefined = false, isGrader = false) {
|
|
219
|
+
if (!isGrader && require_logger.getEnvBool("PROMPTFOO_DISABLE_TEMPLATING")) return { renderString: (template) => template };
|
|
220
|
+
const env = nunjucks.default.configure({
|
|
221
|
+
autoescape: false,
|
|
222
|
+
throwOnUndefined
|
|
223
|
+
});
|
|
224
|
+
const envGlobals = {
|
|
225
|
+
...require_logger.getEnvBool("PROMPTFOO_DISABLE_TEMPLATE_ENV_VARS", require_logger.getEnvBool("PROMPTFOO_SELF_HOSTED", false)) ? {} : process.env,
|
|
226
|
+
...require_logger.state.config?.env
|
|
227
|
+
};
|
|
228
|
+
env.addGlobal("env", envGlobals);
|
|
229
|
+
env.addFilter("load", function(str) {
|
|
230
|
+
return JSON.parse(str);
|
|
231
|
+
});
|
|
232
|
+
if (filters) for (const [name, filter] of Object.entries(filters)) env.addFilter(name, filter);
|
|
233
|
+
return env;
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Parse Nunjucks template to extract variables.
|
|
237
|
+
* @param template - The Nunjucks template string.
|
|
238
|
+
* @returns An array of variables used in the template.
|
|
239
|
+
*/
|
|
240
|
+
function extractVariablesFromTemplate(template) {
|
|
241
|
+
const variableSet = /* @__PURE__ */ new Set();
|
|
242
|
+
const regex = /\{\{[\s]*([^{}\s|]+)[\s]*(?:\|[^}]+)?\}\}|\{%[\s]*(?:if|for)[\s]+([^{}\s]+)[\s]*.*?%\}/g;
|
|
243
|
+
template = template.replace(/\{#[\s\S]*?#\}/g, "");
|
|
244
|
+
let match;
|
|
245
|
+
while ((match = regex.exec(template)) !== null) {
|
|
246
|
+
const variable = match[1] || match[2];
|
|
247
|
+
if (variable) variableSet.add(variable);
|
|
248
|
+
}
|
|
249
|
+
const forLoopRegex = /\{%[\s]*for[\s]+(\w+)[\s]+in[\s]+(\w+)[\s]*%\}/g;
|
|
250
|
+
while ((match = forLoopRegex.exec(template)) !== null) {
|
|
251
|
+
variableSet.delete(match[1]);
|
|
252
|
+
variableSet.add(match[2]);
|
|
253
|
+
}
|
|
254
|
+
return Array.from(variableSet);
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Extract variables from multiple Nunjucks templates.
|
|
258
|
+
* @param templates - An array of Nunjucks template strings.
|
|
259
|
+
* @returns An array of variables used in the templates.
|
|
260
|
+
*/
|
|
261
|
+
function extractVariablesFromTemplates(templates) {
|
|
262
|
+
const variableSet = /* @__PURE__ */ new Set();
|
|
263
|
+
for (const template of templates) extractVariablesFromTemplate(template).forEach((variable) => variableSet.add(variable));
|
|
264
|
+
return Array.from(variableSet);
|
|
265
|
+
}
|
|
266
|
+
//#endregion
|
|
267
|
+
//#region src/util/render.ts
|
|
268
|
+
/**
|
|
269
|
+
* Renders ONLY environment variable templates in an object, leaving all other templates untouched.
|
|
270
|
+
* This allows env vars to be resolved at provider load time while preserving runtime var templates.
|
|
271
|
+
*
|
|
272
|
+
* Supports full Nunjucks syntax for env vars including filters and expressions:
|
|
273
|
+
* - {{ env.VAR_NAME }}
|
|
274
|
+
* - {{ env['VAR-NAME'] }}
|
|
275
|
+
* - {{ env["VAR-NAME"] }}
|
|
276
|
+
* - {{ env.VAR | default('fallback') }}
|
|
277
|
+
* - {{ env.VAR | upper }}
|
|
278
|
+
*
|
|
279
|
+
* Preserves non-env templates for runtime rendering:
|
|
280
|
+
* - {{ vars.x }} - preserved as literal
|
|
281
|
+
* - {{ prompt }} - preserved as literal
|
|
282
|
+
*
|
|
283
|
+
* Implementation: Uses regex to find env templates, delegates to Nunjucks for rendering.
|
|
284
|
+
* This ensures full Nunjucks feature support while preserving non-env templates.
|
|
285
|
+
*
|
|
286
|
+
* @param obj - The object to process
|
|
287
|
+
* @param envOverrides - Optional env vars to merge with (or replace) the base env
|
|
288
|
+
* @param replaceBase - If true, envOverrides replaces the base env entirely instead of merging
|
|
289
|
+
* @returns The object with only env templates rendered
|
|
290
|
+
*/
|
|
291
|
+
function renderEnvOnlyInObject(obj, envOverrides, replaceBase) {
|
|
292
|
+
if (require_logger.getEnvBool("PROMPTFOO_DISABLE_TEMPLATING")) return obj;
|
|
293
|
+
if (typeof obj === "string") {
|
|
294
|
+
const nunjucks = getNunjucksEngine();
|
|
295
|
+
const baseEnvGlobals = nunjucks.getGlobal("env");
|
|
296
|
+
const envGlobals = replaceBase ? envOverrides ?? {} : envOverrides ? {
|
|
297
|
+
...baseEnvGlobals,
|
|
298
|
+
...envOverrides
|
|
299
|
+
} : baseEnvGlobals;
|
|
300
|
+
return obj.replace(/\{\{(?:[^}]|\}(?!\}))*\}\}/g, (match) => {
|
|
301
|
+
if (!match.match(/\benv\.|env\[/)) return match;
|
|
302
|
+
const varMatch = match.match(/env\.(\w+)|env\[['"]([^'"]+)['"]\]/);
|
|
303
|
+
const varName = varMatch?.[1] || varMatch?.[2];
|
|
304
|
+
if (match.includes("|") || varName && varName in envGlobals && envGlobals[varName] !== void 0) try {
|
|
305
|
+
return nunjucks.renderString(match, { env: envGlobals });
|
|
306
|
+
} catch (error) {
|
|
307
|
+
require_logger.logger.debug(`Failed to render env template "${match}": ${error instanceof Error ? error.message : String(error)}`);
|
|
308
|
+
return match;
|
|
309
|
+
}
|
|
310
|
+
return match;
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
if (Array.isArray(obj)) return obj.map((item) => renderEnvOnlyInObject(item, envOverrides, replaceBase));
|
|
314
|
+
if (typeof obj === "object" && obj !== null) {
|
|
315
|
+
const result = {};
|
|
316
|
+
for (const key in obj) {
|
|
317
|
+
if (key === "_conversation") {
|
|
318
|
+
result[key] = obj[key];
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
result[key] = renderEnvOnlyInObject(obj[key], envOverrides, replaceBase);
|
|
322
|
+
}
|
|
323
|
+
return result;
|
|
324
|
+
}
|
|
325
|
+
return obj;
|
|
326
|
+
}
|
|
327
|
+
function renderVarsInObject(obj, vars) {
|
|
328
|
+
if (!vars || require_logger.getEnvBool("PROMPTFOO_DISABLE_TEMPLATING")) return obj;
|
|
329
|
+
if (typeof obj === "string") return getNunjucksEngine().renderString(obj, vars);
|
|
330
|
+
if (Array.isArray(obj)) return obj.map((item) => renderVarsInObject(item, vars));
|
|
331
|
+
if (typeof obj === "object" && obj !== null) {
|
|
332
|
+
const result = {};
|
|
333
|
+
for (const key in obj) result[key] = renderVarsInObject(obj[key], vars);
|
|
334
|
+
return result;
|
|
335
|
+
} else if (typeof obj === "function") return renderVarsInObject(obj({ vars }));
|
|
336
|
+
return obj;
|
|
337
|
+
}
|
|
338
|
+
//#endregion
|
|
339
|
+
//#region src/util/file.ts
|
|
340
|
+
/**
|
|
341
|
+
* Simple Nunjucks engine specifically for file paths
|
|
342
|
+
* This function is separate from the main getNunjucksEngine to avoid circular dependencies
|
|
343
|
+
*/
|
|
344
|
+
function getNunjucksEngineForFilePath() {
|
|
345
|
+
const env = nunjucks.default.configure({ autoescape: false });
|
|
346
|
+
env.addGlobal("env", {
|
|
347
|
+
...process.env,
|
|
348
|
+
...require_logger.state.config?.env
|
|
349
|
+
});
|
|
350
|
+
return env;
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Loads content from an external file if the input is a file path, otherwise
|
|
354
|
+
* returns the input as-is. Supports Nunjucks templating for file paths.
|
|
355
|
+
*
|
|
356
|
+
* @param filePath - The input to process. Can be a file path string starting with "file://",
|
|
357
|
+
* an array of file paths, or any other type of data.
|
|
358
|
+
* @param context - Optional context to control file loading behavior. 'assertion' context
|
|
359
|
+
* preserves Python/JS file references instead of loading their content.
|
|
360
|
+
* @returns The loaded content if the input was a file path, otherwise the original input.
|
|
361
|
+
* For JSON and YAML files, the content is parsed into an object.
|
|
362
|
+
* For other file types, the raw file content is returned as a string.
|
|
363
|
+
*
|
|
364
|
+
* @throws {Error} If the specified file does not exist.
|
|
365
|
+
*/
|
|
366
|
+
function maybeLoadFromExternalFile(filePath, context) {
|
|
367
|
+
if (Array.isArray(filePath)) return filePath.map((path$2) => {
|
|
368
|
+
return maybeLoadFromExternalFile(path$2, context);
|
|
369
|
+
});
|
|
370
|
+
if (typeof filePath !== "string") return filePath;
|
|
371
|
+
if (!filePath.startsWith("file://")) return filePath;
|
|
372
|
+
const renderedFilePath = getNunjucksEngineForFilePath().renderString(filePath, {});
|
|
373
|
+
const { filePath: cleanPath, functionName } = parseFileUrl(renderedFilePath);
|
|
374
|
+
if (context === "assertion" && (cleanPath.endsWith(".py") || require_fileExtensions.isJavascriptFile(cleanPath))) {
|
|
375
|
+
require_logger.logger.debug(`Preserving Python/JS file reference in assertion context: ${renderedFilePath}`);
|
|
376
|
+
return renderedFilePath;
|
|
377
|
+
}
|
|
378
|
+
if (context === "vars") {
|
|
379
|
+
require_logger.logger.debug(`Preserving file reference in vars context: ${renderedFilePath}`);
|
|
380
|
+
return renderedFilePath;
|
|
381
|
+
}
|
|
382
|
+
if (functionName && (cleanPath.endsWith(".py") || require_fileExtensions.isJavascriptFile(cleanPath))) return renderedFilePath;
|
|
383
|
+
const pathToUse = functionName && !(cleanPath.endsWith(".py") || require_fileExtensions.isJavascriptFile(cleanPath)) ? renderedFilePath.slice(7) : cleanPath;
|
|
384
|
+
const resolvedPath = path.resolve(require_logger.state.basePath || "", pathToUse);
|
|
385
|
+
if ((0, glob.hasMagic)(pathToUse)) {
|
|
386
|
+
const matchedFiles = (0, glob.globSync)(resolvedPath, { windowsPathsNoEscape: true });
|
|
387
|
+
if (matchedFiles.length === 0) throw new Error(`No files found matching pattern: ${resolvedPath}`);
|
|
388
|
+
const allContents = [];
|
|
389
|
+
for (const matchedFile of matchedFiles) {
|
|
390
|
+
let contents;
|
|
391
|
+
try {
|
|
392
|
+
contents = fs.readFileSync(matchedFile, "utf8");
|
|
393
|
+
} catch (error) {
|
|
394
|
+
if (error.code === "ENOENT") {
|
|
395
|
+
require_logger.logger.debug(`File disappeared during glob expansion: ${matchedFile}`);
|
|
396
|
+
continue;
|
|
397
|
+
}
|
|
398
|
+
throw error;
|
|
399
|
+
}
|
|
400
|
+
if (matchedFile.endsWith(".json")) {
|
|
401
|
+
const parsed = JSON.parse(contents);
|
|
402
|
+
if (Array.isArray(parsed)) allContents.push(...parsed);
|
|
403
|
+
else allContents.push(parsed);
|
|
404
|
+
} else if (matchedFile.endsWith(".yaml") || matchedFile.endsWith(".yml")) {
|
|
405
|
+
const parsed = js_yaml.default.load(contents);
|
|
406
|
+
if (parsed === null || parsed === void 0) continue;
|
|
407
|
+
if (Array.isArray(parsed)) allContents.push(...parsed);
|
|
408
|
+
else allContents.push(parsed);
|
|
409
|
+
} else if (matchedFile.endsWith(".csv")) {
|
|
410
|
+
const records = (0, csv_parse_sync.parse)(contents, { columns: true });
|
|
411
|
+
if (records.length > 0 && Object.keys(records[0]).length === 1) allContents.push(...records.map((record) => Object.values(record)[0]));
|
|
412
|
+
else allContents.push(...records);
|
|
413
|
+
} else allContents.push(contents);
|
|
414
|
+
}
|
|
415
|
+
return allContents;
|
|
416
|
+
}
|
|
417
|
+
const finalPath = resolvedPath;
|
|
418
|
+
let contents;
|
|
419
|
+
try {
|
|
420
|
+
contents = fs.readFileSync(finalPath, "utf8");
|
|
421
|
+
} catch (error) {
|
|
422
|
+
if (error.code === "ENOENT") throw new Error(`File does not exist: ${finalPath}`);
|
|
423
|
+
throw new Error(`Failed to read file ${finalPath}: ${error}`);
|
|
424
|
+
}
|
|
425
|
+
if (finalPath.endsWith(".json")) try {
|
|
426
|
+
return JSON.parse(contents);
|
|
427
|
+
} catch (error) {
|
|
428
|
+
throw new Error(`Failed to parse JSON file ${finalPath}: ${error}`);
|
|
429
|
+
}
|
|
430
|
+
if (finalPath.endsWith(".yaml") || finalPath.endsWith(".yml")) try {
|
|
431
|
+
return js_yaml.default.load(contents);
|
|
432
|
+
} catch (error) {
|
|
433
|
+
throw new Error(`Failed to parse YAML file ${finalPath}: ${error}`);
|
|
434
|
+
}
|
|
435
|
+
if (finalPath.endsWith(".csv")) {
|
|
436
|
+
const records = (0, csv_parse_sync.parse)(contents, { columns: true });
|
|
437
|
+
if (records.length > 0 && Object.keys(records[0]).length === 1) return records.map((record) => Object.values(record)[0]);
|
|
438
|
+
return records;
|
|
439
|
+
}
|
|
440
|
+
return contents;
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* Resolves a relative file path with respect to a base path, handling cloud configuration appropriately.
|
|
444
|
+
* When using a cloud configuration, the current working directory is always used instead of the context's base path.
|
|
445
|
+
*
|
|
446
|
+
* @param filePath - The relative or absolute file path to resolve.
|
|
447
|
+
* @param isCloudConfig - Whether this is a cloud configuration.
|
|
448
|
+
* @returns The resolved absolute file path.
|
|
449
|
+
*/
|
|
450
|
+
function getResolvedRelativePath(filePath, isCloudConfig) {
|
|
451
|
+
if (path.isAbsolute(filePath) || !isCloudConfig) return filePath;
|
|
452
|
+
return path.join(process.cwd(), filePath);
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Recursively loads external file references from a configuration object.
|
|
456
|
+
*
|
|
457
|
+
* @param config - The configuration object to process
|
|
458
|
+
* @param context - Optional context to control file loading behavior
|
|
459
|
+
* @returns The configuration with external file references resolved
|
|
460
|
+
*/
|
|
461
|
+
function maybeLoadConfigFromExternalFile(config, context) {
|
|
462
|
+
if (Array.isArray(config)) return config.map((item) => maybeLoadConfigFromExternalFile(item, context));
|
|
463
|
+
if (typeof config === "object" && config !== null) {
|
|
464
|
+
const result = {};
|
|
465
|
+
for (const key of Object.keys(config)) {
|
|
466
|
+
const childContext = key === "value" && "type" in config && typeof config.type === "string" && (config.type === "python" || config.type === "javascript") ? "assertion" : key === "vars" ? "vars" : context;
|
|
467
|
+
result[key] = maybeLoadConfigFromExternalFile(config[key], childContext);
|
|
468
|
+
}
|
|
469
|
+
return result;
|
|
470
|
+
}
|
|
471
|
+
return maybeLoadFromExternalFile(config, context);
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* Parses a file path or glob pattern to extract function names and file extensions.
|
|
475
|
+
* Function names can be specified in the filename like this:
|
|
476
|
+
* prompt.py:myFunction or prompts.js:myFunction.
|
|
477
|
+
* @param basePath - The base path for file resolution.
|
|
478
|
+
* @param promptPath - The path or glob pattern.
|
|
479
|
+
* @returns Parsed details including function name, file extension, and directory status.
|
|
480
|
+
*/
|
|
481
|
+
function parsePathOrGlob(basePath, promptPath) {
|
|
482
|
+
if (promptPath.startsWith("file://")) promptPath = promptPath.slice(7);
|
|
483
|
+
const filePath = path.resolve(basePath, promptPath);
|
|
484
|
+
let filename = path.relative(basePath, filePath);
|
|
485
|
+
let functionName;
|
|
486
|
+
if (filename.includes(":")) {
|
|
487
|
+
const lastColonIndex = filename.lastIndexOf(":");
|
|
488
|
+
if (lastColonIndex > 1) {
|
|
489
|
+
const pathWithoutFunction = filename.slice(0, lastColonIndex);
|
|
490
|
+
if (require_fileExtensions.isJavascriptFile(pathWithoutFunction) || pathWithoutFunction.endsWith(".py") || pathWithoutFunction.endsWith(".go") || pathWithoutFunction.endsWith(".rb")) {
|
|
491
|
+
functionName = filename.slice(lastColonIndex + 1);
|
|
492
|
+
filename = pathWithoutFunction;
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
let stats;
|
|
497
|
+
try {
|
|
498
|
+
stats = fs.statSync(path.join(basePath, filename));
|
|
499
|
+
} catch (err) {
|
|
500
|
+
if (require_logger.getEnvBool("PROMPTFOO_STRICT_FILES")) throw err;
|
|
501
|
+
}
|
|
502
|
+
const normalizedFilePath = filePath.replace(/\\/g, "/");
|
|
503
|
+
const isPathPattern = stats?.isDirectory() || (0, glob.hasMagic)(promptPath) || (0, glob.hasMagic)(normalizedFilePath);
|
|
504
|
+
const safeFilename = path.relative(basePath, require_esm.safeResolve(basePath, filename));
|
|
505
|
+
return {
|
|
506
|
+
extension: isPathPattern ? void 0 : path.parse(safeFilename).ext,
|
|
507
|
+
filePath: path.join(basePath, safeFilename),
|
|
508
|
+
functionName,
|
|
509
|
+
isPathPattern
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* Load custom Nunjucks filters from external files.
|
|
514
|
+
* Note: If a glob pattern matches multiple files, only the last file's export is used.
|
|
515
|
+
* Each filter name should typically resolve to a single file.
|
|
516
|
+
*/
|
|
517
|
+
async function readFilters(filters, basePath = "") {
|
|
518
|
+
const ret = {};
|
|
519
|
+
for (const [name, filterPath] of Object.entries(filters)) {
|
|
520
|
+
const filePaths = (0, glob.globSync)(path.join(basePath, filterPath), { windowsPathsNoEscape: true });
|
|
521
|
+
for (const filePath of filePaths) ret[name] = await require_esm.importModule(path.resolve(filePath));
|
|
522
|
+
}
|
|
523
|
+
return ret;
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* Loads configuration from an external file with variable rendering.
|
|
527
|
+
* This is a convenience wrapper that combines renderVarsInObject and maybeLoadFromExternalFile.
|
|
528
|
+
*
|
|
529
|
+
* Use this for simple config fields that:
|
|
530
|
+
* - Need variable rendering ({{ vars.x }}, {{ env.X }})
|
|
531
|
+
* - May reference external files (file://path.json)
|
|
532
|
+
* - Don't have nested file references that need loading
|
|
533
|
+
*
|
|
534
|
+
* For fields with nested file references (like response_format.schema),
|
|
535
|
+
* use maybeLoadResponseFormatFromExternalFile instead.
|
|
536
|
+
*
|
|
537
|
+
* @param config - The configuration to process
|
|
538
|
+
* @param vars - Variables for template rendering
|
|
539
|
+
* @returns The processed configuration with variables rendered and files loaded
|
|
540
|
+
*/
|
|
541
|
+
function maybeLoadFromExternalFileWithVars(config, vars) {
|
|
542
|
+
return maybeLoadFromExternalFile(renderVarsInObject(config, vars));
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* Loads response_format configuration from an external file with variable rendering.
|
|
546
|
+
*
|
|
547
|
+
* This function handles the special case where response_format may contain:
|
|
548
|
+
* 1. A top-level file reference (file://format.json)
|
|
549
|
+
* 2. A nested schema reference for json_schema type (schema: file://schema.json)
|
|
550
|
+
*
|
|
551
|
+
* Both levels need variable rendering and file loading.
|
|
552
|
+
*
|
|
553
|
+
* @param responseFormat - The response_format configuration
|
|
554
|
+
* @param vars - Variables for template rendering
|
|
555
|
+
* @returns The processed response_format with all files loaded
|
|
556
|
+
*/
|
|
557
|
+
function maybeLoadResponseFormatFromExternalFile(responseFormat, vars) {
|
|
558
|
+
if (responseFormat === void 0 || responseFormat === null) return responseFormat;
|
|
559
|
+
const loaded = maybeLoadFromExternalFile(renderVarsInObject(responseFormat, vars));
|
|
560
|
+
if (!loaded || typeof loaded !== "object") return loaded;
|
|
561
|
+
if (loaded.type === "json_schema") {
|
|
562
|
+
const nestedSchema = loaded.schema || loaded.json_schema?.schema;
|
|
563
|
+
if (nestedSchema) {
|
|
564
|
+
const loadedSchema = maybeLoadFromExternalFile(renderVarsInObject(nestedSchema, vars));
|
|
565
|
+
if (loaded.schema !== void 0) return {
|
|
566
|
+
...loaded,
|
|
567
|
+
schema: loadedSchema
|
|
568
|
+
};
|
|
569
|
+
else if (loaded.json_schema?.schema !== void 0) return {
|
|
570
|
+
...loaded,
|
|
571
|
+
json_schema: {
|
|
572
|
+
...loaded.json_schema,
|
|
573
|
+
schema: loadedSchema
|
|
574
|
+
}
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
return loaded;
|
|
579
|
+
}
|
|
580
|
+
/**
|
|
581
|
+
* Renders variables in a tools object and loads from external file if applicable.
|
|
582
|
+
* This function combines renderVarsInObject and maybeLoadFromExternalFile into a single step
|
|
583
|
+
* specifically for handling tools configurations.
|
|
584
|
+
*
|
|
585
|
+
* Supports loading from JSON, YAML, Python, and JavaScript files.
|
|
586
|
+
*
|
|
587
|
+
* @param tools - The tools configuration object or array to process.
|
|
588
|
+
* @param vars - Variables to use for rendering.
|
|
589
|
+
* @returns The processed tools configuration with variables rendered and content loaded from files if needed.
|
|
590
|
+
* @throws {Error} If the loaded tools are in an invalid format
|
|
591
|
+
*/
|
|
592
|
+
async function maybeLoadToolsFromExternalFile(tools, vars) {
|
|
593
|
+
const rendered = renderVarsInObject(tools, vars);
|
|
594
|
+
if (typeof rendered === "string" && rendered.startsWith("file://")) {
|
|
595
|
+
const { filePath, functionName } = parseFileUrl(rendered);
|
|
596
|
+
if (functionName && (filePath.endsWith(".py") || require_fileExtensions.isJavascriptFile(filePath))) {
|
|
597
|
+
const fileType = filePath.endsWith(".py") ? "Python" : "JavaScript";
|
|
598
|
+
require_logger.logger.debug(`[maybeLoadToolsFromExternalFile] Loading tools from ${fileType} file: ${filePath}:${functionName}`);
|
|
599
|
+
try {
|
|
600
|
+
let toolDefinitions;
|
|
601
|
+
if (filePath.endsWith(".py")) {
|
|
602
|
+
const absPath = require_esm.safeResolve(require_logger.state.basePath || process.cwd(), filePath);
|
|
603
|
+
require_logger.logger.debug(`[maybeLoadToolsFromExternalFile] Resolved Python path: ${absPath}`);
|
|
604
|
+
toolDefinitions = await require_pythonUtils.runPython(absPath, functionName, []);
|
|
605
|
+
} else {
|
|
606
|
+
const absPath = require_esm.safeResolve(require_logger.state.basePath || process.cwd(), filePath);
|
|
607
|
+
require_logger.logger.debug(`[maybeLoadToolsFromExternalFile] Resolved JavaScript path: ${absPath}`);
|
|
608
|
+
const module = await require_esm.importModule(absPath);
|
|
609
|
+
const fn = module[functionName] || module.default?.[functionName];
|
|
610
|
+
if (typeof fn !== "function") {
|
|
611
|
+
const availableExports = Object.keys(module).filter((k) => k !== "default");
|
|
612
|
+
const basePath = require_logger.state.basePath || process.cwd();
|
|
613
|
+
throw new Error(`Function "${functionName}" not found in ${filePath}. Available exports: ${availableExports.length > 0 ? availableExports.join(", ") : "(none)"}\nResolved from: ${basePath}`);
|
|
614
|
+
}
|
|
615
|
+
toolDefinitions = await Promise.resolve(fn());
|
|
616
|
+
}
|
|
617
|
+
if (!toolDefinitions || typeof toolDefinitions === "string" || typeof toolDefinitions === "number" || typeof toolDefinitions === "boolean") throw new Error(`Function "${functionName}" must return an array or object of tool definitions, but returned: ${toolDefinitions === null ? "null" : typeof toolDefinitions}`);
|
|
618
|
+
require_logger.logger.debug(`[maybeLoadToolsFromExternalFile] Successfully loaded ${Array.isArray(toolDefinitions) ? toolDefinitions.length : "object"} tools`);
|
|
619
|
+
return toolDefinitions;
|
|
620
|
+
} catch (err) {
|
|
621
|
+
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
622
|
+
const basePath = require_logger.state.basePath || process.cwd();
|
|
623
|
+
throw new Error(`Failed to load tools from ${rendered}:\n${errorMessage}\n\nMake sure the function "${functionName}" exists and returns a valid tool definition array.\nResolved from: ${basePath}`);
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
if (filePath.endsWith(".py") || require_fileExtensions.isJavascriptFile(filePath)) {
|
|
627
|
+
const ext = filePath.endsWith(".py") ? "Python" : "JavaScript";
|
|
628
|
+
const basePath = require_logger.state.basePath || process.cwd();
|
|
629
|
+
throw new Error(`Cannot load tools from ${rendered}\n${ext} files require a function name. Use this format:\n tools: file://${filePath}:get_tools\n\nYour ${ext} file should export a function that returns tool definitions:\n` + (filePath.endsWith(".py") ? ` def get_tools():\n return [{"type": "function", "function": {...}}]` : ` module.exports.get_tools = () => [{ type: "function", function: {...} }];`) + `\n\nResolved from: ${basePath}`);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
if (Array.isArray(rendered)) {
|
|
633
|
+
const results = await Promise.all(rendered.map((item) => maybeLoadToolsFromExternalFile(item, vars)));
|
|
634
|
+
if (results.every((r) => Array.isArray(r))) return results.flat();
|
|
635
|
+
return results;
|
|
636
|
+
}
|
|
637
|
+
if (typeof rendered !== "string") return rendered;
|
|
638
|
+
const loaded = maybeLoadFromExternalFile(rendered);
|
|
639
|
+
if (loaded !== void 0 && loaded !== null && typeof loaded === "string") {
|
|
640
|
+
if (loaded.startsWith("file://")) throw new Error(`Failed to load tools from ${loaded}\nEnsure the file exists and contains valid JSON or YAML tool definitions.`);
|
|
641
|
+
if (loaded.includes("def ") || loaded.includes("import ")) throw new Error("Invalid tools configuration: file appears to contain Python code.\nPython files require a function name. Use this format:\n tools: file://tools.py:get_tools");
|
|
642
|
+
throw new Error("Invalid tools configuration: expected an array or object, but got a string.\nIf using file://, ensure the file contains valid JSON or YAML tool definitions.");
|
|
643
|
+
}
|
|
644
|
+
return loaded;
|
|
645
|
+
}
|
|
646
|
+
//#endregion
|
|
647
|
+
//#region src/googleSheets.ts
|
|
648
|
+
async function checkGoogleSheetAccess(url) {
|
|
649
|
+
try {
|
|
650
|
+
const response = await require_fetch.fetchWithProxy(url);
|
|
651
|
+
if (response.ok) return {
|
|
652
|
+
public: true,
|
|
653
|
+
status: response.status
|
|
654
|
+
};
|
|
655
|
+
else return {
|
|
656
|
+
public: false,
|
|
657
|
+
status: response.status
|
|
658
|
+
};
|
|
659
|
+
} catch (error) {
|
|
660
|
+
require_logger.logger.error(`Error checking sheet access: ${error}`);
|
|
661
|
+
return { public: false };
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
async function fetchCsvFromGoogleSheetUnauthenticated(url) {
|
|
665
|
+
const { parse: parseCsv } = await import("csv-parse/sync");
|
|
666
|
+
const gid = new URL(url).searchParams.get("gid");
|
|
667
|
+
const response = await require_fetch.fetchWithProxy(`${url.replace(/\/edit.*$/, "/export")}?format=csv${gid ? `&gid=${gid}` : ""}`);
|
|
668
|
+
if (response.status !== 200) throw new Error(`Failed to fetch CSV from Google Sheets URL: ${url}`);
|
|
669
|
+
return parseCsv(await response.text(), { columns: true });
|
|
670
|
+
}
|
|
671
|
+
async function fetchCsvFromGoogleSheetAuthenticated(url) {
|
|
672
|
+
const { sheets: googleSheets, auth: googleAuth } = await import("@googleapis/sheets");
|
|
673
|
+
const auth = new googleAuth.GoogleAuth({ scopes: ["https://www.googleapis.com/auth/spreadsheets.readonly"] });
|
|
674
|
+
const sheets = googleSheets("v4");
|
|
675
|
+
const match = url.match(/\/d\/([^/]+)/);
|
|
676
|
+
if (!match) throw new Error(`Invalid Google Sheets URL: ${url}`);
|
|
677
|
+
const spreadsheetId = match[1];
|
|
678
|
+
let range;
|
|
679
|
+
const gid = Number(new URL(url).searchParams.get("gid"));
|
|
680
|
+
if (gid) {
|
|
681
|
+
const sheet = (await sheets.spreadsheets.get({
|
|
682
|
+
spreadsheetId,
|
|
683
|
+
auth
|
|
684
|
+
})).data.sheets?.find((sheet) => sheet.properties?.sheetId === gid);
|
|
685
|
+
if (!sheet || !sheet.properties?.title) throw new Error(`Sheet not found for gid: ${gid}`);
|
|
686
|
+
range = sheet.properties.title;
|
|
687
|
+
} else {
|
|
688
|
+
const firstSheet = (await sheets.spreadsheets.get({
|
|
689
|
+
spreadsheetId,
|
|
690
|
+
auth
|
|
691
|
+
})).data.sheets?.[0];
|
|
692
|
+
if (!firstSheet || !firstSheet.properties?.title) throw new Error(`No sheets found in spreadsheet`);
|
|
693
|
+
range = firstSheet.properties.title;
|
|
694
|
+
}
|
|
695
|
+
const rows = (await sheets.spreadsheets.values.get({
|
|
696
|
+
spreadsheetId,
|
|
697
|
+
range,
|
|
698
|
+
auth
|
|
699
|
+
})).data.values;
|
|
700
|
+
if (!rows?.length) throw new Error(`No data found in Google Sheets URL: ${url}`);
|
|
701
|
+
const headers = rows[0];
|
|
702
|
+
return rows.slice(1).map((row) => {
|
|
703
|
+
const csvRow = {};
|
|
704
|
+
headers.forEach((header, index) => {
|
|
705
|
+
csvRow[header] = row[index] ?? "";
|
|
706
|
+
});
|
|
707
|
+
return csvRow;
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
async function fetchCsvFromGoogleSheet(url) {
|
|
711
|
+
const { public: isPublic } = await checkGoogleSheetAccess(url);
|
|
712
|
+
require_logger.logger.debug(`Google Sheets URL: ${url}, isPublic: ${isPublic}`);
|
|
713
|
+
if (isPublic) return fetchCsvFromGoogleSheetUnauthenticated(url);
|
|
714
|
+
return fetchCsvFromGoogleSheetAuthenticated(url);
|
|
715
|
+
}
|
|
716
|
+
async function writeCsvToGoogleSheet(rows, url) {
|
|
717
|
+
const { sheets: googleSheets, auth: googleAuth } = await import("@googleapis/sheets");
|
|
718
|
+
const auth = new googleAuth.GoogleAuth({ scopes: ["https://www.googleapis.com/auth/spreadsheets"] });
|
|
719
|
+
const sheets = googleSheets("v4");
|
|
720
|
+
const match = url.match(/\/d\/([^/]+)/);
|
|
721
|
+
if (!match) throw new Error(`Invalid Google Sheets URL: ${url}`);
|
|
722
|
+
const spreadsheetId = match[1];
|
|
723
|
+
const headers = Object.keys(rows[0]);
|
|
724
|
+
const values = [headers, ...rows.map((row) => headers.map((header) => row[header]))];
|
|
725
|
+
const getColumnLetter = (col) => {
|
|
726
|
+
let letter = "";
|
|
727
|
+
while (col > 0) {
|
|
728
|
+
col--;
|
|
729
|
+
letter = String.fromCharCode(65 + col % 26) + letter;
|
|
730
|
+
col = Math.floor(col / 26);
|
|
731
|
+
}
|
|
732
|
+
return letter;
|
|
733
|
+
};
|
|
734
|
+
const numRows = values.length;
|
|
735
|
+
const numCols = headers.length;
|
|
736
|
+
const endColumn = getColumnLetter(numCols);
|
|
737
|
+
let range;
|
|
738
|
+
const gid = Number(new URL(url).searchParams.get("gid"));
|
|
739
|
+
if (gid) {
|
|
740
|
+
const sheet = (await sheets.spreadsheets.get({
|
|
741
|
+
spreadsheetId,
|
|
742
|
+
auth
|
|
743
|
+
})).data.sheets?.find((sheet) => sheet.properties?.sheetId === gid);
|
|
744
|
+
if (!sheet || !sheet.properties?.title) throw new Error(`Sheet not found for gid: ${gid}`);
|
|
745
|
+
range = `${sheet.properties.title}!A1:${endColumn}${numRows}`;
|
|
746
|
+
} else {
|
|
747
|
+
const newSheetTitle = `Sheet${Date.now()}`;
|
|
748
|
+
await sheets.spreadsheets.batchUpdate({
|
|
749
|
+
spreadsheetId,
|
|
750
|
+
auth,
|
|
751
|
+
requestBody: { requests: [{ addSheet: { properties: { title: newSheetTitle } } }] }
|
|
752
|
+
});
|
|
753
|
+
range = `${newSheetTitle}!A1:${endColumn}${numRows}`;
|
|
754
|
+
}
|
|
755
|
+
require_logger.logger.debug(`Writing CSV to Google Sheets URL: ${url} with ${values.length} rows`);
|
|
756
|
+
await sheets.spreadsheets.values.update({
|
|
757
|
+
spreadsheetId,
|
|
758
|
+
range,
|
|
759
|
+
valueInputOption: "USER_ENTERED",
|
|
760
|
+
auth,
|
|
761
|
+
requestBody: { values }
|
|
762
|
+
});
|
|
763
|
+
}
|
|
764
|
+
//#endregion
|
|
765
|
+
//#region src/util/evalCsv.ts
|
|
766
|
+
async function streamEvalCsv(evalRecord, options) {
|
|
767
|
+
const table = await evalRecord.getTable();
|
|
768
|
+
if (!table) return;
|
|
769
|
+
const escapeCsv = (val) => {
|
|
770
|
+
const str = String(val ?? "");
|
|
771
|
+
if (str.includes(",") || str.includes("\"") || str.includes("\n")) return `"${str.replace(/"/g, "\"\"")}"`;
|
|
772
|
+
return str;
|
|
773
|
+
};
|
|
774
|
+
const headers = [...table.head.vars, ...table.head.prompts.map((p) => `[${p.provider}] ${p.label}`)];
|
|
775
|
+
await options.write(headers.map(escapeCsv).join(",") + "\n");
|
|
776
|
+
for (const row of table.body) {
|
|
777
|
+
const outputTexts = row.outputs.map((o) => {
|
|
778
|
+
return `[${o.pass ? "PASS" : "FAIL"}] ${o.text}`;
|
|
779
|
+
});
|
|
780
|
+
const cells = [...row.vars, ...outputTexts];
|
|
781
|
+
await options.write(cells.map(escapeCsv).join(",") + "\n");
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
//#endregion
|
|
785
|
+
//#region src/util/output.ts
|
|
786
|
+
const outputToSimpleString = (output) => {
|
|
787
|
+
const passFailText = output.pass ? "[PASS]" : output.failureReason === require_types.ResultFailureReason.ASSERT ? "[FAIL]" : "[ERROR]";
|
|
788
|
+
const namedScoresText = Object.entries(output.namedScores).map(([name, value]) => `${name}: ${value?.toFixed(2)}`).join(", ");
|
|
789
|
+
const scoreText = namedScoresText.length > 0 ? `(${output.score?.toFixed(2)}, ${namedScoresText})` : `(${output.score?.toFixed(2)})`;
|
|
790
|
+
const gradingResultText = output.gradingResult ? `${output.pass ? "Pass" : "Fail"} Reason: ${output.gradingResult.reason}` : "";
|
|
791
|
+
return dedent.default`
|
|
792
|
+
${passFailText} ${scoreText}
|
|
793
|
+
|
|
794
|
+
${output.text}
|
|
795
|
+
|
|
796
|
+
${gradingResultText}
|
|
797
|
+
`.trim();
|
|
798
|
+
};
|
|
799
|
+
function sanitizeConfigForOutput(config) {
|
|
800
|
+
return require_logger.sanitizeObject(config, {
|
|
801
|
+
context: "output config",
|
|
802
|
+
throwOnError: true,
|
|
803
|
+
maxDepth: Number.POSITIVE_INFINITY
|
|
804
|
+
});
|
|
805
|
+
}
|
|
806
|
+
function createOutputMetadata(evalRecord) {
|
|
807
|
+
let evaluationCreatedAt;
|
|
808
|
+
if (evalRecord.createdAt) try {
|
|
809
|
+
const date = new Date(evalRecord.createdAt);
|
|
810
|
+
evaluationCreatedAt = Number.isNaN(date.getTime()) ? void 0 : date.toISOString();
|
|
811
|
+
} catch {
|
|
812
|
+
evaluationCreatedAt = void 0;
|
|
813
|
+
}
|
|
814
|
+
return {
|
|
815
|
+
promptfooVersion: require_fetch.VERSION,
|
|
816
|
+
nodeVersion: process.version,
|
|
817
|
+
platform: os.platform(),
|
|
818
|
+
arch: os.arch(),
|
|
819
|
+
exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
820
|
+
evaluationCreatedAt,
|
|
821
|
+
author: evalRecord.author
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
/**
|
|
825
|
+
* JSON writer with improved error handling for large datasets.
|
|
826
|
+
* Provides helpful error messages when memory limits are exceeded.
|
|
827
|
+
*/
|
|
828
|
+
async function writeJsonOutputSafely(outputPath, evalRecord, shareableUrl) {
|
|
829
|
+
const metadata = createOutputMetadata(evalRecord);
|
|
830
|
+
try {
|
|
831
|
+
const summary = await evalRecord.toEvaluateSummary();
|
|
832
|
+
const redactedConfig = sanitizeConfigForOutput(evalRecord.config);
|
|
833
|
+
const outputData = {
|
|
834
|
+
evalId: evalRecord.id,
|
|
835
|
+
results: summary,
|
|
836
|
+
config: redactedConfig,
|
|
837
|
+
shareableUrl,
|
|
838
|
+
metadata
|
|
839
|
+
};
|
|
840
|
+
const jsonString = JSON.stringify(outputData, null, 2);
|
|
841
|
+
await fs_promises.writeFile(outputPath, jsonString);
|
|
842
|
+
} catch (error) {
|
|
843
|
+
const msg = error?.message ?? "";
|
|
844
|
+
const isStringLen = error instanceof RangeError && msg.includes("Invalid string length");
|
|
845
|
+
const isHeapOOM = /heap out of memory|Array buffer allocation failed|ERR_STRING_TOO_LONG/i.test(msg);
|
|
846
|
+
if (isStringLen || isHeapOOM) {
|
|
847
|
+
const resultCount = await evalRecord.getResultsCount();
|
|
848
|
+
require_logger.logger.error(`Dataset too large for JSON export (${resultCount} results).`);
|
|
849
|
+
throw new Error(`Dataset too large for JSON export. The evaluation has ${resultCount} results which exceeds memory limits. Consider using JSONL format instead: --output output.jsonl`);
|
|
850
|
+
} else throw error;
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
async function writeOutput(outputPath, evalRecord, shareableUrl) {
|
|
854
|
+
if (outputPath.match(/^https:\/\/docs\.google\.com\/spreadsheets\//)) {
|
|
855
|
+
const table = await evalRecord.getTable();
|
|
856
|
+
require_invariant.invariant(table, "Table is required");
|
|
857
|
+
const rows = table.body.map((row) => {
|
|
858
|
+
const csvRow = {};
|
|
859
|
+
table.head.vars.forEach((varName, index) => {
|
|
860
|
+
csvRow[varName] = row.vars[index];
|
|
861
|
+
});
|
|
862
|
+
table.head.prompts.forEach((prompt, index) => {
|
|
863
|
+
csvRow[`[${prompt.provider}] ${prompt.label}`] = outputToSimpleString(row.outputs[index]);
|
|
864
|
+
});
|
|
865
|
+
return csvRow;
|
|
866
|
+
});
|
|
867
|
+
require_logger.logger.info(`Writing ${rows.length} rows to Google Sheets...`);
|
|
868
|
+
await writeCsvToGoogleSheet(rows, outputPath);
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
871
|
+
const { data: outputExtension } = require_types.OutputFileExtension.safeParse(path.extname(outputPath).slice(1).toLowerCase());
|
|
872
|
+
require_invariant.invariant(outputExtension, `Unsupported output file format ${outputExtension}. Please use one of: ${require_types.OutputFileExtension.options.join(", ")}.`);
|
|
873
|
+
const outputDir = path.dirname(outputPath);
|
|
874
|
+
await fs_promises.mkdir(outputDir, { recursive: true });
|
|
875
|
+
const metadata = createOutputMetadata(evalRecord);
|
|
876
|
+
if (outputExtension === "csv") {
|
|
877
|
+
const fileHandle = await fs_promises.open(outputPath, "w");
|
|
878
|
+
try {
|
|
879
|
+
await streamEvalCsv(evalRecord, {
|
|
880
|
+
isRedteam: Boolean(evalRecord.config.redteam),
|
|
881
|
+
write: async (data) => {
|
|
882
|
+
await fileHandle.write(data);
|
|
883
|
+
}
|
|
884
|
+
});
|
|
885
|
+
} finally {
|
|
886
|
+
await fileHandle.close();
|
|
887
|
+
}
|
|
888
|
+
} else if (outputExtension === "json") await writeJsonOutputSafely(outputPath, evalRecord, shareableUrl);
|
|
889
|
+
else if (outputExtension === "yaml" || outputExtension === "yml" || outputExtension === "txt") {
|
|
890
|
+
const summary = await evalRecord.toEvaluateSummary();
|
|
891
|
+
const redactedConfig = sanitizeConfigForOutput(evalRecord.config);
|
|
892
|
+
await fs_promises.writeFile(outputPath, js_yaml.default.dump({
|
|
893
|
+
evalId: evalRecord.id,
|
|
894
|
+
results: summary,
|
|
895
|
+
config: redactedConfig,
|
|
896
|
+
shareableUrl,
|
|
897
|
+
metadata
|
|
898
|
+
}));
|
|
899
|
+
} else if (outputExtension === "html") {
|
|
900
|
+
const table = await evalRecord.getTable();
|
|
901
|
+
require_invariant.invariant(table, "Table is required");
|
|
902
|
+
const summary = await evalRecord.toEvaluateSummary();
|
|
903
|
+
const redactedConfig = sanitizeConfigForOutput(evalRecord.config);
|
|
904
|
+
const template = await fs_promises.readFile(path.join(require_esm.getDirectory(), "tableOutput.html"), "utf-8");
|
|
905
|
+
const htmlTable = [[...table.head.vars, ...table.head.prompts.map((prompt) => `[${prompt.provider}] ${prompt.label}`)], ...table.body.map((row) => [...row.vars, ...row.outputs.map(outputToSimpleString)])];
|
|
906
|
+
const htmlOutput = getNunjucksEngine().renderString(template, {
|
|
907
|
+
config: redactedConfig,
|
|
908
|
+
table: htmlTable,
|
|
909
|
+
results: summary
|
|
910
|
+
});
|
|
911
|
+
await fs_promises.writeFile(outputPath, htmlOutput);
|
|
912
|
+
} else if (outputExtension === "jsonl") {
|
|
913
|
+
await fs_promises.writeFile(outputPath, "");
|
|
914
|
+
for await (const batchResults of evalRecord.fetchResultsBatched()) {
|
|
915
|
+
const text = batchResults.map((result) => JSON.stringify(result)).join(os.EOL) + os.EOL;
|
|
916
|
+
await fs_promises.appendFile(outputPath, text);
|
|
917
|
+
}
|
|
918
|
+
} else if (outputExtension === "xml") {
|
|
919
|
+
const summary = await evalRecord.toEvaluateSummary();
|
|
920
|
+
const redactedConfig = sanitizeConfigForOutput(evalRecord.config);
|
|
921
|
+
const sanitizeForXml = (obj) => {
|
|
922
|
+
if (obj === null || obj === void 0) return "";
|
|
923
|
+
if (typeof obj === "boolean" || typeof obj === "number") return String(obj);
|
|
924
|
+
if (typeof obj === "string") return obj;
|
|
925
|
+
if (Array.isArray(obj)) return obj.map(sanitizeForXml);
|
|
926
|
+
if (typeof obj === "object") {
|
|
927
|
+
const sanitized = {};
|
|
928
|
+
for (const [key, value] of Object.entries(obj)) sanitized[key] = sanitizeForXml(value);
|
|
929
|
+
return sanitized;
|
|
930
|
+
}
|
|
931
|
+
return String(obj);
|
|
932
|
+
};
|
|
933
|
+
const xmlData = new fast_xml_parser.XMLBuilder({
|
|
934
|
+
ignoreAttributes: false,
|
|
935
|
+
format: true,
|
|
936
|
+
indentBy: " "
|
|
937
|
+
}).build({ promptfoo: {
|
|
938
|
+
evalId: evalRecord.id,
|
|
939
|
+
results: sanitizeForXml(summary),
|
|
940
|
+
config: sanitizeForXml(redactedConfig),
|
|
941
|
+
shareableUrl: shareableUrl || ""
|
|
942
|
+
} });
|
|
943
|
+
await fs_promises.writeFile(outputPath, xmlData);
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
async function writeMultipleOutputs(outputPaths, evalRecord, shareableUrl) {
|
|
947
|
+
await Promise.all(outputPaths.map((outputPath) => writeOutput(outputPath, evalRecord, shareableUrl)));
|
|
948
|
+
}
|
|
949
|
+
//#endregion
|
|
950
|
+
//#region src/util/runtime.ts
|
|
951
|
+
function printBorder() {
|
|
952
|
+
const border = "=".repeat(require_fetch.TERMINAL_MAX_WIDTH);
|
|
953
|
+
require_logger.logger.info(border);
|
|
954
|
+
}
|
|
955
|
+
//#endregion
|
|
956
|
+
Object.defineProperty(exports, "doesProviderRefMatch", {
|
|
957
|
+
enumerable: true,
|
|
958
|
+
get: function() {
|
|
959
|
+
return doesProviderRefMatch;
|
|
960
|
+
}
|
|
961
|
+
});
|
|
962
|
+
Object.defineProperty(exports, "extractVariablesFromTemplate", {
|
|
963
|
+
enumerable: true,
|
|
964
|
+
get: function() {
|
|
965
|
+
return extractVariablesFromTemplate;
|
|
966
|
+
}
|
|
967
|
+
});
|
|
968
|
+
Object.defineProperty(exports, "extractVariablesFromTemplates", {
|
|
969
|
+
enumerable: true,
|
|
970
|
+
get: function() {
|
|
971
|
+
return extractVariablesFromTemplates;
|
|
972
|
+
}
|
|
973
|
+
});
|
|
974
|
+
Object.defineProperty(exports, "fetchCsvFromGoogleSheet", {
|
|
975
|
+
enumerable: true,
|
|
976
|
+
get: function() {
|
|
977
|
+
return fetchCsvFromGoogleSheet;
|
|
978
|
+
}
|
|
979
|
+
});
|
|
980
|
+
Object.defineProperty(exports, "getNunjucksEngine", {
|
|
981
|
+
enumerable: true,
|
|
982
|
+
get: function() {
|
|
983
|
+
return getNunjucksEngine;
|
|
984
|
+
}
|
|
985
|
+
});
|
|
986
|
+
Object.defineProperty(exports, "getNunjucksEngineForFilePath", {
|
|
987
|
+
enumerable: true,
|
|
988
|
+
get: function() {
|
|
989
|
+
return getNunjucksEngineForFilePath;
|
|
990
|
+
}
|
|
991
|
+
});
|
|
992
|
+
Object.defineProperty(exports, "getProviderDescription", {
|
|
993
|
+
enumerable: true,
|
|
994
|
+
get: function() {
|
|
995
|
+
return getProviderDescription;
|
|
996
|
+
}
|
|
997
|
+
});
|
|
998
|
+
Object.defineProperty(exports, "getResolvedRelativePath", {
|
|
999
|
+
enumerable: true,
|
|
1000
|
+
get: function() {
|
|
1001
|
+
return getResolvedRelativePath;
|
|
1002
|
+
}
|
|
1003
|
+
});
|
|
1004
|
+
Object.defineProperty(exports, "isAnthropicProvider", {
|
|
1005
|
+
enumerable: true,
|
|
1006
|
+
get: function() {
|
|
1007
|
+
return isAnthropicProvider;
|
|
1008
|
+
}
|
|
1009
|
+
});
|
|
1010
|
+
Object.defineProperty(exports, "isGoogleProvider", {
|
|
1011
|
+
enumerable: true,
|
|
1012
|
+
get: function() {
|
|
1013
|
+
return isGoogleProvider;
|
|
1014
|
+
}
|
|
1015
|
+
});
|
|
1016
|
+
Object.defineProperty(exports, "isOpenAiProvider", {
|
|
1017
|
+
enumerable: true,
|
|
1018
|
+
get: function() {
|
|
1019
|
+
return isOpenAiProvider;
|
|
1020
|
+
}
|
|
1021
|
+
});
|
|
1022
|
+
Object.defineProperty(exports, "isProviderAllowed", {
|
|
1023
|
+
enumerable: true,
|
|
1024
|
+
get: function() {
|
|
1025
|
+
return isProviderAllowed;
|
|
1026
|
+
}
|
|
1027
|
+
});
|
|
1028
|
+
Object.defineProperty(exports, "loadFunction", {
|
|
1029
|
+
enumerable: true,
|
|
1030
|
+
get: function() {
|
|
1031
|
+
return loadFunction;
|
|
1032
|
+
}
|
|
1033
|
+
});
|
|
1034
|
+
Object.defineProperty(exports, "maybeLoadConfigFromExternalFile", {
|
|
1035
|
+
enumerable: true,
|
|
1036
|
+
get: function() {
|
|
1037
|
+
return maybeLoadConfigFromExternalFile;
|
|
1038
|
+
}
|
|
1039
|
+
});
|
|
1040
|
+
Object.defineProperty(exports, "maybeLoadFromExternalFile", {
|
|
1041
|
+
enumerable: true,
|
|
1042
|
+
get: function() {
|
|
1043
|
+
return maybeLoadFromExternalFile;
|
|
1044
|
+
}
|
|
1045
|
+
});
|
|
1046
|
+
Object.defineProperty(exports, "maybeLoadFromExternalFileWithVars", {
|
|
1047
|
+
enumerable: true,
|
|
1048
|
+
get: function() {
|
|
1049
|
+
return maybeLoadFromExternalFileWithVars;
|
|
1050
|
+
}
|
|
1051
|
+
});
|
|
1052
|
+
Object.defineProperty(exports, "maybeLoadResponseFormatFromExternalFile", {
|
|
1053
|
+
enumerable: true,
|
|
1054
|
+
get: function() {
|
|
1055
|
+
return maybeLoadResponseFormatFromExternalFile;
|
|
1056
|
+
}
|
|
1057
|
+
});
|
|
1058
|
+
Object.defineProperty(exports, "maybeLoadToolsFromExternalFile", {
|
|
1059
|
+
enumerable: true,
|
|
1060
|
+
get: function() {
|
|
1061
|
+
return maybeLoadToolsFromExternalFile;
|
|
1062
|
+
}
|
|
1063
|
+
});
|
|
1064
|
+
Object.defineProperty(exports, "parseFileUrl", {
|
|
1065
|
+
enumerable: true,
|
|
1066
|
+
get: function() {
|
|
1067
|
+
return parseFileUrl;
|
|
1068
|
+
}
|
|
1069
|
+
});
|
|
1070
|
+
Object.defineProperty(exports, "parsePathOrGlob", {
|
|
1071
|
+
enumerable: true,
|
|
1072
|
+
get: function() {
|
|
1073
|
+
return parsePathOrGlob;
|
|
1074
|
+
}
|
|
1075
|
+
});
|
|
1076
|
+
Object.defineProperty(exports, "printBorder", {
|
|
1077
|
+
enumerable: true,
|
|
1078
|
+
get: function() {
|
|
1079
|
+
return printBorder;
|
|
1080
|
+
}
|
|
1081
|
+
});
|
|
1082
|
+
Object.defineProperty(exports, "readFilters", {
|
|
1083
|
+
enumerable: true,
|
|
1084
|
+
get: function() {
|
|
1085
|
+
return readFilters;
|
|
1086
|
+
}
|
|
1087
|
+
});
|
|
1088
|
+
Object.defineProperty(exports, "renderEnvOnlyInObject", {
|
|
1089
|
+
enumerable: true,
|
|
1090
|
+
get: function() {
|
|
1091
|
+
return renderEnvOnlyInObject;
|
|
1092
|
+
}
|
|
1093
|
+
});
|
|
1094
|
+
Object.defineProperty(exports, "renderVarsInObject", {
|
|
1095
|
+
enumerable: true,
|
|
1096
|
+
get: function() {
|
|
1097
|
+
return renderVarsInObject;
|
|
1098
|
+
}
|
|
1099
|
+
});
|
|
1100
|
+
Object.defineProperty(exports, "setupEnv", {
|
|
1101
|
+
enumerable: true,
|
|
1102
|
+
get: function() {
|
|
1103
|
+
return setupEnv;
|
|
1104
|
+
}
|
|
1105
|
+
});
|
|
1106
|
+
Object.defineProperty(exports, "writeMultipleOutputs", {
|
|
1107
|
+
enumerable: true,
|
|
1108
|
+
get: function() {
|
|
1109
|
+
return writeMultipleOutputs;
|
|
1110
|
+
}
|
|
1111
|
+
});
|
|
1112
|
+
Object.defineProperty(exports, "writeOutput", {
|
|
1113
|
+
enumerable: true,
|
|
1114
|
+
get: function() {
|
|
1115
|
+
return writeOutput;
|
|
1116
|
+
}
|
|
1117
|
+
});
|
|
1118
|
+
|
|
1119
|
+
//# sourceMappingURL=util-CTh0bfOm.cjs.map
|