promptfoo 0.121.4 → 0.121.5

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.
Files changed (346) hide show
  1. package/dist/src/{ListApp-DQkFNqE9.js → ListApp-BRUsT43Y.js} +1 -1
  2. package/dist/src/{accounts-Dy17bs4D.cjs → accounts-BIFntVWB.cjs} +4 -4
  3. package/dist/src/{accounts-F9d_5sMC.js → accounts-CLJHCDDb.js} +6 -6
  4. package/dist/src/{accounts-DhMYUUbu.js → accounts-CaLNYnf7.js} +4 -4
  5. package/dist/src/{accounts-DdJ2pHMI.js → accounts-bnyHT7Ju.js} +5 -5
  6. package/dist/src/{agentic-utils-w68v6_Dz.js → agentic-utils-B5krlibj.js} +3 -3
  7. package/dist/src/{agentic-utils-P172hM8B.js → agentic-utils-Ba67xmgs.js} +2 -2
  8. package/dist/src/{agentic-utils-qFlm6zes.js → agentic-utils-BclbiXiq.js} +3 -3
  9. package/dist/src/{agentic-utils-BpX5b23w.cjs → agentic-utils-D2x0wGhB.cjs} +2 -2
  10. package/dist/src/{agents-CgaMXvLM.js → agents-BGqaTDnr.js} +5 -5
  11. package/dist/src/{agents-8FDnTriG.js → agents-BV9yFpXX.js} +5 -5
  12. package/dist/src/{agents-aYPQLf8W.js → agents-BYdMl1UE.js} +4 -4
  13. package/dist/src/{agents-pQeBEXMm.js → agents-DhxWMCtH.js} +5 -5
  14. package/dist/src/{agents-D7-HGxUj.cjs → agents-DiWmQYH9.cjs} +4 -4
  15. package/dist/src/{agents-BahDpe5G.cjs → agents-WULPVjbH.cjs} +4 -4
  16. package/dist/src/{agents-DJ35I3Nt.js → agents-emVcx3yh.js} +5 -5
  17. package/dist/src/{agents-C-R_jfzI.js → agents-n6vPqV3i.js} +4 -4
  18. package/dist/src/{aimlapi-BCq3MHeL.js → aimlapi-BxqK9HF_.js} +7 -7
  19. package/dist/src/{aimlapi-qcK4OT55.cjs → aimlapi-BzLjZI_m.cjs} +6 -6
  20. package/dist/src/{aimlapi-BD6J9oKt.js → aimlapi-DR4pgeiC.js} +6 -6
  21. package/dist/src/{aimlapi-sgYnkE54.js → aimlapi-uPGp0Zdo.js} +7 -7
  22. package/dist/src/app/app/tsconfig.app.tsbuildinfo +1 -1
  23. package/dist/src/app/assets/Report-vjzrbgce.js +1 -0
  24. package/dist/src/app/assets/index-B3NQ8HTd.js +385 -0
  25. package/dist/src/app/assets/{index-BXGkeMwh.css → index-Cli2yAXv.css} +1 -1
  26. package/dist/src/app/index.html +27 -2
  27. package/dist/src/{audio-DcVKoInv.js → audio-BvpTOArF.js} +4 -4
  28. package/dist/src/{audio-BQtNuYBj.cjs → audio-C0vDeS0j.cjs} +3 -3
  29. package/dist/src/{audio-B7izf48x.js → audio-CScmnmEB.js} +4 -4
  30. package/dist/src/{audio-COrn8rM6.js → audio-Da8U9IS5.js} +3 -3
  31. package/dist/src/{base-fZ9wgg50.js → base-BOMaNEes.js} +3 -3
  32. package/dist/src/{base-PYJvBE1i.js → base-BTux96b1.js} +2 -2
  33. package/dist/src/{base-D-670DX8.cjs → base-Tw6uhH8K.cjs} +2 -2
  34. package/dist/src/{base-yrI1Yal4.js → base-dYsl2hmL.js} +3 -3
  35. package/dist/src/{blobs-D2FAd1Q5.cjs → blobs-B95F_7vE.cjs} +2 -2
  36. package/dist/src/{blobs-C-F78Kfn.js → blobs-BW4U31ue.js} +2 -2
  37. package/dist/src/{blobs-BCZavS8s.js → blobs-D_gg8nbm.js} +3 -3
  38. package/dist/src/{blobs-BQWqnnvL.js → blobs-DjLby-uP.js} +3 -3
  39. package/dist/src/{cache-mb7c8hbp.js → cache-BI5BY7ey.js} +4 -4
  40. package/dist/src/{cache-DbLsVWB2.cjs → cache-BRkhlH3k.cjs} +1 -1
  41. package/dist/src/cache-BlC6aeJ0.js +3 -0
  42. package/dist/src/{cache-D5NZmMiT.js → cache-Bzttsk0X.js} +2 -2
  43. package/dist/src/{cache-C4Xb-hNb.js → cache-Cr-qWIbP.js} +3 -3
  44. package/dist/src/{cache-BIyPcp5v.cjs → cache-DGg-yTZG.cjs} +2 -2
  45. package/dist/src/{chat-Dr3DUQ0D.js → chat-BLOdH60v.js} +12 -12
  46. package/dist/src/{chat-BfPaS15_.js → chat-Cx_LkwvZ.js} +12 -12
  47. package/dist/src/{chat-mW0ORo8G.js → chat-D9nudO9b.js} +4 -4
  48. package/dist/src/{chat-I9izLm49.js → chat-DChSH_Es.js} +12 -12
  49. package/dist/src/{chat-MKxMnZJZ.js → chat-DG2LkwLq.js} +2 -2
  50. package/dist/src/{chat-BPXSW8Bv.cjs → chat-DH97tVV9.cjs} +2 -2
  51. package/dist/src/{chat-0bwXjVP0.js → chat-aMQZw6R7.js} +4 -4
  52. package/dist/src/{chat-CclRbxGf.cjs → chat-vYqqv1gP.cjs} +11 -11
  53. package/dist/src/{chatkit-zUIVoDos.js → chatkit-B8X34dQc.js} +4 -4
  54. package/dist/src/{chatkit-Cv6AhukM.js → chatkit-BXu42Qwt.js} +3 -3
  55. package/dist/src/{chatkit-CJnHRRMM.js → chatkit-CbMRoeYw.js} +4 -4
  56. package/dist/src/{chatkit-BoWoSgXl.cjs → chatkit-D44VyUyB.cjs} +3 -3
  57. package/dist/src/{claude-agent-sdk-CPJo3dBQ.cjs → claude-agent-sdk-BRq0bbIK.cjs} +8 -8
  58. package/dist/src/{claude-agent-sdk-BQNuLaAK.js → claude-agent-sdk-BjriSVRZ.js} +7 -7
  59. package/dist/src/{claude-agent-sdk-Dtq_L-Sc.js → claude-agent-sdk-BzNZeZ0N.js} +7 -7
  60. package/dist/src/{claude-agent-sdk-nfAIcxNf.js → claude-agent-sdk-DYv_AJ8u.js} +7 -7
  61. package/dist/src/cloud-CoD5OacT.js +3 -0
  62. package/dist/src/{cloud-DQZ5sVjW.js → cloud-Da0bofJd.js} +3 -3
  63. package/dist/src/{cloudflare-ai-BIB567w6.js → cloudflare-ai-CXC4b1EU.js} +4 -4
  64. package/dist/src/{cloudflare-ai-DlKr0rY7.js → cloudflare-ai-CyBoIs1Q.js} +6 -6
  65. package/dist/src/{cloudflare-ai-DGLte7Py.js → cloudflare-ai-DGOwgexC.js} +6 -6
  66. package/dist/src/{cloudflare-ai-Dl3N9OVD.cjs → cloudflare-ai-DJv5qnyb.cjs} +4 -4
  67. package/dist/src/{cloudflare-gateway-BDZrYydE.js → cloudflare-gateway-1sAoOyft.js} +5 -5
  68. package/dist/src/{cloudflare-gateway-CiIZHU0Q.js → cloudflare-gateway-D-dnkzCF.js} +5 -5
  69. package/dist/src/{cloudflare-gateway-BYDp495F.cjs → cloudflare-gateway-DKVjkDav.cjs} +3 -3
  70. package/dist/src/{cloudflare-gateway-DI1HNP5F.js → cloudflare-gateway-TJkVrZlB.js} +3 -3
  71. package/dist/src/codex-app-server-CCLjqCh9.js +1915 -0
  72. package/dist/src/codex-app-server-CCe0TiDc.js +1915 -0
  73. package/dist/src/codex-app-server-CPW1LFwh.js +1916 -0
  74. package/dist/src/codex-app-server-VMRnjZ68.cjs +1920 -0
  75. package/dist/src/codex-sdk-1jm_qPHf.js +3 -0
  76. package/dist/src/{codex-sdk-C2_M2pl_.cjs → codex-sdk-Bd8UbO9q.cjs} +5 -5
  77. package/dist/src/{codex-sdk-CpqiOqDO.js → codex-sdk-BgEFQ70r.js} +6 -6
  78. package/dist/src/{codex-sdk-Rtky3M4I.js → codex-sdk-Bzb_TqX9.js} +6 -6
  79. package/dist/src/{codex-sdk-CWEnH70W.cjs → codex-sdk-Danroptg.cjs} +1 -1
  80. package/dist/src/{codex-sdk-CErXn7qh.js → codex-sdk-DfvDTN33.js} +5 -5
  81. package/dist/src/{cometapi-CtJ-mS8R.js → cometapi-B5ImDlSm.js} +8 -8
  82. package/dist/src/{cometapi-UVOryo4W.cjs → cometapi-BgAkuYCw.cjs} +7 -7
  83. package/dist/src/{cometapi-BUlt_ELa.js → cometapi-CC7hWxmX.js} +8 -8
  84. package/dist/src/{cometapi-DT-jlVCB.js → cometapi-CCbpHkuF.js} +7 -7
  85. package/dist/src/{completion-x0a_c2y1.js → completion-2iuYVxwi.js} +6 -6
  86. package/dist/src/{completion-Dnxn7E-j.js → completion-CrD6MQ93.js} +5 -5
  87. package/dist/src/{completion-BozdoXba.cjs → completion-DtQ72Bm3.cjs} +5 -5
  88. package/dist/src/{completion-HUe8wDhZ.js → completion-Vq_ad618.js} +6 -6
  89. package/dist/src/{createHash-ChI45QR1.js → createHash-DPpsZgFF.js} +1 -1
  90. package/dist/src/{createHash-CwDVU5xr.js → createHash-Un4Q_huE.js} +1 -1
  91. package/dist/src/{createHash-B7KvgoOD.cjs → createHash-VvBIc-AW.cjs} +1 -1
  92. package/dist/src/{docker-DCgsveLD.js → docker--3qzPa-6.js} +6 -6
  93. package/dist/src/{docker-DS4_Osau.cjs → docker-D3AY-5F5.cjs} +5 -5
  94. package/dist/src/{docker-CQmlA2NU.js → docker-DCsCDvwM.js} +6 -6
  95. package/dist/src/{docker-ClnmCf1Z.js → docker-Dorv4_Dg.js} +5 -5
  96. package/dist/src/{embedding-I45KG3o7.cjs → embedding-BXhN5lCH.cjs} +5 -5
  97. package/dist/src/{embedding-nFbumxcv.js → embedding-ChS1ivFS.js} +5 -5
  98. package/dist/src/{embedding-D3xTseo7.js → embedding-DNRvZwRN.js} +6 -6
  99. package/dist/src/{embedding-DD9wa3ae.js → embedding-D_bI4NDq.js} +6 -6
  100. package/dist/src/{errors-Cw810C93.js → errors-DFHe4L-n.js} +1 -1
  101. package/dist/src/{esm-Dh4dOLlt.js → esm-B6whoAcf.js} +2 -2
  102. package/dist/src/{esm-C7PnfdF8.js → esm-BRkfNsYs.js} +1 -1
  103. package/dist/src/{esm-tVgYPY-f.js → esm-BX8fwlAO.js} +2 -2
  104. package/dist/src/{esm-CtEPLdAj.cjs → esm-B_rGuPTo.cjs} +1 -1
  105. package/dist/src/{eval-CzJFfFO9.js → eval-BQPLBJbw.js} +1 -1
  106. package/dist/src/{eval-u4UVafl6.js → eval-DJ_4A-tr.js} +14 -14
  107. package/dist/src/evalResult-BBJAHAtw.cjs +2 -0
  108. package/dist/src/evalResult-BBK58h2B.js +3 -0
  109. package/dist/src/{evalResult-KZqXl4XP.cjs → evalResult-Cx-8OWkb.cjs} +28 -10
  110. package/dist/src/{evalResult-D3hVYFis.js → evalResult-D6P5I5il.js} +29 -11
  111. package/dist/src/{evalResult-Bgm9ZH31.js → evalResult-pSvGWFMo.js} +29 -11
  112. package/dist/src/{evaluator-IvuDYSvQ.js → evaluator-D-UIbbYq.js} +845 -98
  113. package/dist/src/evaluator-DgLKaZk8.js +3 -0
  114. package/dist/src/{extractor-Dk6bRWkv.js → extractor-BM3jRERL.js} +5 -5
  115. package/dist/src/{extractor-WVPOrH43.cjs → extractor-Dxr2J_wK.cjs} +5 -5
  116. package/dist/src/{extractor-DNSeBVOJ.js → extractor-DxyiFhPk.js} +6 -6
  117. package/dist/src/{extractor-CAfTSraf.js → extractor-YlZbUMsL.js} +6 -6
  118. package/dist/src/fetch-8viavNv8.js +3 -0
  119. package/dist/src/{fetch-BEWnXrrG.js → fetch-B6ch2nU2.js} +9 -20
  120. package/dist/src/{fetch-Di00EQrc.js → fetch-D9xxyC1p.js} +221 -232
  121. package/dist/src/{fetch-CJU5ELPa.cjs → fetch-NuqXW1Xb.cjs} +221 -244
  122. package/dist/src/{fetch-B0Z3Oe4k.js → fetch-Y5qX_kST.js} +8 -19
  123. package/dist/src/{fileExtensions-BArZuxsI.js → fileExtensions-8CjoL7vB.js} +1 -1
  124. package/dist/src/{fileExtensions-DnqA1y9x.js → fileExtensions-BGh-W-HT.js} +1 -1
  125. package/dist/src/{fileExtensions-bYh77CN8.cjs → fileExtensions-D9h-8Wxg.cjs} +1 -1
  126. package/dist/src/{fileExtensions-AWa2ZML4.js → fileExtensions-DysCsxNG.js} +1 -1
  127. package/dist/src/{formatDuration-DZzPsexs.js → formatDuration-Ch4A7G3o.js} +1 -1
  128. package/dist/src/{genaiTracer-yRuxj9-L.cjs → genaiTracer-BokHC-MW.cjs} +1 -1
  129. package/dist/src/{genaiTracer-DWdZ28hY.js → genaiTracer-C3ZPQU60.js} +1 -1
  130. package/dist/src/{genaiTracer-XnrcgDCe.js → genaiTracer-CFny3gOy.js} +1 -1
  131. package/dist/src/{genaiTracer-COYDi-tC.js → genaiTracer-DxODqT9e.js} +1 -1
  132. package/dist/src/{graders-Zy3x0zqX.js → graders-BoUqsCEm.js} +1303 -2044
  133. package/dist/src/{graders--zknU_uk.cjs → graders-Bw1wk_21.cjs} +1553 -2240
  134. package/dist/src/graders-C84JI-m5.js +2 -0
  135. package/dist/src/graders-CBbd0K0Q.cjs +2 -0
  136. package/dist/src/graders-CbQqpHSN.js +3 -0
  137. package/dist/src/{graders-eIHhRqoC.js → graders-CgPn32yp.js} +1300 -2041
  138. package/dist/src/{graders-pvbReLLn.js → graders-CwrbifOo.js} +747 -1488
  139. package/dist/src/graders-DS42d3ZG.js +2 -0
  140. package/dist/src/{image-9302QVqR.js → image-BeWaInPF.js} +3 -3
  141. package/dist/src/{image-DVz2RiMF.js → image-BmilRNqO.js} +7 -7
  142. package/dist/src/{image-x6KqLQl4.cjs → image-CxJoa3aW.cjs} +6 -6
  143. package/dist/src/{image-De2FBmYV.cjs → image-D10dNAav.cjs} +3 -3
  144. package/dist/src/{image-dnoUgPrC.js → image-Dr_3I3nK.js} +4 -4
  145. package/dist/src/{image-B5Mv-Z3h.js → image-DsGRlkh7.js} +7 -7
  146. package/dist/src/{image-qUpPvmNZ.js → image-a_SGUobh.js} +6 -6
  147. package/dist/src/{image-u7-rKnYU.js → image-qjO6FWPs.js} +4 -4
  148. package/dist/src/index.cjs +1052 -296
  149. package/dist/src/index.d.cts +124 -13
  150. package/dist/src/index.d.ts +125 -14
  151. package/dist/src/index.js +1018 -262
  152. package/dist/src/{interactiveCheck-CLERUB0c.js → interactiveCheck-CCICw2cy.js} +2 -2
  153. package/dist/src/{invariant-BtWWVVhl.js → invariant-B2Rf6avk.js} +1 -1
  154. package/dist/src/{invariant-vgHWClmd.js → invariant-DIYf9sP1.js} +1 -1
  155. package/dist/src/{knowledgeBase-RhFPGWDc.js → knowledgeBase-BBETc5-S.js} +6 -6
  156. package/dist/src/{knowledgeBase-Bpoe_nLu.cjs → knowledgeBase-C8qOo26M.cjs} +5 -5
  157. package/dist/src/{knowledgeBase-lm9RXSAm.js → knowledgeBase-CzAi2rUI.js} +6 -6
  158. package/dist/src/{knowledgeBase-Dgc7CBWF.js → knowledgeBase-Dr3Kib7F.js} +5 -5
  159. package/dist/src/{litellm-C2kqjxqp.js → litellm-BLSiANhk.js} +5 -5
  160. package/dist/src/{litellm-CoyI4IAl.cjs → litellm-CaUmV7Mk.cjs} +4 -4
  161. package/dist/src/{litellm-p37R1dzQ.js → litellm-DQGo_juI.js} +4 -4
  162. package/dist/src/{litellm-DRjpcSa7.js → litellm-DRc4qWfc.js} +5 -5
  163. package/dist/src/{logger-DksKw1Qc.js → logger-BbY6ypFL.js} +2 -2
  164. package/dist/src/{logger-B88EkIn6.js → logger-KD8JjCRJ.js} +2 -2
  165. package/dist/src/{luma-ray-KgTCXrZC.js → luma-ray-B-tNZzqW.js} +6 -6
  166. package/dist/src/{luma-ray-B863CmuZ.js → luma-ray-CtS3OlGq.js} +5 -5
  167. package/dist/src/{luma-ray-BTTLtqQ8.js → luma-ray-PJJgUjOc.js} +6 -6
  168. package/dist/src/{luma-ray-BxVKaW2a.cjs → luma-ray-if-Ml4R9.cjs} +5 -5
  169. package/dist/src/main.js +242 -198
  170. package/dist/src/{messages-zWbkLLHz.js → messages-B9dSjrNf.js} +264 -16
  171. package/dist/src/{messages-811uVVW5.cjs → messages-BnsVHUnm.cjs} +266 -15
  172. package/dist/src/{messages-MYTQ2TWp.js → messages-CI69Lasb.js} +264 -16
  173. package/dist/src/{messages-BTQz42fn.js → messages-CewuNcNS.js} +264 -16
  174. package/dist/src/{meteor-Co1VQ1u5.cjs → meteor-BBGcGeCa.cjs} +1 -1
  175. package/dist/src/{meteor-DuAFv6gF.js → meteor-BKTM-7KS.js} +1 -1
  176. package/dist/src/{meteor-DHdzY1Ss.js → meteor-CeGo0Lu2.js} +2 -2
  177. package/dist/src/{meteor-CU5UAE-H.js → meteor-Wc_aUVvu.js} +2 -2
  178. package/dist/src/{modelslab-wu9yi5GE.js → modelslab-BCLOtfek.js} +7 -7
  179. package/dist/src/{modelslab-Dk1JAtVo.cjs → modelslab-BkapYJhh.cjs} +6 -6
  180. package/dist/src/{modelslab-DIq-6y7x.js → modelslab-D73OnKSx.js} +6 -6
  181. package/dist/src/{modelslab-D0erNWKe.js → modelslab-zpz9JcK0.js} +7 -7
  182. package/dist/src/{nova-reel-CCFRfeRb.js → nova-reel-B8F_TK5w.js} +6 -6
  183. package/dist/src/{nova-reel-DQrm74ng.js → nova-reel-Bx0NFV2f.js} +5 -5
  184. package/dist/src/{nova-reel-gr11WG7f.js → nova-reel-CNGJTLtG.js} +6 -6
  185. package/dist/src/{nova-reel-CrLXVKQf.cjs → nova-reel-DkT7tnoB.cjs} +5 -5
  186. package/dist/src/{nova-sonic-BYdp-QLs.js → nova-sonic-BaXRN1cr.js} +4 -4
  187. package/dist/src/{nova-sonic-TDgrlTk7.js → nova-sonic-BeTRaFOh.js} +4 -4
  188. package/dist/src/{nova-sonic-B_ZXcUJB.js → nova-sonic-CL7Zqv0G.js} +3 -3
  189. package/dist/src/{nova-sonic-i5tUvXKn.cjs → nova-sonic-YT426juD.cjs} +3 -3
  190. package/dist/src/{openai-DhVEmgeZ.js → openai-BMHD2Huo.js} +2 -2
  191. package/dist/src/{openai-Qsvz25mV.js → openai-BT-JvDse.js} +2 -2
  192. package/dist/src/{openai-URNyItar.cjs → openai-Cy1XLs0c.cjs} +1 -1
  193. package/dist/src/{openai-iYtrXzOX.js → openai-D4fxGvRx.js} +1 -1
  194. package/dist/src/{openclaw-CwzlQSQX.js → openclaw-Bq7RVR3k.js} +7 -6
  195. package/dist/src/{openclaw-CLWrW03k.js → openclaw-DA8U4DsD.js} +8 -7
  196. package/dist/src/{openclaw-CnQ363Wi.js → openclaw-DObVgpjC.js} +8 -7
  197. package/dist/src/{openclaw-wX9rtfke.cjs → openclaw-DUBZP3GL.cjs} +8 -7
  198. package/dist/src/{opencode-sdk-BUu5Nevv.js → opencode-sdk-BB40Wir1.js} +4 -4
  199. package/dist/src/{opencode-sdk-GI2KaAXq.js → opencode-sdk-BM1UAIv1.js} +3 -3
  200. package/dist/src/{opencode-sdk-BZ2idgYA.cjs → opencode-sdk-CeqiOcOU.cjs} +4 -4
  201. package/dist/src/{opencode-sdk-BxD8vXp_.js → opencode-sdk-ChdK7F7z.js} +4 -4
  202. package/dist/src/{otlpReceiver-DmVulbhC.js → otlpReceiver-C6thJRXi.js} +4 -4
  203. package/dist/src/{otlpReceiver-B2z58l4e.js → otlpReceiver-CcdIikOu.js} +3 -3
  204. package/dist/src/{otlpReceiver-BfcVq2Nq.cjs → otlpReceiver-DNSQj6bf.cjs} +3 -3
  205. package/dist/src/{otlpReceiver-BntK801g.js → otlpReceiver-UYMQx3sy.js} +4 -4
  206. package/dist/src/{providerRegistry-CPQ_CmVO.js → providerRegistry-1gB5vtzQ.js} +2 -2
  207. package/dist/src/{providerRegistry-CQMdTmHP.cjs → providerRegistry-BESeALrr.cjs} +1 -1
  208. package/dist/src/{providerRegistry-Bvh8mv85.js → providerRegistry-DoACwqhD.js} +1 -1
  209. package/dist/src/{providerRegistry-CWoPjKFZ.js → providerRegistry-PMsleEzs.js} +2 -2
  210. package/dist/src/{providers-Bp4S-FvO.js → providers-BuyzKt7C.js} +1 -1
  211. package/dist/src/{providers-DV3ax9e_.cjs → providers-C7lNVBjX.cjs} +1 -1
  212. package/dist/src/{providers-u9Enmfok.js → providers-CCE2COJi2.js} +1 -1
  213. package/dist/src/{providers-DruaQfwu.js → providers-CJh7iriU.js} +18103 -17952
  214. package/dist/src/{providers-iUt5fbAN.js → providers-Ctcc592x.js} +1 -1
  215. package/dist/src/{providers-Domz_llv.js → providers-DRrerKra.js} +432 -281
  216. package/dist/src/{providers-BV_KMZje.js → providers-DT-GtF2t.js} +19094 -18943
  217. package/dist/src/{providers-1eKkXBKp.cjs → providers-eDShy16E.cjs} +17946 -17795
  218. package/dist/src/{pythonUtils-Cldx7huE.js → pythonUtils-C4tltmIn.js} +3 -3
  219. package/dist/src/{pythonUtils-tAJvvpS-.cjs → pythonUtils-CoLaCwNY.cjs} +3 -3
  220. package/dist/src/{pythonUtils-C2UQ30Rz.js → pythonUtils-DMO68Jg7.js} +3 -3
  221. package/dist/src/{pythonUtils-CnndUbW-.js → pythonUtils-DNqbnRdx.js} +3 -3
  222. package/dist/src/{quiverai-DR0SnIQV.js → quiverai-BSS9a7wV.js} +3 -3
  223. package/dist/src/{quiverai-CtWi6x_g.js → quiverai-Bk1KrvL6.js} +4 -4
  224. package/dist/src/{quiverai-DFotyafY.cjs → quiverai-Bpx6MZ7T.cjs} +3 -3
  225. package/dist/src/{quiverai-aPPvXOgn.js → quiverai-CPKhWgaT.js} +4 -4
  226. package/dist/src/{render-DHIZ6_k8.js → render-7uNJ2V14.js} +2 -2
  227. package/dist/src/{render-CH-62LbA.js → render-DlscvAUJ.js} +1 -1
  228. package/dist/src/{render-CMEpfLaO.js → render-eui5p5mL.js} +2 -2
  229. package/dist/src/{render-CgVDrJmM.js → render-nj-UaPdn.js} +2 -2
  230. package/dist/src/{render-DfQSFxGE.cjs → render-tG6ir9_g.cjs} +1 -1
  231. package/dist/src/{responses--OsX2aYW.js → responses-1ztiVYsx.js} +49 -15
  232. package/dist/src/{responses-DL9m8CyY.js → responses-B8haB-mD.js} +49 -15
  233. package/dist/src/{responses-C-flexAY.js → responses-BiaBguAu.js} +49 -15
  234. package/dist/src/{responses-Bi9vBuW_.cjs → responses-CF-ayauu.cjs} +48 -14
  235. package/dist/src/rubyUtils-4hjGxvju.js +3 -0
  236. package/dist/src/{rubyUtils-DVLeA2jg.js → rubyUtils-BI0p46eZ.js} +3 -3
  237. package/dist/src/{rubyUtils-DsGrTx8R.js → rubyUtils-CIQFnVz4.js} +3 -3
  238. package/dist/src/rubyUtils-CO-tuszQ.cjs +2 -0
  239. package/dist/src/{rubyUtils-CYSQEG4a.js → rubyUtils-DGnoCYL2.js} +3 -3
  240. package/dist/src/{rubyUtils-B6eljPuh.cjs → rubyUtils-DoifqkiA.cjs} +4 -3
  241. package/dist/src/{sagemaker-BveBvuxm.js → sagemaker-BDLeW29y.js} +12 -12
  242. package/dist/src/{sagemaker-D67yzMzs.js → sagemaker-C5T60MKf.js} +13 -13
  243. package/dist/src/{sagemaker-BVkaG2-l.js → sagemaker-ClS_NB07.js} +13 -13
  244. package/dist/src/{sagemaker-XnfhheQv.cjs → sagemaker-ljtY12VM.cjs} +12 -12
  245. package/dist/src/{scanner-1DqWi1Ej.js → scanner-nOCWNIXa.js} +7 -7
  246. package/dist/src/server/index.js +1067 -265
  247. package/dist/src/{server-Dx2TyCH2.cjs → server-BEECpeGG.cjs} +5 -5
  248. package/dist/src/{server-BNYztJkh.js → server-ByiF3qlg.js} +9 -8
  249. package/dist/src/{server-BSB45Nt9.js → server-ByxbqAcQ.js} +8 -7
  250. package/dist/src/{server-DaA2eR26.cjs → server-C0XKRNB_.cjs} +1 -1
  251. package/dist/src/server-C_15p79-.js +3 -0
  252. package/dist/src/{server-D6Il2Sob.js → server-gyd6d4Hc.js} +5 -5
  253. package/dist/src/{signal-CE5G3a7x.js → signal-DTtUuU3l.js} +3 -3
  254. package/dist/src/{slack-acRb0IqQ.js → slack-4zZX1OKP.js} +1 -1
  255. package/dist/src/{slack-1Rhq0EoV.cjs → slack-BLlsDpfG.cjs} +1 -1
  256. package/dist/src/{slack-D5Wpy8LM.js → slack-BPYLQLgb.js} +2 -2
  257. package/dist/src/{slack-DDUe-5MC.js → slack-Bamy_7te.js} +2 -2
  258. package/dist/src/{store-DAAyxcy6.cjs → store-2K0kDi80.cjs} +2 -2
  259. package/dist/src/{store-Dn9HUkdW.js → store-2OXm_eBY.js} +3 -3
  260. package/dist/src/store-BELqNwvz.js +3 -0
  261. package/dist/src/{store-M0b1WfYb.js → store-BPkzEyFM.js} +2 -2
  262. package/dist/src/{store-CYEy5J2D.js → store-CPh25336.js} +3 -3
  263. package/dist/src/store-uQZ4AjPe.cjs +2 -0
  264. package/dist/src/{tables-CsWou1Bx.js → tables-BMSOS2Gg.js} +3 -3
  265. package/dist/src/{tables-DUfh1F7Z.cjs → tables-CXbaZ9y1.cjs} +2 -2
  266. package/dist/src/{tables-C4CH3zRr.js → tables-NlvH23ky.js} +3 -3
  267. package/dist/src/{tables-DQ4WU5tX.js → tables-WgdUZ8Ck.js} +2 -2
  268. package/dist/src/{telemetry-dbaJ0E98.js → telemetry--iqaGyaS.js} +5 -4
  269. package/dist/src/{telemetry-Dsw_faFj.cjs → telemetry-CEQxGnMZ.cjs} +7 -6
  270. package/dist/src/{telemetry-Dvqxv3YC.js → telemetry-CgdVGV8N.js} +4 -3
  271. package/dist/src/{telemetry-CQPez_Jp.js → telemetry-DWdGHvEf.js} +5 -4
  272. package/dist/src/telemetry-DjNoC_n3.cjs +2 -0
  273. package/dist/src/telemetry-ZdPZc0fm.js +3 -0
  274. package/dist/src/{text-BVi-cLPJ.cjs → text-BiNME7QG.cjs} +1 -1
  275. package/dist/src/{text-KvuD2Iko.js → text-D4lz-Jg_.js} +1 -1
  276. package/dist/src/{text-DHxdyQqT.js → text-DDQP0tuQ.js} +1 -1
  277. package/dist/src/{text-CZr46tp_.js → text-NWvfMfkF.js} +1 -1
  278. package/dist/src/{tokenUsageUtils-CXrvO-wA.js → tokenUsageUtils-2wIvAhB3.js} +1 -1
  279. package/dist/src/{tokenUsageUtils-C-bmyHoE.js → tokenUsageUtils-4c780gFd.js} +1 -1
  280. package/dist/src/tokenUsageUtils-BjVkdk18.js +142 -0
  281. package/dist/src/{tokenUsageUtils-Bb7DkZPz.cjs → tokenUsageUtils-C9odhsbW.cjs} +1 -1
  282. package/dist/src/{transcription-DuWDupG7.js → transcription-84t4ALo2.js} +5 -5
  283. package/dist/src/{transcription-CJspiD2c.js → transcription-Bm2emLmJ.js} +6 -6
  284. package/dist/src/{transcription-BvjmiYB1.cjs → transcription-CZ4LG5hQ.cjs} +5 -5
  285. package/dist/src/{transcription-V2HaAmy2.js → transcription-D7Q0vJsh.js} +6 -6
  286. package/dist/src/{transform-zDhMmzwX.js → transform-B-b6Cq-q.js} +5 -5
  287. package/dist/src/transform-BQt0BeAW.js +3 -0
  288. package/dist/src/{transform-DgKlRr73.cjs → transform-Bq5oqC0s.cjs} +1 -1
  289. package/dist/src/{transform-CUnzlsbn.cjs → transform-C9izGX54.cjs} +4 -4
  290. package/dist/src/{transform-DYX1_Xnh.js → transform-CwbAZ84V.js} +5 -5
  291. package/dist/src/{transform-CTeuTR3S.cjs → transform-Dg4LcO1Y.cjs} +6 -6
  292. package/dist/src/{transform-CG0ehZNG.js → transform-DtooZqYY.js} +6 -6
  293. package/dist/src/{transform-UN5UGu8U.js → transform-DzCF-wqV.js} +5 -5
  294. package/dist/src/{transform-lQrDE1BQ.js → transform-_DpNB4qp.js} +5 -5
  295. package/dist/src/{transform-Bbg6A8Jk.js → transform-eGiUAv86.js} +4 -4
  296. package/dist/src/{transformersAvailability-Cju9mHgR.cjs → transformersAvailability-B22swDxr.cjs} +1 -1
  297. package/dist/src/{transformersAvailability-CcHusyhw.js → transformersAvailability-lvCCvuPT.js} +1 -1
  298. package/dist/src/{transformersAvailability-DLlROWhg.js → transformersAvailability-rJGPccjr.js} +1 -1
  299. package/dist/src/{types-Bgh5SOn6.js → types-BDjGOq4E.js} +4 -2
  300. package/dist/src/{types-Dm9JM6Vb.js → types-BVH9hjgW.js} +4 -2
  301. package/dist/src/{types-CeaeaZdP.cjs → types-CgG2rKiW.cjs} +151 -149
  302. package/dist/src/{types-BGQDAP8i.js → types-DNRZVOue.js} +152 -150
  303. package/dist/src/{util-C8e5uydV.js → util-3pBZZb_H.js} +142 -17
  304. package/dist/src/{util-CN3SrLT4.cjs → util-A5_ZsQUn.cjs} +65 -43
  305. package/dist/src/{util-D3q0WQ-0.js → util-B9CNhyac.js} +66 -44
  306. package/dist/src/{util-DxWpWjhc.js → util-BQOCAHQC.js} +700 -575
  307. package/dist/src/{util-BYvQUPp7.js → util-BVXcTwXu.js} +3 -3
  308. package/dist/src/{util-D9TisOyk.js → util-BlFVL0UF.js} +65 -43
  309. package/dist/src/{util-C9J8ahRn.js → util-C-kmRosx.js} +66 -44
  310. package/dist/src/{util-DvU2Pw8c.js → util-DFPeFkiV.js} +3 -3
  311. package/dist/src/{util-DDs-7g6-.js → util-DN0-b81k.js} +3 -3
  312. package/dist/src/{util-olYL5C6N.cjs → util-Dpmm_dAI.cjs} +3 -3
  313. package/dist/src/{util-oGMLA7vc.js → util-Dub0f_ej.js} +700 -575
  314. package/dist/src/{util-Bxn8emtE.cjs → util-DvpHnLt0.cjs} +718 -570
  315. package/dist/src/{utils-DJfvjyMj.js → utils-BUMN8orw.js} +3 -3
  316. package/dist/src/{utils-B05gLxER.cjs → utils-DkVeShIB.cjs} +2 -2
  317. package/dist/src/{utils-BLJKfv0y.js → utils-kt7lv30R.js} +3 -3
  318. package/dist/src/{utils-hXtCYanr.js → utils-o8S5huU2.js} +2 -2
  319. package/dist/src/version-0frU0UTr.js +16 -0
  320. package/dist/src/version-CbpiUINz.js +17 -0
  321. package/dist/src/version-CbuBKu2U.js +16 -0
  322. package/dist/src/version-D9zu9FWB.cjs +27 -0
  323. package/dist/tsconfig.tsbuildinfo +1 -1
  324. package/package.json +22 -20
  325. package/dist/src/app/assets/Report-CQYFezYu.js +0 -1
  326. package/dist/src/app/assets/index-BzJt18Jz.js +0 -385
  327. package/dist/src/cache-Cr9oLMUa.js +0 -3
  328. package/dist/src/cloud-Hphvo8kr.js +0 -3
  329. package/dist/src/codex-sdk-BAmYE7qy.js +0 -3
  330. package/dist/src/evalResult-D8MT9p0s.js +0 -3
  331. package/dist/src/evalResult-Dvc-iucu.cjs +0 -2
  332. package/dist/src/evaluator-CVessDWe.js +0 -3
  333. package/dist/src/fetch-C7bGKDlQ.js +0 -3
  334. package/dist/src/graders-BOAzQEUe.cjs +0 -2
  335. package/dist/src/graders-D4BTsZdG2.js +0 -3
  336. package/dist/src/graders-DOJK1XpV.js +0 -2
  337. package/dist/src/graders-NAv9LcBn.js +0 -2
  338. package/dist/src/rubyUtils-D1L2d3jb.js +0 -3
  339. package/dist/src/rubyUtils-DUbq4tff.cjs +0 -2
  340. package/dist/src/server-DCtHUqlp.js +0 -3
  341. package/dist/src/store-CWOSz6D_.cjs +0 -2
  342. package/dist/src/store-DCDBhv7B.js +0 -3
  343. package/dist/src/telemetry-C1IqxcdW.js +0 -3
  344. package/dist/src/telemetry-C4ZEa_es.cjs +0 -2
  345. package/dist/src/transform-M6ITAESf.js +0 -3
  346. /package/dist/src/{evalResult-DElBuddX.js → evalResult-spPqh1G_.js} +0 -0
@@ -1,26 +1,25 @@
1
1
  #!/usr/bin/env node
2
- import { N as state, O as getEnvString, T as getEnvBool, _ as extractJsonObjects, g as extractFirstJsonObject, j as isCI, s as logger, x as safeJsonStringify } from "./logger-DksKw1Qc.js";
3
- import { i as fetchWithTimeout, l as sleep, m as REQUEST_TIMEOUT_MS, n as fetchWithProxy } from "./fetch-BEWnXrrG.js";
4
- import { t as invariant } from "./invariant-BtWWVVhl.js";
5
- import { o as getUserEmail } from "./accounts-F9d_5sMC.js";
6
- import { C as PolicyObjectSchema, M as MULTI_TURN_STRATEGIES, T as isValidReusablePolicyId, _ as PromptSchema, _t as CODING_AGENT_PLUGINS, nt as LLAMA_GUARD_REPLICATE_PROVIDER, vt as CODING_AGENT_PLUGIN_DESCRIPTIONS, yt as CODING_AGENT_PLUGIN_DISPLAY_NAMES } from "./types-Dm9JM6Vb.js";
7
- import { r as importModule } from "./esm-tVgYPY-f.js";
8
- import { a as getNunjucksEngine, r as extractVariablesFromTemplate } from "./render-CMEpfLaO.js";
9
- import { g as hasCodexDefaultCredentials, h as getCodexDefaultProviders, l as getRemoteGenerationUrl, m as shouldGenerateRemote } from "./server-BNYztJkh.js";
10
- import { $ as DefaultGradingProvider$2, B as MAX_CHARS_PER_MESSAGE_MODIFIER_KEY, C as extractVariablesFromJson, D as isEmptyResponse, E as isBasicRefusal, G as OpenAiModerationProvider, H as getMaxCharsPerMessageModifierValue, J as DefaultEmbeddingProvider$2, K as MistralChatCompletionProvider, L as createProviderRateLimitOptions, O as removePrefix, P as redteamProviderManager, Q as DefaultGradingJsonProvider$2, R as isRateLimitWrapped, S as extractPromptFromTags, T as getShortPluginId, V as getGeneratedPromptOverLimit, W as REDTEAM_MEMORY_POISONING_PLUGIN_ID, Y as DefaultGradingProvider$3, at as AzureChatCompletionProvider, b as extractGoalFromPrompt, et as DefaultLlmRubricProvider, ht as getPoliciesFromCloud, it as AzureEmbeddingProvider, n as loadApiProvider, nt as DefaultSynthesizeProvider$1, ot as getFileHashes, q as MistralEmbeddingProvider, rt as AzureModerationProvider, st as parseScriptParts, tt as DefaultSuggestionsProvider$2, v as checkExfilTracking, x as extractInputVarsFromPrompt, y as extractAllPromptsFromTags } from "./providers-BV_KMZje.js";
11
- import { a as fetchWithCache, o as getCache, s as isCacheEnabled } from "./cache-mb7c8hbp.js";
12
- import { i as isJavascriptFile } from "./fileExtensions-AWa2ZML4.js";
13
- import { _ as parsePathOrGlob, f as maybeLoadConfigFromExternalFile, g as maybeLoadToolsFromExternalFile, p as maybeLoadFromExternalFile, u as getNunjucksEngineForFilePath, x as parseFileUrl } from "./util-DxWpWjhc.js";
14
- import { r as runPython } from "./pythonUtils-CnndUbW-.js";
15
- import { n as transform } from "./transform-UN5UGu8U.js";
16
- import { a as PROMPT_DELIMITER, n as maybeFilePath, r as normalizeInput } from "./utils-BLJKfv0y.js";
17
- import { n as sha256 } from "./createHash-ChI45QR1.js";
18
- import { t as OpenAiChatCompletionProvider } from "./chat-Dr3DUQ0D.js";
19
- import { r as accumulateTokenUsage } from "./tokenUsageUtils-CXrvO-wA.js";
20
- import { x as hasGoogleDefaultCredentials } from "./transform-zDhMmzwX.js";
21
- import { t as AnthropicMessagesProvider } from "./messages-zWbkLLHz.js";
22
- import { t as OpenAiResponsesProvider } from "./responses-DL9m8CyY.js";
23
- import { t as OpenAiEmbeddingProvider } from "./embedding-D3xTseo7.js";
2
+ import { N as state, O as getEnvString, T as getEnvBool, _ as extractJsonObjects, g as extractFirstJsonObject, j as isCI, s as logger, x as safeJsonStringify } from "./logger-BbY6ypFL.js";
3
+ import { i as fetchWithTimeout, l as sleep, m as REQUEST_TIMEOUT_MS, n as fetchWithProxy } from "./fetch-B6ch2nU2.js";
4
+ import { t as invariant } from "./invariant-B2Rf6avk.js";
5
+ import { o as getUserEmail } from "./accounts-CLJHCDDb.js";
6
+ import { C as PolicyObjectSchema, M as MULTI_TURN_STRATEGIES, T as isValidReusablePolicyId, _ as PromptSchema, _t as CODING_AGENT_PLUGINS, vt as CODING_AGENT_PLUGIN_DESCRIPTIONS, yt as CODING_AGENT_PLUGIN_DISPLAY_NAMES } from "./types-BVH9hjgW.js";
7
+ import { r as importModule } from "./esm-BX8fwlAO.js";
8
+ import { a as getNunjucksEngine, r as extractVariablesFromTemplate } from "./render-eui5p5mL.js";
9
+ import { g as hasCodexDefaultCredentials, h as getCodexDefaultProviders, l as getRemoteGenerationUrl, m as shouldGenerateRemote } from "./server-ByiF3qlg.js";
10
+ import { B as extractVariablesFromJson, C as DefaultSuggestionsProvider$2, D as AzureChatCompletionProvider, E as AzureEmbeddingProvider, F as checkExfilTracking, G as removePrefix, H as getShortPluginId, I as extractAllPromptsFromTags, L as extractGoalFromPrompt, R as extractInputVarsFromPrompt, S as DefaultLlmRubricProvider, T as AzureModerationProvider, U as isBasicRefusal, W as isEmptyResponse, Z as redteamProviderManager, at as getMaxCharsPerMessageModifierValue, b as DefaultGradingJsonProvider$2, c as OpenAiModerationProvider, et as createProviderRateLimitOptions, g as DefaultGradingProvider$3, h as DefaultEmbeddingProvider$2, ht as getPoliciesFromCloud, it as getGeneratedPromptOverLimit, l as MistralChatCompletionProvider, n as loadApiProvider, o as getFileHashes, rt as MAX_CHARS_PER_MESSAGE_MODIFIER_KEY, s as parseScriptParts, st as REDTEAM_MEMORY_POISONING_PLUGIN_ID, tt as isRateLimitWrapped, u as MistralEmbeddingProvider, w as DefaultSynthesizeProvider$1, x as DefaultGradingProvider$2, z as extractPromptFromTags } from "./providers-DT-GtF2t.js";
11
+ import { a as fetchWithCache, o as getCache, s as isCacheEnabled } from "./cache-BI5BY7ey.js";
12
+ import { i as isJavascriptFile } from "./fileExtensions-DysCsxNG.js";
13
+ import { r as runPython } from "./pythonUtils-DNqbnRdx.js";
14
+ import { A as maybeLoadFromExternalFile, D as getNunjucksEngineForFilePath, N as maybeLoadToolsFromExternalFile, P as parsePathOrGlob, R as parseFileUrl, k as maybeLoadConfigFromExternalFile } from "./util-BQOCAHQC.js";
15
+ import { r as accumulateTokenUsage } from "./tokenUsageUtils-2wIvAhB3.js";
16
+ import { t as OpenAiChatCompletionProvider } from "./chat-BLOdH60v.js";
17
+ import { x as hasGoogleDefaultCredentials } from "./transform-B-b6Cq-q.js";
18
+ import { t as OpenAiEmbeddingProvider } from "./embedding-DNRvZwRN.js";
19
+ import { t as AnthropicMessagesProvider } from "./messages-B9dSjrNf.js";
20
+ import { t as OpenAiResponsesProvider } from "./responses-B8haB-mD.js";
21
+ import { n as sha256 } from "./createHash-DPpsZgFF.js";
22
+ import { a as PROMPT_DELIMITER, n as maybeFilePath, r as normalizeInput } from "./utils-kt7lv30R.js";
24
23
  import { AsyncLocalStorage } from "node:async_hooks";
25
24
  import z$1 from "zod";
26
25
  import * as fs$2 from "fs";
@@ -37,316 +36,561 @@ import { execFile } from "child_process";
37
36
  import { PythonShell } from "python-shell";
38
37
  import Clone from "rfdc";
39
38
  import cliProgress from "cli-progress";
40
- //#region src/assertions/contextUtils.ts
39
+ //#region src/scheduler/providerCallExecutionContext.ts
40
+ const providerCallExecutionContext = new AsyncLocalStorage();
41
+ function getProviderCallExecutionContext() {
42
+ return providerCallExecutionContext.getStore();
43
+ }
44
+ function withProviderCallExecutionContext(context, fn) {
45
+ return providerCallExecutionContext.run(context, fn);
46
+ }
47
+ //#endregion
48
+ //#region src/matchers/providers.ts
41
49
  /**
42
- * Resolves the context value for context-based assertions.
43
- * Supports extracting context from test variables or transforming from output.
44
- * Can return either a single context string or an array of context chunks.
50
+ * Helper to call provider with consistent context propagation pattern.
51
+ * Spreads the optional context and merges with prompt label and vars.
52
+ * Also reuses evaluator scheduler context for cancellation, rate limits,
53
+ * and grouped grading provider calls when present.
45
54
  *
46
- * @param assertion - The assertion configuration
47
- * @param test - The test case
48
- * @param output - The provider output (after provider transform, before test transform)
49
- * @param prompt - The prompt text
50
- * @param fallbackContext - Optional fallback context (e.g., prompt for context-recall)
51
- * @param providerResponse - Optional full provider response for contextTransform
52
- * @returns The resolved context string or array of strings
53
- * @throws Error if context cannot be resolved or transform fails
55
+ * IMPORTANT: Spread order matters - context is spread first, then prompt/vars
56
+ * override. This ensures originalProvider from context is preserved while
57
+ * allowing this call to specify its own prompt metadata.
54
58
  */
55
- async function resolveContext(assertion, test, output, prompt, fallbackContext, providerResponse) {
56
- let contextValue;
57
- if (test.vars?.context) {
58
- if (typeof test.vars.context === "string") contextValue = test.vars.context;
59
- else if (Array.isArray(test.vars.context)) {
60
- const invalidEntry = [...test.vars.context.entries()].find(([, v]) => typeof v !== "string");
61
- if (invalidEntry) {
62
- const [idx, val] = invalidEntry;
63
- invariant(false, `Invalid context: expected an array of strings, but found ${typeof val} at index ${idx}`);
59
+ function callProviderWithContext(provider, prompt, label, vars, context) {
60
+ const callApiContext = {
61
+ ...context,
62
+ prompt: {
63
+ raw: prompt,
64
+ label
65
+ },
66
+ vars
67
+ };
68
+ const executionContext = getProviderCallExecutionContext();
69
+ const callApiOptions = executionContext?.abortSignal ? { abortSignal: executionContext.abortSignal } : void 0;
70
+ const callApi = () => callApiOptions ? provider.callApi(prompt, callApiContext, callApiOptions) : provider.callApi(prompt, callApiContext);
71
+ const executeCall = () => {
72
+ if (executionContext?.rateLimitRegistry && !isRateLimitWrapped(provider)) return executionContext.rateLimitRegistry.execute(provider, callApi, createProviderRateLimitOptions());
73
+ return callApi();
74
+ };
75
+ if (executionContext?.providerCallQueue) return executionContext.providerCallQueue.enqueue(provider.id(), executeCall);
76
+ return executeCall();
77
+ }
78
+ async function loadFromProviderOptions(provider) {
79
+ invariant(typeof provider === "object", `Provider must be an object, but received a ${typeof provider}: ${provider}`);
80
+ invariant(!Array.isArray(provider), `Provider must be an object, but received an array: ${JSON.stringify(provider)}`);
81
+ invariant(provider.id, "Provider supplied to assertion must have an id");
82
+ return loadApiProvider(provider.id, {
83
+ options: provider,
84
+ basePath: state.basePath
85
+ });
86
+ }
87
+ function isSimulatedUserProviderConfig(provider) {
88
+ if (typeof provider === "string") return provider === "promptfoo:simulated-user";
89
+ if (!provider || typeof provider !== "object" || Array.isArray(provider)) return false;
90
+ if (typeof provider.id === "function") return provider.id() === "promptfoo:simulated-user";
91
+ const providerId = provider.id;
92
+ if (typeof providerId === "string") return providerId === "promptfoo:simulated-user";
93
+ return Object.values(provider).some((providerTypeConfig) => isSimulatedUserProviderConfig(providerTypeConfig));
94
+ }
95
+ async function getGradingProvider(type, provider, defaultProvider) {
96
+ let finalProvider;
97
+ if (typeof provider === "string") finalProvider = await loadApiProvider(provider, { basePath: state.basePath });
98
+ else if (provider != null && typeof provider === "object" && typeof provider.id === "function") finalProvider = provider;
99
+ else if (provider != null && typeof provider === "object") {
100
+ const typeValue = provider[type];
101
+ if (typeValue) finalProvider = await getGradingProvider(type, typeValue, defaultProvider);
102
+ else if (provider.id) finalProvider = await loadFromProviderOptions(provider);
103
+ else if (Array.isArray(provider)) throw new Error(`Provider must be an object or string, but received an array.\n\nCheck that the provider ${JSON.stringify(provider[0], null, 2)} is not nested in an array.`);
104
+ else throw new Error(`Invalid provider definition for output type '${type}': ${JSON.stringify(provider, null, 2)}`);
105
+ } else {
106
+ const defaultTest = state.config?.defaultTest;
107
+ const defaultTestObj = typeof defaultTest === "object" ? defaultTest : null;
108
+ const cfg = [
109
+ defaultTestObj?.provider || void 0,
110
+ defaultTestObj?.options?.provider?.text || void 0,
111
+ defaultTestObj?.options?.provider || void 0
112
+ ].find((candidateProvider) => {
113
+ if (!candidateProvider) return false;
114
+ if (isSimulatedUserProviderConfig(candidateProvider)) {
115
+ logger.debug("[Grading] Skipping promptfoo:simulated-user as an implicit grader fallback");
116
+ return false;
64
117
  }
65
- contextValue = test.vars.context;
66
- }
67
- } else if (fallbackContext) contextValue = fallbackContext;
68
- if (assertion.contextTransform) try {
69
- const outputForTransform = providerResponse?.providerTransformedOutput ?? output;
70
- const transformed = await transform(assertion.contextTransform, outputForTransform, {
71
- vars: test.vars,
72
- prompt: { label: prompt },
73
- ...providerResponse && providerResponse.metadata && { metadata: providerResponse.metadata }
118
+ return true;
74
119
  });
75
- invariant(typeof transformed === "string" || Array.isArray(transformed) && transformed.every((item) => typeof item === "string"), `contextTransform must return a string or array of strings. Got ${typeof transformed}. Check your transform expression: ${assertion.contextTransform}`);
76
- contextValue = transformed;
77
- } catch (error) {
78
- throw new Error(`Failed to transform context using expression '${assertion.contextTransform}': ${error instanceof Error ? error.message : String(error)}`);
120
+ if (cfg) {
121
+ finalProvider = await getGradingProvider(type, cfg, defaultProvider);
122
+ if (finalProvider) logger.debug("[Grading] Using provider from defaultTest fallback", { providerId: finalProvider.id() });
123
+ } else finalProvider = defaultProvider;
79
124
  }
80
- invariant(typeof contextValue === "string" && contextValue.length > 0 || Array.isArray(contextValue) && contextValue.length > 0 && contextValue.every((item) => typeof item === "string" && item.length > 0), "Context is required for context-based assertions. Provide either a \"context\" variable (string or array of strings) in your test case or use \"contextTransform\" to extract context from the provider response.");
81
- return contextValue;
125
+ return finalProvider;
82
126
  }
83
- /**
84
- * Serializes context (string or string[]) to a single string for prompts.
85
- * Joins chunks with double newlines to preserve separation.
86
- */
87
- function serializeContext(context) {
88
- return Array.isArray(context) ? context.join("\n\n") : context;
127
+ async function getAndCheckProvider(type, provider, defaultProvider, checkName) {
128
+ const matchedProvider = await getGradingProvider(type, provider, defaultProvider);
129
+ if (!matchedProvider) if (defaultProvider) {
130
+ logger.warn("[Grading] Falling back to default provider", {
131
+ checkName,
132
+ type
133
+ });
134
+ return defaultProvider;
135
+ } else throw new Error(`No provider of type ${type} found for '${checkName}'`);
136
+ let isValidProviderType = true;
137
+ if (type === "embedding") isValidProviderType = "callEmbeddingApi" in matchedProvider || "callSimilarityApi" in matchedProvider;
138
+ else if (type === "classification") isValidProviderType = "callClassificationApi" in matchedProvider;
139
+ else if (type === "moderation") isValidProviderType = "callModerationApi" in matchedProvider;
140
+ if (!isValidProviderType) {
141
+ if (provider) throw new Error(`Provider ${matchedProvider.id()} is not a valid ${type} provider for '${checkName}'`);
142
+ if (defaultProvider) {
143
+ logger.warn("[Grading] Falling back to default provider after type check failed", {
144
+ checkName,
145
+ providerId: matchedProvider.id(),
146
+ type
147
+ });
148
+ return defaultProvider;
149
+ }
150
+ throw new Error(`Provider ${matchedProvider.id()} is not a valid ${type} provider for '${checkName}'`);
151
+ }
152
+ return matchedProvider;
89
153
  }
90
154
  //#endregion
91
- //#region src/assertions/utils.ts
92
- const clone = Clone();
93
- function getFinalTest(test, assertion) {
94
- const ret = clone({
95
- ...test,
96
- ...test.options && test.options.provider && { options: {
97
- ...test.options,
98
- provider: void 0
99
- } },
100
- ...test.provider && { provider: void 0 }
101
- });
102
- ret.options = ret.options || {};
103
- if (test.provider) ret.provider = test.provider;
104
- ret.options.provider = assertion.provider || test?.options?.provider;
105
- ret.options.rubricPrompt = assertion.rubricPrompt || ret.options.rubricPrompt;
106
- return Object.freeze(ret);
107
- }
108
- async function loadFromJavaScriptFile(filePath, functionName, args) {
109
- const requiredModule = await importModule(filePath, functionName);
110
- if (functionName && typeof requiredModule[functionName] === "function") return requiredModule[functionName](...args);
111
- else if (typeof requiredModule === "function") return requiredModule(...args);
112
- else if (requiredModule.default && typeof requiredModule.default === "function") return requiredModule.default(...args);
113
- else throw new Error(`Assertion malformed: ${filePath} must export a function or have a default export as a function`);
114
- }
115
- function processFileReference(fileRef) {
116
- const basePath = state.basePath || "";
117
- const filePath = path.resolve(basePath, fileRef.slice(7));
118
- const fileContent = fs.readFileSync(filePath, "utf8");
119
- const extension = path.extname(filePath);
120
- if ([
121
- ".json",
122
- ".yaml",
123
- ".yml"
124
- ].includes(extension)) return yaml.load(fileContent);
125
- else if (extension === ".txt") return fileContent.trim();
126
- else throw new Error(`Unsupported file type: ${filePath}`);
155
+ //#region src/providers/anthropic/defaults.ts
156
+ const DEFAULT_ANTHROPIC_MODEL = "claude-sonnet-4-6";
157
+ /**
158
+ * Helper function to create a lazy-loaded provider. This allows the .env file to be
159
+ * loaded first before the provider is initialized.
160
+ * @param factory Factory function that creates provider instance with optional env
161
+ * @returns Object with getter that lazily initializes the provider with the latest env
162
+ */
163
+ function createLazyProvider(factory) {
164
+ const instances = /* @__PURE__ */ new Map();
165
+ return { getInstance(env) {
166
+ const cacheKey = env ? JSON.stringify(env) : "";
167
+ if (!instances.has(cacheKey)) instances.set(cacheKey, factory(env));
168
+ return instances.get(cacheKey);
169
+ } };
127
170
  }
128
- function coerceString(value) {
129
- if (typeof value === "string") return value;
130
- return JSON.stringify(value);
171
+ var AnthropicLlmRubricProvider = class extends AnthropicMessagesProvider {
172
+ constructor(modelName, options = {}) {
173
+ const { env, config = {} } = options;
174
+ super(modelName, {
175
+ env,
176
+ config: {
177
+ tool_choice: {
178
+ type: "tool",
179
+ name: "grade_output"
180
+ },
181
+ tools: [{
182
+ name: "grade_output",
183
+ description: "Grade the given output based on specific criteria",
184
+ input_schema: {
185
+ type: "object",
186
+ properties: {
187
+ pass: {
188
+ type: "boolean",
189
+ description: "Whether the output passes the criteria"
190
+ },
191
+ score: {
192
+ type: "number",
193
+ description: "The score assigned to the output"
194
+ },
195
+ reason: {
196
+ type: "string",
197
+ description: "The reason for the given grade"
198
+ }
199
+ },
200
+ required: [
201
+ "pass",
202
+ "score",
203
+ "reason"
204
+ ]
205
+ }
206
+ }],
207
+ ...config
208
+ }
209
+ });
210
+ }
211
+ async callApi(prompt) {
212
+ const result = await super.callApi(prompt);
213
+ if (typeof result.output !== "string") return { error: `Anthropic LLM rubric grader - malformed non-string output\n\n${JSON.stringify(result.output)}` };
214
+ try {
215
+ return { output: JSON.parse(result.output).input };
216
+ } catch (err) {
217
+ return { error: `Anthropic LLM rubric grader - invalid JSON: ${err}\n\n${result.output}` };
218
+ }
219
+ }
220
+ };
221
+ const gradingProviderFactory = createLazyProvider((env) => new AnthropicMessagesProvider(DEFAULT_ANTHROPIC_MODEL, { env }));
222
+ const llmRubricProviderFactory = createLazyProvider((env) => new AnthropicLlmRubricProvider(DEFAULT_ANTHROPIC_MODEL, { env }));
223
+ const webSearchProviderFactory = createLazyProvider((env) => new AnthropicMessagesProvider(DEFAULT_ANTHROPIC_MODEL, {
224
+ env,
225
+ config: { tools: [{
226
+ type: "web_search_20250305",
227
+ name: "web_search",
228
+ max_uses: 5
229
+ }] }
230
+ }));
231
+ /**
232
+ * Gets all default Anthropic providers with the given environment overrides
233
+ * @param env - Optional environment overrides
234
+ * @returns Anthropic provider implementations for various functions
235
+ */
236
+ function getAnthropicProviders(env) {
237
+ const gradingProvider = gradingProviderFactory.getInstance(env);
238
+ return {
239
+ gradingJsonProvider: gradingProvider,
240
+ gradingProvider,
241
+ llmRubricProvider: llmRubricProviderFactory.getInstance(env),
242
+ suggestionsProvider: gradingProvider,
243
+ synthesizeProvider: gradingProvider,
244
+ webSearchProvider: webSearchProviderFactory.getInstance(env)
245
+ };
131
246
  }
132
247
  //#endregion
133
- //#region src/external/prompts/ragas.ts
134
- const ANSWER_RELEVANCY_GENERATE = `Generate question for the given answer.
135
- Answer:\nThe PSLV-C56 mission is scheduled to be launched on Sunday, 30 July 2023 at 06:30 IST / 01:00 UTC. It will be launched from the Satish Dhawan Space Centre, Sriharikota, Andhra Pradesh, India
136
- Question: When is the scheduled launch date and time for the PSLV-C56 mission, and where will it be launched from?
137
-
138
- Answer:{{answer}}
139
- Question:`;
140
- const CONTEXT_RECALL = `Given a context, and an answer, analyze each sentence in the answer and classify if the sentence can be attributed to the given context or not.
141
- Think in steps and reason before coming to conclusion.
142
-
143
- context: Albert Einstein (14 March 1879 – 18 April 1955) was a German-born theoretical physicist,widely held to be one of the greatest and most influential scientists of all time. Best known for developing the theory of relativity, he also made important contributions to quantum mechanics, and was thus a central figure in the revolutionary reshaping of the scientific understanding of nature that modern physics accomplished in the first decades of the twentieth century. His mass–energy equivalence formula E = mc2, which arises from relativity theory, has been called "the world's most famous equation". He received the 1921 Nobel Prize in Physics "for his services to theoretical physics, and especially for his discovery of the law of the photoelectric effect", a pivotal step in the development of quantum theory. His work is also known for its influence on the philosophy of science. In a 1999 poll of 130 leading physicists worldwide by the British journal Physics World, Einstein was ranked the greatest physicist of all time. His intellectual achievements and originality have made Einstein synonymous with genius.
144
- answer: Albert Einstein born in 14 March 1879 was German-born theoretical physicist, widely held to be one of the greatest and most influential scientists of all time. He received the 1921 Nobel Prize in Physics "for his services to theoretical physics. He published 4 papers in 1905. Einstein moved to Switzerland in 1895
145
- classification
146
- 1. Albert Einstein born in 14 March 1879 was German-born theoretical physicist, widely held to be one of the greatest and most influential scientists of all time. The date of birth of Einstein is mentioned clearly in the context. So [Attributed]
147
- 2. He received the 1921 Nobel Prize in Physics "for his services to theoretical physics. The exact sentence is present in the given context. So [Attributed]
148
- 3. He published 4 papers in 1905. There is no mention about papers he wrote in given the context. So [Not Attributed]
149
- 4. Einstein moved to Switzerland in 1895. There is not supporting evidence for this in the given the context. So [Not Attributed]
150
-
151
- context:{{context}}
152
- answer:{{groundTruth}}
153
- classification:
154
- `;
155
- const CONTEXT_RECALL_ATTRIBUTED_TOKEN = "[Attributed]";
156
- const CONTEXT_RECALL_NOT_ATTRIBUTED_TOKEN = "[Not Attributed]";
157
- const CONTEXT_RELEVANCE = `Please extract relevant sentences from the provided context that is absolutely required answer the following query. If no relevant sentences are found, or if you believe the query cannot be answered from the given context, return the phrase "Insufficient Information". While extracting candidate sentences you're not allowed to make any changes to sentences from given context.
158
-
159
- query: {{query}}
160
- context: {{context}}
161
- candidate sentences:
162
- `;
163
- const CONTEXT_RELEVANCE_BAD = "Insufficient Information";
164
- const CONTEXT_FAITHFULNESS_LONGFORM = `Given a question and answer, create one or more statements from each sentence in the given answer.
165
- question: Who was Albert Einstein and what is he best known for?
166
- answer: He was a German-born theoretical physicist, widely acknowledged to be one of the greatest and most influential physicists of all time. He was best known for developing the theory of relativity, he also made important contributions to the development of the theory of quantum mechanics.
167
- statements:\nAlbert Einstein was born in Germany.\nAlbert Einstein was best known for his theory of relativity.
168
- question: Cadmium Chloride is slightly soluble in this chemical, it is also called what?
169
- answer: alcohol
170
- statements:\nCadmium Chloride is slightly soluble in alcohol.
171
- question: Were Shahul and Jithin of the same nationality?
172
- answer: They were from different countries.
173
- statements:\nShahul and Jithin were from different countries.
174
- question:{{question}}
175
- answer: {{answer}}
176
- statements:\n`;
177
- const CONTEXT_FAITHFULNESS_NLI_STATEMENTS = `Prompt: Natural language inference
178
- Consider the given context and following statements, then determine whether they are supported by the information present in the context.Provide a brief explanation for each statement before arriving at the verdict (Yes/No). Provide a final verdict for each statement in order at the end in the given format. Do not deviate from the specified format.
179
-
180
- Context:\nJohn is a student at XYZ University. He is pursuing a degree in Computer Science. He is enrolled in several courses this semester, including Data Structures, Algorithms, and Database Management. John is a diligent student and spends a significant amount of time studying and completing assignments. He often stays late in the library to work on his projects.
181
- statements:\n1. John is majoring in Biology.\n2. John is taking a course on Artificial Intelligence.\n3. John is a dedicated student.\n4. John has a part-time job.\n5. John is interested in computer programming.\n
182
- Answer:
183
- 1. John is majoring in Biology.
184
- Explanation: John's major is explicitly mentioned as Computer Science. There is no information suggesting he is majoring in Biology. Verdict: No.
185
- 2. John is taking a course on Artificial Intelligence.
186
- Explanation: The context mentions the courses John is currently enrolled in, and Artificial Intelligence is not mentioned. Therefore, it cannot be deduced that John is taking a course on AI. Verdict: No.
187
- 3. John is a dedicated student.
188
- Explanation: The prompt states that he spends a significant amount of time studying and completing assignments. Additionally, it mentions that he often stays late in the library to work on his projects, which implies dedication. Verdict: Yes.
189
- 4. John has a part-time job.
190
- Explanation: There is no information given in the context about John having a part-time job. Therefore, it cannot be deduced that John has a part-time job. Verdict: No.
191
- 5. John is interested in computer programming.
192
- Explanation: The context states that John is pursuing a degree in Computer Science, which implies an interest in computer programming. Verdict: Yes.
193
- Final verdict for each statement in order: No. No. Yes. No. Yes.
194
- context:\n{{context}}
195
- statements:\n{{statements|join("\\n")}}
196
- Answer:
197
- `;
248
+ //#region src/providers/github/defaults.ts
249
+ const githubConfig = {
250
+ apiBaseUrl: "https://models.github.ai/inference",
251
+ apiKeyEnvar: "GITHUB_TOKEN"
252
+ };
253
+ const DefaultGitHubGradingProvider = new OpenAiChatCompletionProvider("openai/gpt-5", { config: githubConfig });
254
+ const DefaultGitHubGradingJsonProvider = new OpenAiChatCompletionProvider("openai/gpt-5", { config: {
255
+ ...githubConfig,
256
+ response_format: { type: "json_object" }
257
+ } });
258
+ const DefaultGitHubSuggestionsProvider = new OpenAiChatCompletionProvider("openai/gpt-5", { config: githubConfig });
259
+ new OpenAiChatCompletionProvider("openai/gpt-5-nano", { config: githubConfig });
260
+ new OpenAiChatCompletionProvider("openai/gpt-5-mini", { config: githubConfig });
261
+ new OpenAiChatCompletionProvider("openai/o4-mini", { config: githubConfig });
198
262
  //#endregion
199
- //#region src/prompts/grading.ts
200
- const DEFAULT_GRADING_PROMPT = JSON.stringify([{
201
- role: "system",
202
- content: dedent`You are grading output according to a user-specified rubric. If the statement in the rubric is true, then the output passes the test. You respond with a JSON object with this structure: {reason: string, pass: boolean, score: number}
203
-
204
- Examples:
205
-
206
- <Output>Hello world</Output>
207
- <Rubric>Content contains a greeting</Rubric>
208
- {"reason": "the content contains the word 'Hello'", "pass": true, "score": 1.0}
209
-
210
- <Output>Avast ye swabs, repel the invaders!</Output>
211
- <Rubric>Does not speak like a pirate</Rubric>
212
- {"reason": "'avast ye' is a common pirate term", "pass": false, "score": 0.0}`
213
- }, {
214
- role: "user",
215
- content: "<Output>\n{{ output }}\n</Output>\n<Rubric>\n{{ rubric }}\n</Rubric>"
216
- }]);
217
- const PROMPTFOO_FACTUALITY_PROMPT = JSON.stringify([{
218
- role: "system",
219
- content: dedent`
220
- You are a precise factuality evaluator that compares a submitted answer to an expert answer.
221
-
222
- Your task is to analyze the factual content while ignoring differences in style, grammar, or punctuation.
223
- You must categorize the submission into one of these options:
224
-
225
- (A) The submitted answer is a subset of the expert answer and is fully consistent with it.
226
- (B) The submitted answer is a superset of the expert answer and is fully consistent with it.
227
- (C) The submitted answer contains all the same details as the expert answer.
228
- (D) There is a disagreement between the submitted answer and the expert answer.
229
- (E) The answers differ, but these differences don't matter from the perspective of factuality.
230
-
231
- Respond ONLY with a JSON object in this format:
232
- {
233
- "category": "[LETTER]",
234
- "reason": "[DETAILED EXPLANATION]"
235
- }
236
-
237
- - The "category" must be a single letter A, B, C, D, or E.
238
- - Provide a clear, detailed explanation in the "reason" field.
239
- - Your response must be valid JSON with no additional text.`
240
- }, {
241
- role: "user",
242
- content: dedent`
243
- I need you to compare these answers:
244
-
245
- <question>
246
- {{input}}
247
- </question>
248
-
249
- <expert_answer>
250
- {{ideal}}
251
- </expert_answer>
252
-
253
- <submitted_answer>
254
- {{completion}}
255
- </submitted_answer>
256
-
257
- Please analyze the factual relationship between these answers according to the categories you've been given.`
258
- }]);
259
- const OPENAI_CLOSED_QA_PROMPT = JSON.stringify([{
260
- role: "system",
261
- content: `You are assessing a submitted answer on a given task based on a criterion. Here is the data:
262
- [BEGIN DATA]
263
- ***
264
- [Task]: {{input}}
265
- ***
266
- [Submission]: {{completion}}
267
- ***
268
- [Criterion]: {{criteria}}
269
- ***
270
- [END DATA]
271
- Does the submission meet the criterion? First, write out in a step by step manner your reasoning about the criterion to be sure that your conclusion is correct. Avoid simply stating the correct answers at the outset. Then print only the single character "Y" or "N" (without quotes or punctuation) on its own line corresponding to the correct answer. At the end, repeat just the letter again by itself on a new line.
272
-
273
- Reasoning:`
274
- }]);
275
- const SUGGEST_PROMPTS_SYSTEM_MESSAGE = {
276
- role: "system",
277
- content: `You're helping a scientist who is tuning a prompt for a large language model. You will receive messages, and each message is a full prompt. Generate a candidate variation of the given prompt. This variation will be tested for quality in order to select a winner.
278
-
279
- Substantially revise the prompt, revising its structure and content however necessary to make it perform better, while preserving the original intent and including important details.
280
-
281
- Your output is going to be copied directly into the program. It should contain the prompt ONLY`
263
+ //#region src/providers/mistral/defaults.ts
264
+ const DefaultEmbeddingProvider$1 = new MistralEmbeddingProvider();
265
+ const DefaultGradingProvider$1 = new MistralChatCompletionProvider("mistral-large-latest");
266
+ const DefaultGradingJsonProvider$1 = new MistralChatCompletionProvider("mistral-large-latest", { config: { response_format: { type: "json_object" } } });
267
+ const DefaultSuggestionsProvider$1 = new MistralChatCompletionProvider("mistral-large-latest");
268
+ const DefaultSynthesizeProvider = new MistralChatCompletionProvider("mistral-large-latest");
269
+ //#endregion
270
+ //#region src/providers/openai/defaults.ts
271
+ const DEFAULT_OPENAI_GRADING_MODEL = "gpt-5.4-2026-03-05";
272
+ const DefaultEmbeddingProvider = new OpenAiEmbeddingProvider("text-embedding-3-large");
273
+ const DefaultGradingProvider = new OpenAiChatCompletionProvider(DEFAULT_OPENAI_GRADING_MODEL);
274
+ const DefaultGradingJsonProvider = new OpenAiChatCompletionProvider(DEFAULT_OPENAI_GRADING_MODEL, { config: { response_format: { type: "json_object" } } });
275
+ const DefaultSuggestionsProvider = new OpenAiChatCompletionProvider(DEFAULT_OPENAI_GRADING_MODEL);
276
+ const DefaultModerationProvider = new OpenAiModerationProvider("omni-moderation-latest");
277
+ const DefaultWebSearchProvider = new OpenAiResponsesProvider("gpt-5.4-2026-03-05", { config: { tools: [{ type: "web_search_preview" }] } });
278
+ async function getDefaultProviderPreferences(env) {
279
+ const hasAnthropicCredentials = Boolean(getEnvString("ANTHROPIC_API_KEY") || env?.ANTHROPIC_API_KEY);
280
+ const hasOpenAiCredentials = Boolean(getEnvString("OPENAI_API_KEY") || env?.OPENAI_API_KEY);
281
+ const hasGitHubCredentials = Boolean(getEnvString("GITHUB_TOKEN") || env?.GITHUB_TOKEN);
282
+ const hasGoogleAiStudioCredentials = Boolean(getEnvString("GEMINI_API_KEY") || env?.GEMINI_API_KEY || getEnvString("GOOGLE_API_KEY") || env?.GOOGLE_API_KEY || getEnvString("PALM_API_KEY") || env?.PALM_API_KEY);
283
+ const hasAzureApiKey = getEnvString("AZURE_OPENAI_API_KEY") || env?.AZURE_OPENAI_API_KEY || getEnvString("AZURE_API_KEY") || env?.AZURE_API_KEY;
284
+ const hasAzureClientCreds = (getEnvString("AZURE_CLIENT_ID") || env?.AZURE_CLIENT_ID) && (getEnvString("AZURE_CLIENT_SECRET") || env?.AZURE_CLIENT_SECRET) && (getEnvString("AZURE_TENANT_ID") || env?.AZURE_TENANT_ID);
285
+ const hasMistralCredentials = Boolean(getEnvString("MISTRAL_API_KEY") || env?.MISTRAL_API_KEY);
286
+ const preferAzure = Boolean(!hasOpenAiCredentials && (hasAzureApiKey || hasAzureClientCreds) && (getEnvString("AZURE_DEPLOYMENT_NAME") || env?.AZURE_DEPLOYMENT_NAME) && (getEnvString("AZURE_OPENAI_DEPLOYMENT_NAME") || env?.AZURE_OPENAI_DEPLOYMENT_NAME));
287
+ const preferAnthropic = !hasOpenAiCredentials && hasAnthropicCredentials;
288
+ const shouldUseFallbackDefaults = !preferAzure && !hasOpenAiCredentials && !hasAnthropicCredentials && !hasGoogleAiStudioCredentials;
289
+ const useGoogleVertexDefaults = shouldUseFallbackDefaults ? await hasGoogleDefaultCredentials() : false;
290
+ const useNonGoogleFallbackDefaults = shouldUseFallbackDefaults && !useGoogleVertexDefaults;
291
+ const hasCodexCredentials = useNonGoogleFallbackDefaults && !hasMistralCredentials && hasCodexDefaultCredentials(env);
292
+ return {
293
+ preferAnthropic,
294
+ preferAzure,
295
+ useCodexDefaults: hasCodexCredentials,
296
+ useGitHubDefaults: useNonGoogleFallbackDefaults && !hasMistralCredentials && !hasCodexCredentials && hasGitHubCredentials,
297
+ useGoogleAiStudioDefaults: !hasOpenAiCredentials && !hasAnthropicCredentials && hasGoogleAiStudioCredentials,
298
+ useGoogleVertexDefaults,
299
+ useMistralDefaults: useNonGoogleFallbackDefaults && hasMistralCredentials
300
+ };
301
+ }
302
+ async function getDefaultProviders(env) {
303
+ const { preferAnthropic, preferAzure, useCodexDefaults, useGitHubDefaults, useGoogleAiStudioDefaults, useGoogleVertexDefaults, useMistralDefaults } = await getDefaultProviderPreferences(env);
304
+ let providers;
305
+ if (preferAzure) {
306
+ logger.debug("Using Azure OpenAI default providers");
307
+ const deploymentName = getEnvString("AZURE_OPENAI_DEPLOYMENT_NAME") || env?.AZURE_OPENAI_DEPLOYMENT_NAME;
308
+ if (!deploymentName) throw new Error("AZURE_OPENAI_DEPLOYMENT_NAME must be set when using Azure OpenAI");
309
+ const embeddingDeploymentName = getEnvString("AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME") || env?.AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME || deploymentName;
310
+ const azureProvider = new AzureChatCompletionProvider(deploymentName, { env });
311
+ providers = {
312
+ embeddingProvider: new AzureEmbeddingProvider(embeddingDeploymentName, { env }),
313
+ gradingJsonProvider: azureProvider,
314
+ gradingProvider: azureProvider,
315
+ moderationProvider: DefaultModerationProvider,
316
+ suggestionsProvider: azureProvider,
317
+ synthesizeProvider: azureProvider
318
+ };
319
+ } else if (preferAnthropic) {
320
+ logger.debug("Using Anthropic default providers");
321
+ const anthropicProviders = getAnthropicProviders(env);
322
+ providers = {
323
+ embeddingProvider: DefaultEmbeddingProvider,
324
+ gradingJsonProvider: anthropicProviders.gradingJsonProvider,
325
+ gradingProvider: anthropicProviders.gradingProvider,
326
+ llmRubricProvider: anthropicProviders.llmRubricProvider,
327
+ moderationProvider: DefaultModerationProvider,
328
+ suggestionsProvider: anthropicProviders.suggestionsProvider,
329
+ synthesizeProvider: anthropicProviders.synthesizeProvider,
330
+ webSearchProvider: anthropicProviders.webSearchProvider
331
+ };
332
+ } else if (useGoogleAiStudioDefaults) {
333
+ logger.debug("Using Google AI Studio default providers");
334
+ providers = {
335
+ embeddingProvider: DefaultEmbeddingProvider$2,
336
+ gradingJsonProvider: DefaultGradingJsonProvider$2,
337
+ gradingProvider: DefaultGradingProvider$2,
338
+ llmRubricProvider: DefaultLlmRubricProvider,
339
+ moderationProvider: DefaultModerationProvider,
340
+ suggestionsProvider: DefaultSuggestionsProvider$2,
341
+ synthesizeProvider: DefaultSynthesizeProvider$1
342
+ };
343
+ } else if (useGoogleVertexDefaults) {
344
+ logger.debug("Using Google Vertex default providers");
345
+ providers = {
346
+ embeddingProvider: DefaultEmbeddingProvider$2,
347
+ gradingJsonProvider: DefaultGradingProvider$3,
348
+ gradingProvider: DefaultGradingProvider$3,
349
+ moderationProvider: DefaultModerationProvider,
350
+ suggestionsProvider: DefaultGradingProvider$3,
351
+ synthesizeProvider: DefaultGradingProvider$3
352
+ };
353
+ } else if (useMistralDefaults) {
354
+ logger.debug("Using Mistral default providers");
355
+ providers = {
356
+ embeddingProvider: DefaultEmbeddingProvider$1,
357
+ gradingJsonProvider: DefaultGradingJsonProvider$1,
358
+ gradingProvider: DefaultGradingProvider$1,
359
+ moderationProvider: DefaultModerationProvider,
360
+ suggestionsProvider: DefaultSuggestionsProvider$1,
361
+ synthesizeProvider: DefaultSynthesizeProvider
362
+ };
363
+ } else if (useCodexDefaults) {
364
+ logger.debug("Using Codex SDK default providers from ChatGPT/Codex credentials");
365
+ providers = {
366
+ embeddingProvider: DefaultEmbeddingProvider,
367
+ moderationProvider: DefaultModerationProvider,
368
+ ...getCodexDefaultProviders(env)
369
+ };
370
+ } else if (useGitHubDefaults) {
371
+ logger.debug("Using GitHub Models default providers");
372
+ providers = {
373
+ embeddingProvider: DefaultEmbeddingProvider,
374
+ gradingJsonProvider: DefaultGitHubGradingJsonProvider,
375
+ gradingProvider: DefaultGitHubGradingProvider,
376
+ moderationProvider: DefaultModerationProvider,
377
+ suggestionsProvider: DefaultGitHubSuggestionsProvider,
378
+ synthesizeProvider: DefaultGitHubGradingJsonProvider
379
+ };
380
+ } else {
381
+ logger.debug("Using OpenAI default providers");
382
+ providers = {
383
+ embeddingProvider: DefaultEmbeddingProvider,
384
+ gradingJsonProvider: DefaultGradingJsonProvider,
385
+ gradingProvider: DefaultGradingProvider,
386
+ moderationProvider: DefaultModerationProvider,
387
+ suggestionsProvider: DefaultSuggestionsProvider,
388
+ synthesizeProvider: DefaultGradingJsonProvider,
389
+ webSearchProvider: DefaultWebSearchProvider
390
+ };
391
+ }
392
+ if (getEnvString("AZURE_CONTENT_SAFETY_ENDPOINT") || env?.AZURE_CONTENT_SAFETY_ENDPOINT) providers.moderationProvider = new AzureModerationProvider("text-content-safety", { env });
393
+ return providers;
394
+ }
395
+ //#endregion
396
+ //#region src/assertions/utils.ts
397
+ const clone = Clone();
398
+ function getFinalTest(test, assertion) {
399
+ const ret = clone({
400
+ ...test,
401
+ ...test.options && test.options.provider && { options: {
402
+ ...test.options,
403
+ provider: void 0
404
+ } },
405
+ ...test.provider && { provider: void 0 }
406
+ });
407
+ ret.options = ret.options || {};
408
+ if (test.provider) ret.provider = test.provider;
409
+ ret.options.provider = assertion.provider || test?.options?.provider;
410
+ ret.options.rubricPrompt = assertion.rubricPrompt || ret.options.rubricPrompt;
411
+ return Object.freeze(ret);
412
+ }
413
+ async function loadFromJavaScriptFile(filePath, functionName, args) {
414
+ const requiredModule = await importModule(filePath, functionName);
415
+ if (functionName && typeof requiredModule[functionName] === "function") return requiredModule[functionName](...args);
416
+ else if (typeof requiredModule === "function") return requiredModule(...args);
417
+ else if (requiredModule.default && typeof requiredModule.default === "function") return requiredModule.default(...args);
418
+ else throw new Error(`Assertion malformed: ${filePath} must export a function or have a default export as a function`);
419
+ }
420
+ function processFileReference(fileRef) {
421
+ const basePath = state.basePath || "";
422
+ const filePath = path.resolve(basePath, fileRef.slice(7));
423
+ const fileContent = fs.readFileSync(filePath, "utf8");
424
+ const extension = path.extname(filePath);
425
+ if ([
426
+ ".json",
427
+ ".yaml",
428
+ ".yml"
429
+ ].includes(extension)) return yaml.load(fileContent);
430
+ else if (extension === ".txt") return fileContent.trim();
431
+ else throw new Error(`Unsupported file type: ${filePath}`);
432
+ }
433
+ function coerceString(value) {
434
+ if (typeof value === "string") return value;
435
+ return JSON.stringify(value);
436
+ }
437
+ //#endregion
438
+ //#region src/matchers/shared.ts
439
+ /**
440
+ * Normalize token usage for matcher results. Unlike the evaluator-level
441
+ * normalizeTokenUsage, this excludes the `assertions` field and preserves
442
+ * the existing completionDetails shape (passing through whatever the
443
+ * provider returned, or undefined if not present).
444
+ */
445
+ function normalizeMatcherTokenUsage(tokenUsage) {
446
+ return {
447
+ total: tokenUsage?.total || 0,
448
+ prompt: tokenUsage?.prompt || 0,
449
+ completion: tokenUsage?.completion || 0,
450
+ cached: tokenUsage?.cached || 0,
451
+ numRequests: tokenUsage?.numRequests || 0,
452
+ completionDetails: tokenUsage?.completionDetails || {
453
+ reasoning: 0,
454
+ acceptedPrediction: 0,
455
+ rejectedPrediction: 0
456
+ }
457
+ };
458
+ }
459
+ function fail(reason, tokensUsed) {
460
+ return {
461
+ pass: false,
462
+ reason,
463
+ score: 0,
464
+ tokensUsed: normalizeMatcherTokenUsage(tokensUsed)
465
+ };
466
+ }
467
+ function cosineSimilarity(vecA, vecB) {
468
+ if (vecA.length !== vecB.length) throw new Error("Vectors must be of equal length");
469
+ const dotProduct = vecA.reduce((acc, val, idx) => acc + val * vecB[idx], 0);
470
+ const vecAMagnitude = Math.sqrt(vecA.reduce((acc, val) => acc + val * val, 0));
471
+ const vecBMagnitude = Math.sqrt(vecB.reduce((acc, val) => acc + val * val, 0));
472
+ if (vecAMagnitude === 0 || vecBMagnitude === 0) return 0;
473
+ return dotProduct / (vecAMagnitude * vecBMagnitude);
474
+ }
475
+ function dotProduct(vecA, vecB) {
476
+ if (vecA.length !== vecB.length) throw new Error("Vectors must be of equal length");
477
+ return vecA.reduce((acc, val, idx) => acc + val * vecB[idx], 0);
478
+ }
479
+ function euclideanDistance(vecA, vecB) {
480
+ if (vecA.length !== vecB.length) throw new Error("Vectors must be of equal length");
481
+ const sumSquaredDiff = vecA.reduce((acc, val, idx) => {
482
+ const diff = val - vecB[idx];
483
+ return acc + diff * diff;
484
+ }, 0);
485
+ return Math.sqrt(sumSquaredDiff);
486
+ }
487
+ function tryParse(content) {
488
+ try {
489
+ return JSON.parse(content);
490
+ } catch {}
491
+ return content;
492
+ }
493
+ function splitIntoSentences(text) {
494
+ return text.split("\n").filter((sentence) => sentence.trim() !== "");
495
+ }
496
+ //#endregion
497
+ //#region src/matchers/rubric.ts
498
+ const nunjucks = getNunjucksEngine(void 0, false, true);
499
+ var LlmRubricProviderError = class extends Error {
500
+ constructor(message) {
501
+ super(message);
502
+ this.name = "LlmRubricProviderError";
503
+ }
282
504
  };
283
- const SELECT_BEST_PROMPT = JSON.stringify([{
284
- role: "system",
285
- content: `You are comparing multiple pieces of text to see which best fits the following criteria: {{criteria}}
286
-
287
- Here are the pieces of text:
288
-
289
- {% for output in outputs %}
290
- <Text index="{{ loop.index0 }}">
291
- {{ output }}
292
- </Text>
293
- {% endfor %}
294
-
295
- Output the index of the text that best fits the criteria. You must output a single integer.`
296
- }]);
297
- const DEFAULT_WEB_SEARCH_PROMPT = JSON.stringify([{
298
- role: "system",
299
- content: dedent`You are grading output according to a user-specified rubric, with the ability to search the web for current information. If the statement in the rubric is true, then the output passes the test. You respond with a JSON object with this structure: {reason: string, pass: boolean, score: number}
300
-
301
- You MUST search the web when:
302
- - The rubric asks about current information (prices, weather, news, etc.)
303
- - Facts need to be verified against recent data
304
- - The rubric references time-sensitive information
305
-
306
- Examples:
307
-
308
- <Output>The current CEO of Microsoft is Satya Nadella</Output>
309
- <Rubric>Contains accurate information about Microsoft's leadership</Rubric>
310
- {"reason": "I searched and confirmed Satya Nadella is indeed the current CEO of Microsoft", "pass": true, "score": 1.0}
311
-
312
- <Output>Bitcoin is trading at $45,000</Output>
313
- <Rubric>Provides current Bitcoin price within 10% accuracy</Rubric>
314
- {"reason": "Web search shows Bitcoin is currently trading at $98,000, not $45,000. The output is off by more than 50%", "pass": false, "score": 0.0}`
315
- }, {
316
- role: "user",
317
- content: "<Output>\n{{ output }}\n</Output>\n<Rubric>\n{{ rubric }}\n</Rubric>"
318
- }]);
319
- const TRAJECTORY_GOAL_SUCCESS_PROMPT = JSON.stringify([{
320
- role: "system",
321
- content: dedent`You are grading whether an AI agent successfully completed a goal based on its final output and a summarized execution trajectory. You respond with a JSON object with this structure: {reason: string, pass: boolean, score: number}
322
-
323
- Judge end-to-end success, not stylistic perfection.
324
- Use the trajectory as evidence for what the agent actually did.
325
- Give partial credit when the agent made progress but did not fully achieve the goal.
326
-
327
- Examples:
328
-
329
- <Goal>Find the order status and tell the user whether it has shipped</Goal>
330
- <Trajectory>{"stepCount":2,"steps":[{"index":1,"type":"tool","name":"search_orders"},{"index":2,"type":"message","name":"agent response"}]}</Trajectory>
331
- <Output>Your order shipped yesterday and should arrive on Tuesday.</Output>
332
- {"reason":"The agent used the order lookup tool and gave the user the shipping status, so the goal was achieved.","pass":true,"score":1.0}
333
-
334
- <Goal>Find the order status and tell the user whether it has shipped</Goal>
335
- <Trajectory>{"stepCount":1,"steps":[{"index":1,"type":"message","name":"agent response"}]}</Trajectory>
336
- <Output>I cannot check your order right now.</Output>
337
- {"reason":"The agent did not show evidence of checking the order and did not provide the requested status.","pass":false,"score":0.0}`
338
- }, {
339
- role: "user",
340
- content: dedent`<Goal>
341
- {{ goal }}
342
- </Goal>
343
- <Trajectory>
344
- {{ trajectory }}
345
- </Trajectory>
346
- <Output>
347
- {{ output }}
348
- </Output>`
349
- }]);
505
+ async function loadRubricPrompt(rubricPrompt, defaultPrompt) {
506
+ if (!rubricPrompt) return defaultPrompt;
507
+ if (typeof rubricPrompt === "object" && Object.keys(rubricPrompt).length === 0) return defaultPrompt;
508
+ if (typeof rubricPrompt === "string" && rubricPrompt.startsWith("file://")) {
509
+ const basePath = state.basePath || "";
510
+ const { filePath, functionName } = parseFileUrl(getNunjucksEngineForFilePath().renderString(rubricPrompt, {}));
511
+ const resolvedPath = path.resolve(basePath, filePath);
512
+ if (isJavascriptFile(filePath)) rubricPrompt = await loadFromJavaScriptFile(resolvedPath, functionName, []);
513
+ else {
514
+ if (!fs$2.existsSync(resolvedPath)) throw new Error(`File does not exist: ${resolvedPath}`);
515
+ rubricPrompt = fs$2.readFileSync(resolvedPath, "utf8");
516
+ }
517
+ } else rubricPrompt = maybeLoadFromExternalFile(rubricPrompt);
518
+ if (typeof rubricPrompt === "object") rubricPrompt = JSON.stringify(rubricPrompt);
519
+ invariant(typeof rubricPrompt === "string", "rubricPrompt must be a string");
520
+ return rubricPrompt;
521
+ }
522
+ function processContextForTemplating(context, enableObjectAccess) {
523
+ if (enableObjectAccess) return context;
524
+ return Object.fromEntries(Object.entries(context).map(([key, value]) => {
525
+ if (value && typeof value === "object") {
526
+ if (Array.isArray(value)) return [key, value.map((item) => item && typeof item === "object" ? JSON.stringify(item) : item)];
527
+ return [key, JSON.stringify(value)];
528
+ }
529
+ return [key, value];
530
+ }));
531
+ }
532
+ async function renderLlmRubricPrompt(rubricPrompt, context) {
533
+ const processedContext = processContextForTemplating(context, getEnvBool("PROMPTFOO_DISABLE_OBJECT_STRINGIFY", false));
534
+ try {
535
+ const parsed = JSON.parse(rubricPrompt, (_k, v) => typeof v === "string" ? nunjucks.renderString(v, processedContext) : v);
536
+ return JSON.stringify(parsed);
537
+ } catch (err) {
538
+ logger.debug(`[Rubric] Rubric prompt is not valid JSON, using Nunjucks rendering: ${err.message}`);
539
+ }
540
+ return nunjucks.renderString(rubricPrompt, processedContext);
541
+ }
542
+ function parseJsonGradingResponse(label, resp) {
543
+ let jsonObjects = [];
544
+ if (typeof resp.output === "string") try {
545
+ jsonObjects = extractJsonObjects(resp.output);
546
+ if (jsonObjects.length === 0) return { failure: fail(`Could not extract JSON from ${label} response`, resp.tokenUsage) };
547
+ } catch (err) {
548
+ return { failure: fail(`${label} produced malformed response: ${err}\n\n${resp.output}`, resp.tokenUsage) };
549
+ }
550
+ else if (typeof resp.output === "object" && resp.output !== null && !Array.isArray(resp.output)) jsonObjects = [resp.output];
551
+ else return { failure: fail(`${label} produced malformed response - output must be string or object. Output: ${JSON.stringify(resp.output)}`, resp.tokenUsage) };
552
+ const parsed = jsonObjects[0];
553
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return { failure: fail(`${label} produced malformed response. We were not able to parse the response as JSON. Output: ${JSON.stringify(resp.output)}`, resp.tokenUsage) };
554
+ return { parsed };
555
+ }
556
+ async function runJsonGradingPrompt({ assertion, checkName, defaultPrompt, grading, label, providerCallContext, throwOnError, vars }) {
557
+ const prompt = await renderLlmRubricPrompt(await loadRubricPrompt(grading.rubricPrompt, defaultPrompt), vars);
558
+ const defaultProviders = await getDefaultProviders();
559
+ const defaultProvider = defaultProviders.llmRubricProvider || defaultProviders.gradingJsonProvider;
560
+ const resp = await callProviderWithContext(await getAndCheckProvider("text", grading.provider, defaultProvider, checkName), prompt, label, vars, providerCallContext);
561
+ if (resp.error || !resp.output) {
562
+ if (throwOnError) throw new Error(resp.error || "No output");
563
+ return fail(resp.error || "No output", resp.tokenUsage);
564
+ }
565
+ const { parsed, failure } = parseJsonGradingResponse(label, resp);
566
+ if (!parsed) return failure;
567
+ let pass = parsed.pass ?? true;
568
+ if (typeof pass !== "boolean") pass = /^(true|yes|pass|y)$/i.test(String(pass));
569
+ let score = parsed.score;
570
+ if (typeof score !== "number") score = Number.isFinite(Number(score)) ? Number(score) : Number(pass);
571
+ const threshold = typeof assertion?.threshold === "string" ? Number(assertion.threshold) : assertion?.threshold;
572
+ if (typeof threshold === "number" && Number.isFinite(threshold)) pass = pass && score >= threshold;
573
+ const reason = parsed.reason || (pass ? "Grading passed" : `Score ${score} below threshold ${threshold}`);
574
+ let responseMetadata = {};
575
+ if (resp.metadata && typeof resp.metadata === "object" && !Array.isArray(resp.metadata)) {
576
+ const serializedMetadata = safeJsonStringify(resp.metadata);
577
+ responseMetadata = serializedMetadata ? JSON.parse(serializedMetadata) : {};
578
+ }
579
+ return {
580
+ assertion,
581
+ pass,
582
+ score,
583
+ reason,
584
+ tokensUsed: normalizeMatcherTokenUsage({
585
+ ...resp.tokenUsage,
586
+ completionDetails: resp.tokenUsage?.completionDetails || parsed.tokensUsed?.completionDetails
587
+ }),
588
+ metadata: {
589
+ ...responseMetadata,
590
+ renderedGradingPrompt: prompt
591
+ }
592
+ };
593
+ }
350
594
  //#endregion
351
595
  //#region src/prompts/processors/csv.ts
352
596
  /**
@@ -460,810 +704,667 @@ const executablePromptFunction = async (scriptPath, context) => {
460
704
  if (fileHashes.length > 0 && isCacheEnabled()) await getCache().set(cacheKey, standardOutput);
461
705
  resolve(standardOutput);
462
706
  });
463
- });
464
- };
465
- /**
466
- * Processes an executable file to generate prompts.
467
- * The executable can be any script or binary that outputs prompt text to stdout.
468
- * It receives the context as JSON in its first argument.
469
- *
470
- * @param filePath - Path to the executable file (can include arguments).
471
- * @param prompt - The raw prompt data.
472
- * @param functionName - Not used for executables, but kept for interface consistency.
473
- * @returns Array of prompts generated from the executable.
474
- */
475
- async function processExecutableFile(filePath, prompt, _functionName) {
476
- let rawContent = filePath;
477
- const firstPart = parseScriptParts(filePath)[0];
478
- if (firstPart) try {
479
- const stats = await stat(firstPart);
480
- if (stats.isFile() && stats.size < 1024 * 100) {
481
- const content = await readFile(firstPart, "utf-8");
482
- if (!/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/.test(content.substring(0, 1e3))) rawContent = content;
483
- }
484
- } catch (_e) {}
485
- const label = prompt.label ?? filePath;
486
- return [{
487
- raw: rawContent,
488
- label,
489
- function: (context) => executablePromptFunction(filePath, {
490
- ...context,
491
- config: prompt.config
492
- }),
493
- config: prompt.config
494
- }];
495
- }
496
- //#endregion
497
- //#region src/prompts/processors/javascript.ts
498
- const transformContext = (context) => {
499
- invariant(context.provider, "Provider is required");
500
- return {
501
- vars: context.vars,
502
- provider: {
503
- id: context.provider.id(),
504
- label: context.provider.label
505
- },
506
- config: context.config ?? {}
507
- };
508
- };
509
- /**
510
- * Processes a JavaScript file to import and execute a module function as a prompt.
511
- * @param filePath - Path to the JavaScript file.
512
- * @param functionName - Optional function name to execute.
513
- * @returns Promise resolving to an array of prompts.
514
- */
515
- async function processJsFile(filePath, prompt, functionName) {
516
- const promptFunction = await importModule(filePath, functionName);
517
- return [{
518
- raw: String(promptFunction),
519
- label: prompt.label ? prompt.label : functionName ? `${filePath}:${functionName}` : filePath,
520
- function: (context) => promptFunction(transformContext({
521
- ...context,
522
- config: prompt.config ?? {}
523
- })),
524
- config: prompt.config ?? {}
525
- }];
526
- }
527
- //#endregion
528
- //#region src/prompts/processors/jinja.ts
529
- /**
530
- * Processes a Jinja2 template file to extract prompts.
531
- * Similar to markdown files, each Jinja2 file is treated as a single prompt.
532
- *
533
- * @param filePath - Path to the Jinja2 template file.
534
- * @param prompt - The raw prompt data.
535
- * @returns Array of one `Prompt` object.
536
- */
537
- function processJinjaFile(filePath, prompt) {
538
- const content = fs$2.readFileSync(filePath, "utf8");
539
- return [{
540
- raw: content,
541
- label: prompt.label || `${filePath}: ${content.slice(0, 50)}...`,
542
- config: prompt.config
543
- }];
544
- }
545
- //#endregion
546
- //#region src/prompts/processors/json.ts
547
- /**
548
- * Processes a JSON file to extract prompts.
549
- * This function reads a JSON file and converts it to a `Prompt` object.
550
- * Any file:// references within the JSON content are recursively resolved.
551
- *
552
- * @param filePath - The path to the JSON file.
553
- * @param prompt - The raw prompt data, used for labeling.
554
- * @returns An array of one `Prompt` object.
555
- * @throws Will throw an error if the file cannot be read.
556
- */
557
- function processJsonFile(filePath, prompt) {
558
- const fileContents = fs$2.readFileSync(filePath, "utf8");
559
- let processedContents = fileContents;
560
- try {
561
- const resolved = maybeLoadConfigFromExternalFile(JSON.parse(fileContents));
562
- processedContents = JSON.stringify(resolved);
563
- } catch {}
564
- return [{
565
- raw: processedContents,
566
- label: prompt.label || `${filePath}: ${processedContents}`,
567
- config: prompt.config
568
- }];
569
- }
570
- //#endregion
571
- //#region src/prompts/processors/jsonl.ts
572
- /**
573
- * Processes a JSONL file to extract prompts.
574
- * @param filePath - Path to the JSONL file.
575
- * @param prompt - The raw prompt data.
576
- * @returns Array of prompts extracted from the file.
577
- */
578
- function processJsonlFile(filePath, prompt) {
579
- const jsonLines = fs$2.readFileSync(filePath, "utf-8").split(/\r?\n/).filter((line) => line.length > 0);
580
- const containsMultiple = jsonLines.length > 1;
581
- return jsonLines.map((json) => ({
582
- raw: json,
583
- label: containsMultiple ? prompt.label ? `${prompt.label}: ${json}` : `${filePath}: ${json}` : prompt.label || `${filePath}`,
584
- config: prompt.config
585
- }));
586
- }
587
- //#endregion
588
- //#region src/prompts/processors/markdown.ts
589
- function processMarkdownFile(filePath, prompt) {
590
- const content = fs.readFileSync(filePath, "utf8");
591
- return [{
592
- raw: content,
593
- label: prompt.label || `${filePath}: ${content.slice(0, 50)}...`
594
- }];
595
- }
596
- //#endregion
597
- //#region src/prompts/processors/python.ts
598
- /**
599
- * Python prompt function. Runs a specific function from the python file.
600
- * @param promptPath - Path to the Python file.
601
- * @param functionName - Function name to execute.
602
- * @param context - Context for the prompt.
603
- * @returns The prompts
604
- */
605
- const pythonPromptFunction = async (filePath, functionName, context) => {
606
- invariant(context.provider?.id, "provider.id is required");
607
- return runPython(filePath, functionName, [{
608
- vars: context.vars,
609
- provider: {
610
- id: typeof context.provider?.id === "function" ? context.provider?.id() : context.provider?.id,
611
- label: context.provider?.label
612
- },
613
- config: context.config ?? {}
614
- }]);
615
- };
616
- /**
617
- * Legacy Python prompt function. Runs the whole python file.
618
- * @param filePath - Path to the Python file.
619
- * @param context - Context for the prompt.
620
- * @returns The prompts
621
- */
622
- const pythonPromptFunctionLegacy = async (filePath, context) => {
623
- invariant(context?.provider?.id, "provider.id is required");
624
- const transformedContext = {
625
- vars: context.vars,
626
- provider: {
627
- id: typeof context.provider?.id === "function" ? context.provider?.id() : context.provider?.id,
628
- label: context.provider?.label
629
- },
630
- config: context.config ?? {}
631
- };
632
- const options = {
633
- mode: "text",
634
- pythonPath: getEnvString("PROMPTFOO_PYTHON", "python"),
635
- args: [safeJsonStringify(transformedContext)]
636
- };
637
- logger.debug(`Executing python prompt script ${filePath}`);
638
- const results = (await PythonShell.run(filePath, options)).join("\n");
639
- logger.debug(`Python prompt script ${filePath} returned: ${results}`);
640
- return results;
641
- };
642
- /**
643
- * Processes a Python file to extract or execute a function as a prompt.
644
- * @param filePath - Path to the Python file.
645
- * @param prompt - The raw prompt data.
646
- * @param functionName - Optional function name to execute.
647
- * @returns Array of prompts extracted or executed from the file.
648
- */
649
- function processPythonFile(filePath, prompt, functionName) {
650
- const fileContent = fs$2.readFileSync(filePath, "utf-8");
651
- return [{
652
- raw: fileContent,
653
- label: prompt.label ?? (functionName ? `${filePath}:${functionName}` : `${filePath}: ${fileContent}`),
654
- function: functionName ? (context) => pythonPromptFunction(filePath, functionName, {
655
- ...context,
656
- config: prompt.config
657
- }) : (context) => pythonPromptFunctionLegacy(filePath, {
658
- ...context,
659
- config: prompt.config
660
- }),
661
- config: prompt.config
662
- }];
663
- }
664
- //#endregion
665
- //#region src/prompts/processors/string.ts
666
- /**
667
- * Processes a string as a literal prompt.
668
- * @param prompt - The raw prompt data.
669
- * @returns Array of prompts created from the string.
670
- */
671
- function processString(prompt) {
672
- invariant(typeof prompt.raw === "string", `prompt.raw must be a string, but got ${JSON.stringify(prompt.raw)}`);
673
- return [{
674
- id: prompt.id,
675
- raw: prompt.raw,
676
- label: prompt.label ?? `${prompt.raw}`,
677
- config: prompt.config
678
- }];
679
- }
680
- //#endregion
681
- //#region src/prompts/processors/text.ts
682
- /**
683
- * Processes a text file to extract prompts, splitting by a delimiter.
684
- * @param filePath - Path to the text file.
685
- * @param prompt - The raw prompt data.
686
- * @returns Array of prompts extracted from the file.
687
- */
688
- function processTxtFile(filePath, { label }) {
689
- const lines = fs$2.readFileSync(filePath, "utf-8").split(/\r?\n/);
690
- const prompts = [];
691
- let buffer = [];
692
- const flush = () => {
693
- const raw = buffer.join("\n").trim();
694
- if (raw.length > 0) prompts.push({
695
- raw,
696
- label: label ? `${label}: ${filePath}: ${raw}` : `${filePath}: ${raw}`
697
- });
698
- buffer = [];
699
- };
700
- for (const line of lines) if (line.trim() === PROMPT_DELIMITER) flush();
701
- else buffer.push(line);
702
- flush();
703
- return prompts;
704
- }
705
- //#endregion
706
- //#region src/prompts/processors/yaml.ts
707
- /**
708
- * Processes a YAML file to extract prompts.
709
- * This function reads a YAML file, parses it, and maps each entry to a `Prompt` object.
710
- * Each prompt is labeled with the file path and the YAML content.
711
- * Any file:// references within the YAML content are recursively resolved.
707
+ });
708
+ };
709
+ /**
710
+ * Processes an executable file to generate prompts.
711
+ * The executable can be any script or binary that outputs prompt text to stdout.
712
+ * It receives the context as JSON in its first argument.
712
713
  *
713
- * @param filePath - The path to the YAML file.
714
- * @param prompt - The raw prompt data, used for labeling.
715
- * @returns An array of `Prompt` objects extracted from the YAML file.
716
- * @throws Will throw an error if the file cannot be read or parsed.
714
+ * @param filePath - Path to the executable file (can include arguments).
715
+ * @param prompt - The raw prompt data.
716
+ * @param functionName - Not used for executables, but kept for interface consistency.
717
+ * @returns Array of prompts generated from the executable.
717
718
  */
718
- function processYamlFile(filePath, prompt) {
719
- const fileContents = fs$2.readFileSync(filePath, "utf8");
720
- let maybeParsed = fileContents;
721
- try {
722
- const resolved = maybeLoadConfigFromExternalFile(yaml.load(fileContents));
723
- maybeParsed = JSON.stringify(resolved);
724
- } catch (e) {
725
- logger.debug(`Error parsing YAML file ${filePath}: ${e}`);
726
- }
719
+ async function processExecutableFile(filePath, prompt, _functionName) {
720
+ let rawContent = filePath;
721
+ const firstPart = parseScriptParts(filePath)[0];
722
+ if (firstPart) try {
723
+ const stats = await stat(firstPart);
724
+ if (stats.isFile() && stats.size < 1024 * 100) {
725
+ const content = await readFile(firstPart, "utf-8");
726
+ if (!/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/.test(content.substring(0, 1e3))) rawContent = content;
727
+ }
728
+ } catch (_e) {}
729
+ const label = prompt.label ?? filePath;
727
730
  return [{
728
- raw: maybeParsed,
729
- label: prompt.label || `${filePath}: ${maybeParsed?.slice(0, 80)}`,
731
+ raw: rawContent,
732
+ label,
733
+ function: (context) => executablePromptFunction(filePath, {
734
+ ...context,
735
+ config: prompt.config
736
+ }),
730
737
  config: prompt.config
731
738
  }];
732
739
  }
733
740
  //#endregion
734
- //#region src/prompts/index.ts
741
+ //#region src/prompts/processors/javascript.ts
742
+ const transformContext = (context) => {
743
+ invariant(context.provider, "Provider is required");
744
+ return {
745
+ vars: context.vars,
746
+ provider: {
747
+ id: context.provider.id(),
748
+ label: context.provider.label
749
+ },
750
+ config: context.config ?? {}
751
+ };
752
+ };
735
753
  /**
736
- * Reads and maps provider prompts based on the configuration and parsed prompts.
737
- * @param config - The configuration object.
738
- * @param parsedPrompts - Array of parsed prompts.
739
- * @returns A map of provider IDs to their respective prompts.
754
+ * Processes a JavaScript file to import and execute a module function as a prompt.
755
+ * @param filePath - Path to the JavaScript file.
756
+ * @param functionName - Optional function name to execute.
757
+ * @returns Promise resolving to an array of prompts.
740
758
  */
741
- function readProviderPromptMap(config, parsedPrompts) {
742
- const ret = {};
743
- if (!config.providers) return ret;
744
- const allPrompts = [];
745
- for (const prompt of parsedPrompts) allPrompts.push(prompt.label);
746
- if (typeof config.providers === "string") return { [config.providers]: allPrompts };
747
- if (typeof config.providers === "function") return { "Custom function": allPrompts };
748
- for (const provider of config.providers) if (typeof provider === "object") if (provider.id) {
749
- const rawProvider = provider;
750
- invariant(rawProvider.id, "You must specify an `id` on the Provider when you override options.prompts");
751
- ret[rawProvider.id] = rawProvider.prompts || allPrompts;
752
- if (rawProvider.label) ret[rawProvider.label] = rawProvider.prompts || allPrompts;
753
- } else {
754
- const rawProvider = provider;
755
- const originalId = Object.keys(rawProvider)[0];
756
- const id = rawProvider[originalId].id || originalId;
757
- ret[id] = rawProvider[originalId].prompts || allPrompts;
758
- }
759
- return ret;
759
+ async function processJsFile(filePath, prompt, functionName) {
760
+ const promptFunction = await importModule(filePath, functionName);
761
+ return [{
762
+ raw: String(promptFunction),
763
+ label: prompt.label ? prompt.label : functionName ? `${filePath}:${functionName}` : filePath,
764
+ function: (context) => promptFunction(transformContext({
765
+ ...context,
766
+ config: prompt.config ?? {}
767
+ })),
768
+ config: prompt.config ?? {}
769
+ }];
760
770
  }
771
+ //#endregion
772
+ //#region src/prompts/processors/jinja.ts
761
773
  /**
762
- * Processes a raw prompt based on its content type and path.
774
+ * Processes a Jinja2 template file to extract prompts.
775
+ * Similar to markdown files, each Jinja2 file is treated as a single prompt.
776
+ *
777
+ * @param filePath - Path to the Jinja2 template file.
763
778
  * @param prompt - The raw prompt data.
764
- * @param basePath - Base path for file resolution.
765
- * @param maxRecursionDepth - Maximum recursion depth for globbing.
766
- * @returns Promise resolving to an array of processed prompts.
779
+ * @returns Array of one `Prompt` object.
767
780
  */
768
- async function processPrompt(prompt, basePath = "", maxRecursionDepth = 1) {
769
- invariant(typeof prompt.raw === "string", `prompt.raw must be a string, but got ${JSON.stringify(prompt.raw)}`);
770
- if (prompt.function) return [prompt];
771
- if (prompt.raw.startsWith("exec:")) {
772
- const { filePath, functionName } = parsePathOrGlob(basePath, prompt.raw.substring(5));
773
- return await processExecutableFile(filePath, prompt, functionName);
774
- }
775
- if (!maybeFilePath(prompt.raw)) return processString(prompt);
776
- const { extension, functionName, isPathPattern, filePath } = parsePathOrGlob(basePath, prompt.raw);
777
- if (isPathPattern && maxRecursionDepth > 0) {
778
- const globbedPath = globSync(filePath.replace(/\\/g, "/"), { windowsPathsNoEscape: true });
779
- logger.debug(`Expanded prompt ${prompt.raw} to ${filePath} and then to ${JSON.stringify(globbedPath)}`);
780
- const prompts = [];
781
- for (const globbedFilePath of globbedPath) {
782
- const processedPrompts = await processPrompt({ raw: functionName ? `${globbedFilePath}:${functionName}` : globbedFilePath }, basePath, maxRecursionDepth - 1);
783
- prompts.push(...processedPrompts);
784
- }
785
- if (prompts.length === 0) {
786
- logger.debug(`Attempted to load file at "${prompt.raw}", but no file found. Using raw string.`);
787
- prompts.push(...processString(prompt));
788
- }
789
- return prompts;
790
- }
791
- if (extension === ".csv") return processCsvPrompts(filePath, prompt);
792
- if (extension === ".j2") return processJinjaFile(filePath, prompt);
793
- if (extension === ".json") return processJsonFile(filePath, prompt);
794
- if (extension === ".jsonl") return processJsonlFile(filePath, prompt);
795
- if (extension && isJavascriptFile(extension)) return processJsFile(filePath, prompt, functionName);
796
- if (extension === ".md") return processMarkdownFile(filePath, prompt);
797
- if (extension === ".py") return processPythonFile(filePath, prompt, functionName);
798
- if (extension === ".txt") return processTxtFile(filePath, prompt);
799
- if (extension && [".yml", ".yaml"].includes(extension)) return processYamlFile(filePath, prompt);
800
- if (extension && [
801
- ".sh",
802
- ".bash",
803
- ".exe",
804
- ".bat",
805
- ".cmd",
806
- ".ps1",
807
- ".rb",
808
- ".pl"
809
- ].includes(extension)) return await processExecutableFile(filePath, prompt, functionName);
810
- try {
811
- const stats = await stat(filePath);
812
- if (stats.isFile() && (stats.mode & 73) !== 0) return await processExecutableFile(filePath, prompt, functionName);
813
- } catch (_e) {}
814
- return [];
781
+ function processJinjaFile(filePath, prompt) {
782
+ const content = fs$2.readFileSync(filePath, "utf8");
783
+ return [{
784
+ raw: content,
785
+ label: prompt.label || `${filePath}: ${content.slice(0, 50)}...`,
786
+ config: prompt.config
787
+ }];
815
788
  }
789
+ //#endregion
790
+ //#region src/prompts/processors/json.ts
816
791
  /**
817
- * Reads and processes prompts from a specified path or glob pattern.
818
- * @param promptPathOrGlobs - The path or glob pattern.
819
- * @param basePath - Base path for file resolution.
820
- * @returns Promise resolving to an array of processed prompts.
821
- */
822
- async function readPrompts(promptPathOrGlobs, basePath = "") {
823
- logger.debug(`Reading prompts from ${JSON.stringify(promptPathOrGlobs)}`);
824
- const promptPartials = normalizeInput(promptPathOrGlobs);
825
- const prompts = [];
826
- for (const prompt of promptPartials) {
827
- const promptBatch = await processPrompt(prompt, basePath);
828
- if (promptBatch.length === 0) throw new Error(`There are no prompts in ${JSON.stringify(prompt.raw)}`);
829
- prompts.push(...promptBatch);
830
- }
831
- return prompts;
832
- }
833
- async function processPrompts(prompts) {
834
- return (await Promise.all(prompts.map(async (promptInput) => {
835
- if (typeof promptInput === "function") return {
836
- raw: promptInput.toString(),
837
- label: promptInput?.name ?? promptInput.toString(),
838
- function: promptInput
839
- };
840
- else if (typeof promptInput === "string") return readPrompts(promptInput);
841
- try {
842
- return PromptSchema.parse(promptInput);
843
- } catch (error) {
844
- logger.warn(`Prompt input is not a valid prompt schema: ${error}\nFalling back to serialized JSON as raw prompt.`);
845
- return {
846
- raw: JSON.stringify(promptInput),
847
- label: JSON.stringify(promptInput)
848
- };
849
- }
850
- }))).flat();
851
- }
852
- const GEVAL_PROMPT_STEPS = `
853
- Given evaluation criteria that outline how you should judge a piece of text, generate 3-4 concise evaluation steps applicable to any text based on the criteria below and designed to check whether the criteria are satisfied by the text.
854
-
855
- **EVALUATION CRITERIA**
856
- {{criteria}}
857
-
858
- **OUTPUT FORMAT**
859
- IMPORTANT:
860
- - Return output ONLY as a minified JSON object (no code fences).
861
- - The JSON object must contain a single key, "steps", whose value is a list of strings.
862
- - Each string must represent one evaluation step.
863
- - Do NOT include any explanations, commentary, extra text, or additional formatting.
864
-
865
- Format:
866
- {"steps": <list_of_strings>}
867
-
868
- Example:
869
- {"steps":["<Evaluation Step 1>","<Evaluation Step 2>","<Evaluation Step 3>","<Evaluation Step 4>"]}
870
-
871
- Here are the 3-4 concise evaluation steps, formatted as required in a minified JSON:
872
- JSON:
873
- `;
874
- const GEVAL_PROMPT_EVALUATE = `
875
- You will be given one Reply for a Prompt below. Your task is to rate the Reply on one metric.
876
- Please make sure you read and understand these instructions carefully. Please keep this document open while reviewing, and refer to it as needed.
877
-
878
- **Evaluation Criteria**
879
- {{criteria}}
880
-
881
- **Evaluation Steps**
882
- - {{steps}}
883
- Given the evaluation steps, return a JSON with two keys:
884
- 1) a "score" key that MUST be an integer from 0 to {{maxScore}}, where {{maxScore}} indicates that the condition described by the Evaluation Criteria is fully and clearly observed in the Reply according to the Evaluation Steps, and 0 indicates that it is not observed at all;
885
- 2) a "reason" key, a reason for the given score, but DO NOT QUOTE THE SCORE in your reason. Please mention specific information from Prompt and Reply in your reason, but be very concise with it!
886
-
887
- **Prompt**
888
- {{input}}
889
-
890
- **Reply**
891
- {{output}}
892
-
893
- **OUTPUT FORMAT**
894
- IMPORTANT:
895
- - Return output ONLY as a minified JSON object (no code fences).
896
- - The JSON object must contain exactly two keys: "score" and "reason".
897
- - No additional words, explanations, or formatting are needed.
898
- - Absolutely no additional text, explanations, line breaks, or formatting outside the JSON object are allowed.
899
-
900
- Example JSON:
901
- {"score":0,"reason":"The text of reply does not follow the evaluation criteria provided."}
902
-
903
- Here is the final evaluation in the required minified JSON format:
904
- JSON:
905
- `;
792
+ * Processes a JSON file to extract prompts.
793
+ * This function reads a JSON file and converts it to a `Prompt` object.
794
+ * Any file:// references within the JSON content are recursively resolved.
795
+ *
796
+ * @param filePath - The path to the JSON file.
797
+ * @param prompt - The raw prompt data, used for labeling.
798
+ * @returns An array of one `Prompt` object.
799
+ * @throws Will throw an error if the file cannot be read.
800
+ */
801
+ function processJsonFile(filePath, prompt) {
802
+ const fileContents = fs$2.readFileSync(filePath, "utf8");
803
+ let processedContents = fileContents;
804
+ try {
805
+ const resolved = maybeLoadConfigFromExternalFile(JSON.parse(fileContents));
806
+ processedContents = JSON.stringify(resolved);
807
+ } catch {}
808
+ return [{
809
+ raw: processedContents,
810
+ label: prompt.label || `${filePath}: ${processedContents}`,
811
+ config: prompt.config
812
+ }];
813
+ }
906
814
  //#endregion
907
- //#region src/providers/anthropic/defaults.ts
908
- const DEFAULT_ANTHROPIC_MODEL = "claude-sonnet-4-6";
815
+ //#region src/prompts/processors/jsonl.ts
909
816
  /**
910
- * Helper function to create a lazy-loaded provider. This allows the .env file to be
911
- * loaded first before the provider is initialized.
912
- * @param factory Factory function that creates provider instance with optional env
913
- * @returns Object with getter that lazily initializes the provider with the latest env
817
+ * Processes a JSONL file to extract prompts.
818
+ * @param filePath - Path to the JSONL file.
819
+ * @param prompt - The raw prompt data.
820
+ * @returns Array of prompts extracted from the file.
914
821
  */
915
- function createLazyProvider(factory) {
916
- const instances = /* @__PURE__ */ new Map();
917
- return { getInstance(env) {
918
- const cacheKey = env ? JSON.stringify(env) : "";
919
- if (!instances.has(cacheKey)) instances.set(cacheKey, factory(env));
920
- return instances.get(cacheKey);
921
- } };
822
+ function processJsonlFile(filePath, prompt) {
823
+ const jsonLines = fs$2.readFileSync(filePath, "utf-8").split(/\r?\n/).filter((line) => line.length > 0);
824
+ const containsMultiple = jsonLines.length > 1;
825
+ return jsonLines.map((json) => ({
826
+ raw: json,
827
+ label: containsMultiple ? prompt.label ? `${prompt.label}: ${json}` : `${filePath}: ${json}` : prompt.label || `${filePath}`,
828
+ config: prompt.config
829
+ }));
922
830
  }
923
- var AnthropicLlmRubricProvider = class extends AnthropicMessagesProvider {
924
- constructor(modelName, options = {}) {
925
- const { env, config = {} } = options;
926
- super(modelName, {
927
- env,
928
- config: {
929
- tool_choice: {
930
- type: "tool",
931
- name: "grade_output"
932
- },
933
- tools: [{
934
- name: "grade_output",
935
- description: "Grade the given output based on specific criteria",
936
- input_schema: {
937
- type: "object",
938
- properties: {
939
- pass: {
940
- type: "boolean",
941
- description: "Whether the output passes the criteria"
942
- },
943
- score: {
944
- type: "number",
945
- description: "The score assigned to the output"
946
- },
947
- reason: {
948
- type: "string",
949
- description: "The reason for the given grade"
950
- }
951
- },
952
- required: [
953
- "pass",
954
- "score",
955
- "reason"
956
- ]
957
- }
958
- }],
959
- ...config
960
- }
961
- });
962
- }
963
- async callApi(prompt) {
964
- const result = await super.callApi(prompt);
965
- if (typeof result.output !== "string") return { error: `Anthropic LLM rubric grader - malformed non-string output\n\n${JSON.stringify(result.output)}` };
966
- try {
967
- return { output: JSON.parse(result.output).input };
968
- } catch (err) {
969
- return { error: `Anthropic LLM rubric grader - invalid JSON: ${err}\n\n${result.output}` };
970
- }
971
- }
831
+ //#endregion
832
+ //#region src/prompts/processors/markdown.ts
833
+ function processMarkdownFile(filePath, prompt) {
834
+ const content = fs.readFileSync(filePath, "utf8");
835
+ return [{
836
+ raw: content,
837
+ label: prompt.label || `${filePath}: ${content.slice(0, 50)}...`
838
+ }];
839
+ }
840
+ //#endregion
841
+ //#region src/prompts/processors/python.ts
842
+ /**
843
+ * Python prompt function. Runs a specific function from the python file.
844
+ * @param promptPath - Path to the Python file.
845
+ * @param functionName - Function name to execute.
846
+ * @param context - Context for the prompt.
847
+ * @returns The prompts
848
+ */
849
+ const pythonPromptFunction = async (filePath, functionName, context) => {
850
+ invariant(context.provider?.id, "provider.id is required");
851
+ return runPython(filePath, functionName, [{
852
+ vars: context.vars,
853
+ provider: {
854
+ id: typeof context.provider?.id === "function" ? context.provider?.id() : context.provider?.id,
855
+ label: context.provider?.label
856
+ },
857
+ config: context.config ?? {}
858
+ }]);
972
859
  };
973
- const gradingProviderFactory = createLazyProvider((env) => new AnthropicMessagesProvider(DEFAULT_ANTHROPIC_MODEL, { env }));
974
- const llmRubricProviderFactory = createLazyProvider((env) => new AnthropicLlmRubricProvider(DEFAULT_ANTHROPIC_MODEL, { env }));
975
- const webSearchProviderFactory = createLazyProvider((env) => new AnthropicMessagesProvider(DEFAULT_ANTHROPIC_MODEL, {
976
- env,
977
- config: { tools: [{
978
- type: "web_search_20250305",
979
- name: "web_search",
980
- max_uses: 5
981
- }] }
982
- }));
983
860
  /**
984
- * Gets all default Anthropic providers with the given environment overrides
985
- * @param env - Optional environment overrides
986
- * @returns Anthropic provider implementations for various functions
861
+ * Legacy Python prompt function. Runs the whole python file.
862
+ * @param filePath - Path to the Python file.
863
+ * @param context - Context for the prompt.
864
+ * @returns The prompts
987
865
  */
988
- function getAnthropicProviders(env) {
989
- const gradingProvider = gradingProviderFactory.getInstance(env);
990
- return {
991
- gradingJsonProvider: gradingProvider,
992
- gradingProvider,
993
- llmRubricProvider: llmRubricProviderFactory.getInstance(env),
994
- suggestionsProvider: gradingProvider,
995
- synthesizeProvider: gradingProvider,
996
- webSearchProvider: webSearchProviderFactory.getInstance(env)
866
+ const pythonPromptFunctionLegacy = async (filePath, context) => {
867
+ invariant(context?.provider?.id, "provider.id is required");
868
+ const transformedContext = {
869
+ vars: context.vars,
870
+ provider: {
871
+ id: typeof context.provider?.id === "function" ? context.provider?.id() : context.provider?.id,
872
+ label: context.provider?.label
873
+ },
874
+ config: context.config ?? {}
997
875
  };
998
- }
999
- //#endregion
1000
- //#region src/providers/github/defaults.ts
1001
- const githubConfig = {
1002
- apiBaseUrl: "https://models.github.ai/inference",
1003
- apiKeyEnvar: "GITHUB_TOKEN"
876
+ const options = {
877
+ mode: "text",
878
+ pythonPath: getEnvString("PROMPTFOO_PYTHON", "python"),
879
+ args: [safeJsonStringify(transformedContext)]
880
+ };
881
+ logger.debug(`Executing python prompt script ${filePath}`);
882
+ const results = (await PythonShell.run(filePath, options)).join("\n");
883
+ logger.debug(`Python prompt script ${filePath} returned: ${results}`);
884
+ return results;
1004
885
  };
1005
- const DefaultGitHubGradingProvider = new OpenAiChatCompletionProvider("openai/gpt-5", { config: githubConfig });
1006
- const DefaultGitHubGradingJsonProvider = new OpenAiChatCompletionProvider("openai/gpt-5", { config: {
1007
- ...githubConfig,
1008
- response_format: { type: "json_object" }
1009
- } });
1010
- const DefaultGitHubSuggestionsProvider = new OpenAiChatCompletionProvider("openai/gpt-5", { config: githubConfig });
1011
- new OpenAiChatCompletionProvider("openai/gpt-5-nano", { config: githubConfig });
1012
- new OpenAiChatCompletionProvider("openai/gpt-5-mini", { config: githubConfig });
1013
- new OpenAiChatCompletionProvider("openai/o4-mini", { config: githubConfig });
886
+ /**
887
+ * Processes a Python file to extract or execute a function as a prompt.
888
+ * @param filePath - Path to the Python file.
889
+ * @param prompt - The raw prompt data.
890
+ * @param functionName - Optional function name to execute.
891
+ * @returns Array of prompts extracted or executed from the file.
892
+ */
893
+ function processPythonFile(filePath, prompt, functionName) {
894
+ const fileContent = fs$2.readFileSync(filePath, "utf-8");
895
+ return [{
896
+ raw: fileContent,
897
+ label: prompt.label ?? (functionName ? `${filePath}:${functionName}` : `${filePath}: ${fileContent}`),
898
+ function: functionName ? (context) => pythonPromptFunction(filePath, functionName, {
899
+ ...context,
900
+ config: prompt.config
901
+ }) : (context) => pythonPromptFunctionLegacy(filePath, {
902
+ ...context,
903
+ config: prompt.config
904
+ }),
905
+ config: prompt.config
906
+ }];
907
+ }
1014
908
  //#endregion
1015
- //#region src/providers/mistral/defaults.ts
1016
- const DefaultEmbeddingProvider$1 = new MistralEmbeddingProvider();
1017
- const DefaultGradingProvider$1 = new MistralChatCompletionProvider("mistral-large-latest");
1018
- const DefaultGradingJsonProvider$1 = new MistralChatCompletionProvider("mistral-large-latest", { config: { response_format: { type: "json_object" } } });
1019
- const DefaultSuggestionsProvider$1 = new MistralChatCompletionProvider("mistral-large-latest");
1020
- const DefaultSynthesizeProvider = new MistralChatCompletionProvider("mistral-large-latest");
909
+ //#region src/prompts/processors/string.ts
910
+ /**
911
+ * Processes a string as a literal prompt.
912
+ * @param prompt - The raw prompt data.
913
+ * @returns Array of prompts created from the string.
914
+ */
915
+ function processString(prompt) {
916
+ invariant(typeof prompt.raw === "string", `prompt.raw must be a string, but got ${JSON.stringify(prompt.raw)}`);
917
+ return [{
918
+ id: prompt.id,
919
+ raw: prompt.raw,
920
+ label: prompt.label ?? `${prompt.raw}`,
921
+ config: prompt.config
922
+ }];
923
+ }
1021
924
  //#endregion
1022
- //#region src/providers/openai/defaults.ts
1023
- const DEFAULT_OPENAI_GRADING_MODEL = "gpt-5.4-2026-03-05";
1024
- const DefaultEmbeddingProvider = new OpenAiEmbeddingProvider("text-embedding-3-large");
1025
- const DefaultGradingProvider = new OpenAiChatCompletionProvider(DEFAULT_OPENAI_GRADING_MODEL);
1026
- const DefaultGradingJsonProvider = new OpenAiChatCompletionProvider(DEFAULT_OPENAI_GRADING_MODEL, { config: { response_format: { type: "json_object" } } });
1027
- const DefaultSuggestionsProvider = new OpenAiChatCompletionProvider(DEFAULT_OPENAI_GRADING_MODEL);
1028
- const DefaultModerationProvider = new OpenAiModerationProvider("omni-moderation-latest");
1029
- const DefaultWebSearchProvider = new OpenAiResponsesProvider("gpt-5.4-2026-03-05", { config: { tools: [{ type: "web_search_preview" }] } });
1030
- async function getDefaultProviderPreferences(env) {
1031
- const hasAnthropicCredentials = Boolean(getEnvString("ANTHROPIC_API_KEY") || env?.ANTHROPIC_API_KEY);
1032
- const hasOpenAiCredentials = Boolean(getEnvString("OPENAI_API_KEY") || env?.OPENAI_API_KEY);
1033
- const hasGitHubCredentials = Boolean(getEnvString("GITHUB_TOKEN") || env?.GITHUB_TOKEN);
1034
- const hasGoogleAiStudioCredentials = Boolean(getEnvString("GEMINI_API_KEY") || env?.GEMINI_API_KEY || getEnvString("GOOGLE_API_KEY") || env?.GOOGLE_API_KEY || getEnvString("PALM_API_KEY") || env?.PALM_API_KEY);
1035
- const hasAzureApiKey = getEnvString("AZURE_OPENAI_API_KEY") || env?.AZURE_OPENAI_API_KEY || getEnvString("AZURE_API_KEY") || env?.AZURE_API_KEY;
1036
- const hasAzureClientCreds = (getEnvString("AZURE_CLIENT_ID") || env?.AZURE_CLIENT_ID) && (getEnvString("AZURE_CLIENT_SECRET") || env?.AZURE_CLIENT_SECRET) && (getEnvString("AZURE_TENANT_ID") || env?.AZURE_TENANT_ID);
1037
- const hasMistralCredentials = Boolean(getEnvString("MISTRAL_API_KEY") || env?.MISTRAL_API_KEY);
1038
- const preferAzure = Boolean(!hasOpenAiCredentials && (hasAzureApiKey || hasAzureClientCreds) && (getEnvString("AZURE_DEPLOYMENT_NAME") || env?.AZURE_DEPLOYMENT_NAME) && (getEnvString("AZURE_OPENAI_DEPLOYMENT_NAME") || env?.AZURE_OPENAI_DEPLOYMENT_NAME));
1039
- const preferAnthropic = !hasOpenAiCredentials && hasAnthropicCredentials;
1040
- const shouldUseFallbackDefaults = !preferAzure && !hasOpenAiCredentials && !hasAnthropicCredentials && !hasGoogleAiStudioCredentials;
1041
- const useGoogleVertexDefaults = shouldUseFallbackDefaults ? await hasGoogleDefaultCredentials() : false;
1042
- const useNonGoogleFallbackDefaults = shouldUseFallbackDefaults && !useGoogleVertexDefaults;
1043
- const hasCodexCredentials = useNonGoogleFallbackDefaults && !hasMistralCredentials && hasCodexDefaultCredentials(env);
1044
- return {
1045
- preferAnthropic,
1046
- preferAzure,
1047
- useCodexDefaults: hasCodexCredentials,
1048
- useGitHubDefaults: useNonGoogleFallbackDefaults && !hasMistralCredentials && !hasCodexCredentials && hasGitHubCredentials,
1049
- useGoogleAiStudioDefaults: !hasOpenAiCredentials && !hasAnthropicCredentials && hasGoogleAiStudioCredentials,
1050
- useGoogleVertexDefaults,
1051
- useMistralDefaults: useNonGoogleFallbackDefaults && hasMistralCredentials
925
+ //#region src/prompts/processors/text.ts
926
+ /**
927
+ * Processes a text file to extract prompts, splitting by a delimiter.
928
+ * @param filePath - Path to the text file.
929
+ * @param prompt - The raw prompt data.
930
+ * @returns Array of prompts extracted from the file.
931
+ */
932
+ function processTxtFile(filePath, { label }) {
933
+ const lines = fs$2.readFileSync(filePath, "utf-8").split(/\r?\n/);
934
+ const prompts = [];
935
+ let buffer = [];
936
+ const flush = () => {
937
+ const raw = buffer.join("\n").trim();
938
+ if (raw.length > 0) prompts.push({
939
+ raw,
940
+ label: label ? `${label}: ${filePath}: ${raw}` : `${filePath}: ${raw}`
941
+ });
942
+ buffer = [];
1052
943
  };
944
+ for (const line of lines) if (line.trim() === PROMPT_DELIMITER) flush();
945
+ else buffer.push(line);
946
+ flush();
947
+ return prompts;
1053
948
  }
1054
- async function getDefaultProviders(env) {
1055
- const { preferAnthropic, preferAzure, useCodexDefaults, useGitHubDefaults, useGoogleAiStudioDefaults, useGoogleVertexDefaults, useMistralDefaults } = await getDefaultProviderPreferences(env);
1056
- let providers;
1057
- if (preferAzure) {
1058
- logger.debug("Using Azure OpenAI default providers");
1059
- const deploymentName = getEnvString("AZURE_OPENAI_DEPLOYMENT_NAME") || env?.AZURE_OPENAI_DEPLOYMENT_NAME;
1060
- if (!deploymentName) throw new Error("AZURE_OPENAI_DEPLOYMENT_NAME must be set when using Azure OpenAI");
1061
- const embeddingDeploymentName = getEnvString("AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME") || env?.AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME || deploymentName;
1062
- const azureProvider = new AzureChatCompletionProvider(deploymentName, { env });
1063
- providers = {
1064
- embeddingProvider: new AzureEmbeddingProvider(embeddingDeploymentName, { env }),
1065
- gradingJsonProvider: azureProvider,
1066
- gradingProvider: azureProvider,
1067
- moderationProvider: DefaultModerationProvider,
1068
- suggestionsProvider: azureProvider,
1069
- synthesizeProvider: azureProvider
1070
- };
1071
- } else if (preferAnthropic) {
1072
- logger.debug("Using Anthropic default providers");
1073
- const anthropicProviders = getAnthropicProviders(env);
1074
- providers = {
1075
- embeddingProvider: DefaultEmbeddingProvider,
1076
- gradingJsonProvider: anthropicProviders.gradingJsonProvider,
1077
- gradingProvider: anthropicProviders.gradingProvider,
1078
- llmRubricProvider: anthropicProviders.llmRubricProvider,
1079
- moderationProvider: DefaultModerationProvider,
1080
- suggestionsProvider: anthropicProviders.suggestionsProvider,
1081
- synthesizeProvider: anthropicProviders.synthesizeProvider,
1082
- webSearchProvider: anthropicProviders.webSearchProvider
1083
- };
1084
- } else if (useGoogleAiStudioDefaults) {
1085
- logger.debug("Using Google AI Studio default providers");
1086
- providers = {
1087
- embeddingProvider: DefaultEmbeddingProvider$2,
1088
- gradingJsonProvider: DefaultGradingJsonProvider$2,
1089
- gradingProvider: DefaultGradingProvider$2,
1090
- llmRubricProvider: DefaultLlmRubricProvider,
1091
- moderationProvider: DefaultModerationProvider,
1092
- suggestionsProvider: DefaultSuggestionsProvider$2,
1093
- synthesizeProvider: DefaultSynthesizeProvider$1
1094
- };
1095
- } else if (useGoogleVertexDefaults) {
1096
- logger.debug("Using Google Vertex default providers");
1097
- providers = {
1098
- embeddingProvider: DefaultEmbeddingProvider$2,
1099
- gradingJsonProvider: DefaultGradingProvider$3,
1100
- gradingProvider: DefaultGradingProvider$3,
1101
- moderationProvider: DefaultModerationProvider,
1102
- suggestionsProvider: DefaultGradingProvider$3,
1103
- synthesizeProvider: DefaultGradingProvider$3
1104
- };
1105
- } else if (useMistralDefaults) {
1106
- logger.debug("Using Mistral default providers");
1107
- providers = {
1108
- embeddingProvider: DefaultEmbeddingProvider$1,
1109
- gradingJsonProvider: DefaultGradingJsonProvider$1,
1110
- gradingProvider: DefaultGradingProvider$1,
1111
- moderationProvider: DefaultModerationProvider,
1112
- suggestionsProvider: DefaultSuggestionsProvider$1,
1113
- synthesizeProvider: DefaultSynthesizeProvider
1114
- };
1115
- } else if (useCodexDefaults) {
1116
- logger.debug("Using Codex SDK default providers from ChatGPT/Codex credentials");
1117
- providers = {
1118
- embeddingProvider: DefaultEmbeddingProvider,
1119
- moderationProvider: DefaultModerationProvider,
1120
- ...getCodexDefaultProviders(env)
1121
- };
1122
- } else if (useGitHubDefaults) {
1123
- logger.debug("Using GitHub Models default providers");
1124
- providers = {
1125
- embeddingProvider: DefaultEmbeddingProvider,
1126
- gradingJsonProvider: DefaultGitHubGradingJsonProvider,
1127
- gradingProvider: DefaultGitHubGradingProvider,
1128
- moderationProvider: DefaultModerationProvider,
1129
- suggestionsProvider: DefaultGitHubSuggestionsProvider,
1130
- synthesizeProvider: DefaultGitHubGradingJsonProvider
1131
- };
1132
- } else {
1133
- logger.debug("Using OpenAI default providers");
1134
- providers = {
1135
- embeddingProvider: DefaultEmbeddingProvider,
1136
- gradingJsonProvider: DefaultGradingJsonProvider,
1137
- gradingProvider: DefaultGradingProvider,
1138
- moderationProvider: DefaultModerationProvider,
1139
- suggestionsProvider: DefaultSuggestionsProvider,
1140
- synthesizeProvider: DefaultGradingJsonProvider,
1141
- webSearchProvider: DefaultWebSearchProvider
1142
- };
949
+ //#endregion
950
+ //#region src/prompts/processors/yaml.ts
951
+ /**
952
+ * Processes a YAML file to extract prompts.
953
+ * This function reads a YAML file, parses it, and maps each entry to a `Prompt` object.
954
+ * Each prompt is labeled with the file path and the YAML content.
955
+ * Any file:// references within the YAML content are recursively resolved.
956
+ *
957
+ * @param filePath - The path to the YAML file.
958
+ * @param prompt - The raw prompt data, used for labeling.
959
+ * @returns An array of `Prompt` objects extracted from the YAML file.
960
+ * @throws Will throw an error if the file cannot be read or parsed.
961
+ */
962
+ function processYamlFile(filePath, prompt) {
963
+ const fileContents = fs$2.readFileSync(filePath, "utf8");
964
+ let maybeParsed = fileContents;
965
+ try {
966
+ const resolved = maybeLoadConfigFromExternalFile(yaml.load(fileContents));
967
+ maybeParsed = JSON.stringify(resolved);
968
+ } catch (e) {
969
+ logger.debug(`Error parsing YAML file ${filePath}: ${e}`);
1143
970
  }
1144
- if (getEnvString("AZURE_CONTENT_SAFETY_ENDPOINT") || env?.AZURE_CONTENT_SAFETY_ENDPOINT) providers.moderationProvider = new AzureModerationProvider("text-content-safety", { env });
1145
- return providers;
971
+ return [{
972
+ raw: maybeParsed,
973
+ label: prompt.label || `${filePath}: ${maybeParsed?.slice(0, 80)}`,
974
+ config: prompt.config
975
+ }];
1146
976
  }
1147
977
  //#endregion
1148
- //#region src/providers/webSearchUtils.ts
1149
- function hasTool(provider, predicate) {
1150
- return Array.isArray(provider.config?.tools) && provider.config.tools.some(predicate);
1151
- }
1152
- function getProviderId(provider) {
1153
- if (typeof provider.id !== "function") return null;
1154
- try {
1155
- return provider.id();
1156
- } catch (err) {
1157
- logger.debug(`Failed to read provider id: ${err}`);
1158
- return null;
1159
- }
1160
- }
1161
- function isOpenAiResponsesProvider(provider, id) {
1162
- return id.includes("openai:responses") || provider.constructor?.name === "OpenAiResponsesProvider";
1163
- }
978
+ //#region src/external/prompts/ragas.ts
979
+ const ANSWER_RELEVANCY_GENERATE = `Generate question for the given answer.
980
+ Answer:\nThe PSLV-C56 mission is scheduled to be launched on Sunday, 30 July 2023 at 06:30 IST / 01:00 UTC. It will be launched from the Satish Dhawan Space Centre, Sriharikota, Andhra Pradesh, India
981
+ Question: When is the scheduled launch date and time for the PSLV-C56 mission, and where will it be launched from?
982
+
983
+ Answer:{{answer}}
984
+ Question:`;
985
+ const CONTEXT_RECALL = `Given a context, and an answer, analyze each sentence in the answer and classify if the sentence can be attributed to the given context or not.
986
+ Think in steps and reason before coming to conclusion.
987
+
988
+ context: Albert Einstein (14 March 1879 – 18 April 1955) was a German-born theoretical physicist,widely held to be one of the greatest and most influential scientists of all time. Best known for developing the theory of relativity, he also made important contributions to quantum mechanics, and was thus a central figure in the revolutionary reshaping of the scientific understanding of nature that modern physics accomplished in the first decades of the twentieth century. His mass–energy equivalence formula E = mc2, which arises from relativity theory, has been called "the world's most famous equation". He received the 1921 Nobel Prize in Physics "for his services to theoretical physics, and especially for his discovery of the law of the photoelectric effect", a pivotal step in the development of quantum theory. His work is also known for its influence on the philosophy of science. In a 1999 poll of 130 leading physicists worldwide by the British journal Physics World, Einstein was ranked the greatest physicist of all time. His intellectual achievements and originality have made Einstein synonymous with genius.
989
+ answer: Albert Einstein born in 14 March 1879 was German-born theoretical physicist, widely held to be one of the greatest and most influential scientists of all time. He received the 1921 Nobel Prize in Physics "for his services to theoretical physics. He published 4 papers in 1905. Einstein moved to Switzerland in 1895
990
+ classification
991
+ 1. Albert Einstein born in 14 March 1879 was German-born theoretical physicist, widely held to be one of the greatest and most influential scientists of all time. The date of birth of Einstein is mentioned clearly in the context. So [Attributed]
992
+ 2. He received the 1921 Nobel Prize in Physics "for his services to theoretical physics. The exact sentence is present in the given context. So [Attributed]
993
+ 3. He published 4 papers in 1905. There is no mention about papers he wrote in given the context. So [Not Attributed]
994
+ 4. Einstein moved to Switzerland in 1895. There is not supporting evidence for this in the given the context. So [Not Attributed]
995
+
996
+ context:{{context}}
997
+ answer:{{groundTruth}}
998
+ classification:
999
+ `;
1000
+ const CONTEXT_RECALL_ATTRIBUTED_TOKEN = "[Attributed]";
1001
+ const CONTEXT_RECALL_NOT_ATTRIBUTED_TOKEN = "[Not Attributed]";
1002
+ const CONTEXT_RELEVANCE = `Please extract relevant sentences from the provided context that is absolutely required answer the following query. If no relevant sentences are found, or if you believe the query cannot be answered from the given context, return the phrase "Insufficient Information". While extracting candidate sentences you're not allowed to make any changes to sentences from given context.
1003
+
1004
+ query: {{query}}
1005
+ context: {{context}}
1006
+ candidate sentences:
1007
+ `;
1008
+ const CONTEXT_RELEVANCE_BAD = "Insufficient Information";
1009
+ const CONTEXT_FAITHFULNESS_LONGFORM = `Given a question and answer, create one or more statements from each sentence in the given answer.
1010
+ question: Who was Albert Einstein and what is he best known for?
1011
+ answer: He was a German-born theoretical physicist, widely acknowledged to be one of the greatest and most influential physicists of all time. He was best known for developing the theory of relativity, he also made important contributions to the development of the theory of quantum mechanics.
1012
+ statements:\nAlbert Einstein was born in Germany.\nAlbert Einstein was best known for his theory of relativity.
1013
+ question: Cadmium Chloride is slightly soluble in this chemical, it is also called what?
1014
+ answer: alcohol
1015
+ statements:\nCadmium Chloride is slightly soluble in alcohol.
1016
+ question: Were Shahul and Jithin of the same nationality?
1017
+ answer: They were from different countries.
1018
+ statements:\nShahul and Jithin were from different countries.
1019
+ question:{{question}}
1020
+ answer: {{answer}}
1021
+ statements:\n`;
1022
+ const CONTEXT_FAITHFULNESS_NLI_STATEMENTS = `Prompt: Natural language inference
1023
+ Consider the given context and following statements, then determine whether they are supported by the information present in the context.Provide a brief explanation for each statement before arriving at the verdict (Yes/No). Provide a final verdict for each statement in order at the end in the given format. Do not deviate from the specified format.
1024
+
1025
+ Context:\nJohn is a student at XYZ University. He is pursuing a degree in Computer Science. He is enrolled in several courses this semester, including Data Structures, Algorithms, and Database Management. John is a diligent student and spends a significant amount of time studying and completing assignments. He often stays late in the library to work on his projects.
1026
+ statements:\n1. John is majoring in Biology.\n2. John is taking a course on Artificial Intelligence.\n3. John is a dedicated student.\n4. John has a part-time job.\n5. John is interested in computer programming.\n
1027
+ Answer:
1028
+ 1. John is majoring in Biology.
1029
+ Explanation: John's major is explicitly mentioned as Computer Science. There is no information suggesting he is majoring in Biology. Verdict: No.
1030
+ 2. John is taking a course on Artificial Intelligence.
1031
+ Explanation: The context mentions the courses John is currently enrolled in, and Artificial Intelligence is not mentioned. Therefore, it cannot be deduced that John is taking a course on AI. Verdict: No.
1032
+ 3. John is a dedicated student.
1033
+ Explanation: The prompt states that he spends a significant amount of time studying and completing assignments. Additionally, it mentions that he often stays late in the library to work on his projects, which implies dedication. Verdict: Yes.
1034
+ 4. John has a part-time job.
1035
+ Explanation: There is no information given in the context about John having a part-time job. Therefore, it cannot be deduced that John has a part-time job. Verdict: No.
1036
+ 5. John is interested in computer programming.
1037
+ Explanation: The context states that John is pursuing a degree in Computer Science, which implies an interest in computer programming. Verdict: Yes.
1038
+ Final verdict for each statement in order: No. No. Yes. No. Yes.
1039
+ context:\n{{context}}
1040
+ statements:\n{{statements|join("\\n")}}
1041
+ Answer:
1042
+ `;
1043
+ //#endregion
1044
+ //#region src/prompts/grading.ts
1045
+ const DEFAULT_GRADING_PROMPT = JSON.stringify([{
1046
+ role: "system",
1047
+ content: dedent`You are grading output according to a user-specified rubric. If the statement in the rubric is true, then the output passes the test. You respond with a JSON object with this structure: {reason: string, pass: boolean, score: number}
1048
+
1049
+ Examples:
1050
+
1051
+ <Output>Hello world</Output>
1052
+ <Rubric>Content contains a greeting</Rubric>
1053
+ {"reason": "the content contains the word 'Hello'", "pass": true, "score": 1.0}
1054
+
1055
+ <Output>Avast ye swabs, repel the invaders!</Output>
1056
+ <Rubric>Does not speak like a pirate</Rubric>
1057
+ {"reason": "'avast ye' is a common pirate term", "pass": false, "score": 0.0}`
1058
+ }, {
1059
+ role: "user",
1060
+ content: "<Output>\n{{ output }}\n</Output>\n<Rubric>\n{{ rubric }}\n</Rubric>"
1061
+ }]);
1062
+ const PROMPTFOO_FACTUALITY_PROMPT = JSON.stringify([{
1063
+ role: "system",
1064
+ content: dedent`
1065
+ You are a precise factuality evaluator that compares a submitted answer to an expert answer.
1066
+
1067
+ Your task is to analyze the factual content while ignoring differences in style, grammar, or punctuation.
1068
+ You must categorize the submission into one of these options:
1069
+
1070
+ (A) The submitted answer is a subset of the expert answer and is fully consistent with it.
1071
+ (B) The submitted answer is a superset of the expert answer and is fully consistent with it.
1072
+ (C) The submitted answer contains all the same details as the expert answer.
1073
+ (D) There is a disagreement between the submitted answer and the expert answer.
1074
+ (E) The answers differ, but these differences don't matter from the perspective of factuality.
1075
+
1076
+ Respond ONLY with a JSON object in this format:
1077
+ {
1078
+ "category": "[LETTER]",
1079
+ "reason": "[DETAILED EXPLANATION]"
1080
+ }
1081
+
1082
+ - The "category" must be a single letter A, B, C, D, or E.
1083
+ - Provide a clear, detailed explanation in the "reason" field.
1084
+ - Your response must be valid JSON with no additional text.`
1085
+ }, {
1086
+ role: "user",
1087
+ content: dedent`
1088
+ I need you to compare these answers:
1089
+
1090
+ <question>
1091
+ {{input}}
1092
+ </question>
1093
+
1094
+ <expert_answer>
1095
+ {{ideal}}
1096
+ </expert_answer>
1097
+
1098
+ <submitted_answer>
1099
+ {{completion}}
1100
+ </submitted_answer>
1101
+
1102
+ Please analyze the factual relationship between these answers according to the categories you've been given.`
1103
+ }]);
1104
+ const OPENAI_CLOSED_QA_PROMPT = JSON.stringify([{
1105
+ role: "system",
1106
+ content: `You are assessing a submitted answer on a given task based on a criterion. Here is the data:
1107
+ [BEGIN DATA]
1108
+ ***
1109
+ [Task]: {{input}}
1110
+ ***
1111
+ [Submission]: {{completion}}
1112
+ ***
1113
+ [Criterion]: {{criteria}}
1114
+ ***
1115
+ [END DATA]
1116
+ Does the submission meet the criterion? First, write out in a step by step manner your reasoning about the criterion to be sure that your conclusion is correct. Avoid simply stating the correct answers at the outset. Then print only the single character "Y" or "N" (without quotes or punctuation) on its own line corresponding to the correct answer. At the end, repeat just the letter again by itself on a new line.
1117
+
1118
+ Reasoning:`
1119
+ }]);
1120
+ const SUGGEST_PROMPTS_SYSTEM_MESSAGE = {
1121
+ role: "system",
1122
+ content: `You're helping a scientist who is tuning a prompt for a large language model. You will receive messages, and each message is a full prompt. Generate a candidate variation of the given prompt. This variation will be tested for quality in order to select a winner.
1123
+
1124
+ Substantially revise the prompt, revising its structure and content however necessary to make it perform better, while preserving the original intent and including important details.
1125
+
1126
+ Your output is going to be copied directly into the program. It should contain the prompt ONLY`
1127
+ };
1128
+ const SELECT_BEST_PROMPT = JSON.stringify([{
1129
+ role: "system",
1130
+ content: `You are comparing multiple pieces of text to see which best fits the following criteria: {{criteria}}
1131
+
1132
+ Here are the pieces of text:
1133
+
1134
+ {% for output in outputs %}
1135
+ <Text index="{{ loop.index0 }}">
1136
+ {{ output }}
1137
+ </Text>
1138
+ {% endfor %}
1139
+
1140
+ Output the index of the text that best fits the criteria. You must output a single integer.`
1141
+ }]);
1142
+ const DEFAULT_WEB_SEARCH_PROMPT = JSON.stringify([{
1143
+ role: "system",
1144
+ content: dedent`You are grading output according to a user-specified rubric, with the ability to search the web for current information. If the statement in the rubric is true, then the output passes the test. You respond with a JSON object with this structure: {reason: string, pass: boolean, score: number}
1145
+
1146
+ You MUST search the web when:
1147
+ - The rubric asks about current information (prices, weather, news, etc.)
1148
+ - Facts need to be verified against recent data
1149
+ - The rubric references time-sensitive information
1150
+
1151
+ Examples:
1152
+
1153
+ <Output>The current CEO of Microsoft is Satya Nadella</Output>
1154
+ <Rubric>Contains accurate information about Microsoft's leadership</Rubric>
1155
+ {"reason": "I searched and confirmed Satya Nadella is indeed the current CEO of Microsoft", "pass": true, "score": 1.0}
1156
+
1157
+ <Output>Bitcoin is trading at $45,000</Output>
1158
+ <Rubric>Provides current Bitcoin price within 10% accuracy</Rubric>
1159
+ {"reason": "Web search shows Bitcoin is currently trading at $98,000, not $45,000. The output is off by more than 50%", "pass": false, "score": 0.0}`
1160
+ }, {
1161
+ role: "user",
1162
+ content: "<Output>\n{{ output }}\n</Output>\n<Rubric>\n{{ rubric }}\n</Rubric>"
1163
+ }]);
1164
+ const TRAJECTORY_GOAL_SUCCESS_PROMPT = JSON.stringify([{
1165
+ role: "system",
1166
+ content: dedent`You are grading whether an AI agent successfully completed a goal based on its final output and a summarized execution trajectory. You respond with a JSON object with this structure: {reason: string, pass: boolean, score: number}
1167
+
1168
+ Judge end-to-end success, not stylistic perfection.
1169
+ Use the trajectory as evidence for what the agent actually did.
1170
+ Give partial credit when the agent made progress but did not fully achieve the goal.
1171
+
1172
+ Examples:
1173
+
1174
+ <Goal>Find the order status and tell the user whether it has shipped</Goal>
1175
+ <Trajectory>{"stepCount":2,"steps":[{"index":1,"type":"tool","name":"search_orders"},{"index":2,"type":"message","name":"agent response"}]}</Trajectory>
1176
+ <Output>Your order shipped yesterday and should arrive on Tuesday.</Output>
1177
+ {"reason":"The agent used the order lookup tool and gave the user the shipping status, so the goal was achieved.","pass":true,"score":1.0}
1178
+
1179
+ <Goal>Find the order status and tell the user whether it has shipped</Goal>
1180
+ <Trajectory>{"stepCount":1,"steps":[{"index":1,"type":"message","name":"agent response"}]}</Trajectory>
1181
+ <Output>I cannot check your order right now.</Output>
1182
+ {"reason":"The agent did not show evidence of checking the order and did not provide the requested status.","pass":false,"score":0.0}`
1183
+ }, {
1184
+ role: "user",
1185
+ content: dedent`<Goal>
1186
+ {{ goal }}
1187
+ </Goal>
1188
+ <Trajectory>
1189
+ {{ trajectory }}
1190
+ </Trajectory>
1191
+ <Output>
1192
+ {{ output }}
1193
+ </Output>`
1194
+ }]);
1195
+ //#endregion
1196
+ //#region src/prompts/index.ts
1164
1197
  /**
1165
- * Check if a provider has web search capabilities
1166
- * @param provider The provider to check
1167
- * @returns true if the provider supports web search
1198
+ * Reads and maps provider prompts based on the configuration and parsed prompts.
1199
+ * @param config - The configuration object.
1200
+ * @param parsedPrompts - Array of parsed prompts.
1201
+ * @returns A map of provider IDs to their respective prompts.
1168
1202
  */
1169
- function hasWebSearchCapability(provider) {
1170
- if (!provider) return false;
1171
- const id = getProviderId(provider);
1172
- if (!id) return false;
1173
- if (id.includes("perplexity")) return true;
1174
- if ((id.includes("google") || id.includes("gemini") || id.includes("vertex")) && hasTool(provider, (t) => t.googleSearch !== void 0)) return true;
1175
- if (id.includes("xai") && provider.config?.search_parameters?.mode === "on") return true;
1176
- if (isOpenAiResponsesProvider(provider, id) && hasTool(provider, (t) => t.type === "web_search_preview")) return true;
1177
- if (id.startsWith("openai:codex") && (provider.config?.web_search_mode === "live" || provider.config?.web_search_mode === "cached" || provider.config?.web_search_enabled === true)) return true;
1178
- if (id.includes("anthropic") && hasTool(provider, (t) => t.type === "web_search_20250305")) return true;
1179
- return false;
1203
+ function readProviderPromptMap(config, parsedPrompts) {
1204
+ const ret = {};
1205
+ if (!config.providers) return ret;
1206
+ const allPrompts = [];
1207
+ for (const prompt of parsedPrompts) allPrompts.push(prompt.label);
1208
+ if (typeof config.providers === "string") return { [config.providers]: allPrompts };
1209
+ if (typeof config.providers === "function") return { "Custom function": allPrompts };
1210
+ for (const provider of config.providers) if (typeof provider === "object") if (provider.id) {
1211
+ const rawProvider = provider;
1212
+ invariant(rawProvider.id, "You must specify an `id` on the Provider when you override options.prompts");
1213
+ ret[rawProvider.id] = rawProvider.prompts || allPrompts;
1214
+ if (rawProvider.label) ret[rawProvider.label] = rawProvider.prompts || allPrompts;
1215
+ } else {
1216
+ const rawProvider = provider;
1217
+ const originalId = Object.keys(rawProvider)[0];
1218
+ const id = rawProvider[originalId].id || originalId;
1219
+ ret[id] = rawProvider[originalId].prompts || allPrompts;
1220
+ }
1221
+ return ret;
1180
1222
  }
1181
1223
  /**
1182
- * Load a provider with web search capabilities.
1183
- * Tries multiple providers in order of preference until one succeeds.
1184
- * Uses the latest and most capable models from each provider with specific checkpoint IDs.
1185
- *
1186
- * @param preferAnthropic Whether to try Anthropic first (true) or OpenAI first (false)
1187
- * @returns A provider with web search capabilities or null
1224
+ * Processes a raw prompt based on its content type and path.
1225
+ * @param prompt - The raw prompt data.
1226
+ * @param basePath - Base path for file resolution.
1227
+ * @param maxRecursionDepth - Maximum recursion depth for globbing.
1228
+ * @returns Promise resolving to an array of processed prompts.
1188
1229
  */
1189
- async function loadWebSearchProvider(preferAnthropic = false) {
1190
- const loadAnthropicWebSearch = async () => {
1191
- try {
1192
- return await loadApiProvider("anthropic:messages:claude-opus-4-6", { options: { config: { tools: [{
1193
- type: "web_search_20250305",
1194
- name: "web_search",
1195
- max_uses: 5
1196
- }] } } });
1197
- } catch (err) {
1198
- logger.debug(`Failed to load Anthropic web search provider: ${err}`);
1199
- return null;
1200
- }
1201
- };
1202
- const loadOpenAIWebSearch = async () => {
1203
- try {
1204
- return await loadApiProvider("openai:responses:gpt-5.4-2026-03-05", { options: { config: { tools: [{ type: "web_search_preview" }] } } });
1205
- } catch (err) {
1206
- logger.debug(`Failed to load OpenAI web search provider: ${err}`);
1207
- return null;
1208
- }
1209
- };
1210
- const loadPerplexity = async () => {
1211
- try {
1212
- return await loadApiProvider("perplexity:sonar-pro");
1213
- } catch (err) {
1214
- logger.debug(`Failed to load Perplexity provider: ${err}`);
1215
- return null;
1216
- }
1217
- };
1218
- const loadGoogleWebSearch = async () => {
1219
- try {
1220
- return await loadApiProvider("google:gemini-3-pro-preview", { options: { config: { tools: [{ googleSearch: {} }] } } });
1221
- } catch (err) {
1222
- logger.debug(`Failed to load Google web search provider: ${err}`);
1223
- return null;
1230
+ async function processPrompt(prompt, basePath = "", maxRecursionDepth = 1) {
1231
+ invariant(typeof prompt.raw === "string", `prompt.raw must be a string, but got ${JSON.stringify(prompt.raw)}`);
1232
+ if (prompt.function) return [prompt];
1233
+ if (prompt.raw.startsWith("exec:")) {
1234
+ const { filePath, functionName } = parsePathOrGlob(basePath, prompt.raw.substring(5));
1235
+ return await processExecutableFile(filePath, prompt, functionName);
1236
+ }
1237
+ if (!maybeFilePath(prompt.raw)) return processString(prompt);
1238
+ const { extension, functionName, isPathPattern, filePath } = parsePathOrGlob(basePath, prompt.raw);
1239
+ if (isPathPattern && maxRecursionDepth > 0) {
1240
+ const globbedPath = globSync(filePath.replace(/\\/g, "/"), { windowsPathsNoEscape: true });
1241
+ logger.debug(`Expanded prompt ${prompt.raw} to ${filePath} and then to ${JSON.stringify(globbedPath)}`);
1242
+ const prompts = [];
1243
+ for (const globbedFilePath of globbedPath) {
1244
+ const processedPrompts = await processPrompt({ raw: functionName ? `${globbedFilePath}:${functionName}` : globbedFilePath }, basePath, maxRecursionDepth - 1);
1245
+ prompts.push(...processedPrompts);
1224
1246
  }
1225
- };
1226
- const loadVertexWebSearch = async () => {
1227
- try {
1228
- return await loadApiProvider("vertex:gemini-3-pro-preview", { options: { config: { tools: [{ googleSearch: {} }] } } });
1229
- } catch (err) {
1230
- logger.debug(`Failed to load Vertex web search provider: ${err}`);
1231
- return null;
1247
+ if (prompts.length === 0) {
1248
+ logger.debug(`Attempted to load file at "${prompt.raw}", but no file found. Using raw string.`);
1249
+ prompts.push(...processString(prompt));
1232
1250
  }
1233
- };
1234
- const loadXaiWebSearch = async () => {
1251
+ return prompts;
1252
+ }
1253
+ if (extension === ".csv") return processCsvPrompts(filePath, prompt);
1254
+ if (extension === ".j2") return processJinjaFile(filePath, prompt);
1255
+ if (extension === ".json") return processJsonFile(filePath, prompt);
1256
+ if (extension === ".jsonl") return processJsonlFile(filePath, prompt);
1257
+ if (extension && isJavascriptFile(extension)) return processJsFile(filePath, prompt, functionName);
1258
+ if (extension === ".md") return processMarkdownFile(filePath, prompt);
1259
+ if (extension === ".py") return processPythonFile(filePath, prompt, functionName);
1260
+ if (extension === ".txt") return processTxtFile(filePath, prompt);
1261
+ if (extension && [".yml", ".yaml"].includes(extension)) return processYamlFile(filePath, prompt);
1262
+ if (extension && [
1263
+ ".sh",
1264
+ ".bash",
1265
+ ".exe",
1266
+ ".bat",
1267
+ ".cmd",
1268
+ ".ps1",
1269
+ ".rb",
1270
+ ".pl"
1271
+ ].includes(extension)) return await processExecutableFile(filePath, prompt, functionName);
1272
+ try {
1273
+ const stats = await stat(filePath);
1274
+ if (stats.isFile() && (stats.mode & 73) !== 0) return await processExecutableFile(filePath, prompt, functionName);
1275
+ } catch (_e) {}
1276
+ return [];
1277
+ }
1278
+ /**
1279
+ * Reads and processes prompts from a specified path or glob pattern.
1280
+ * @param promptPathOrGlobs - The path or glob pattern.
1281
+ * @param basePath - Base path for file resolution.
1282
+ * @returns Promise resolving to an array of processed prompts.
1283
+ */
1284
+ async function readPrompts(promptPathOrGlobs, basePath = "") {
1285
+ logger.debug(`Reading prompts from ${JSON.stringify(promptPathOrGlobs)}`);
1286
+ const promptPartials = normalizeInput(promptPathOrGlobs);
1287
+ const prompts = [];
1288
+ for (const prompt of promptPartials) {
1289
+ const promptBatch = await processPrompt(prompt, basePath);
1290
+ if (promptBatch.length === 0) throw new Error(`There are no prompts in ${JSON.stringify(prompt.raw)}`);
1291
+ prompts.push(...promptBatch);
1292
+ }
1293
+ return prompts;
1294
+ }
1295
+ async function processPrompts(prompts) {
1296
+ return (await Promise.all(prompts.map(async (promptInput) => {
1297
+ if (typeof promptInput === "function") return {
1298
+ raw: promptInput.toString(),
1299
+ label: promptInput?.name ?? promptInput.toString(),
1300
+ function: promptInput
1301
+ };
1302
+ else if (typeof promptInput === "string") return readPrompts(promptInput);
1235
1303
  try {
1236
- return await loadApiProvider("xai:grok-4-1-fast-reasoning", { options: { config: { search_parameters: { mode: "on" } } } });
1237
- } catch (err) {
1238
- logger.debug(`Failed to load xAI web search provider: ${err}`);
1239
- return null;
1240
- }
1241
- };
1242
- const providers = preferAnthropic ? [
1243
- loadAnthropicWebSearch,
1244
- loadOpenAIWebSearch,
1245
- loadPerplexity,
1246
- loadGoogleWebSearch,
1247
- loadVertexWebSearch,
1248
- loadXaiWebSearch
1249
- ] : [
1250
- loadOpenAIWebSearch,
1251
- loadAnthropicWebSearch,
1252
- loadPerplexity,
1253
- loadGoogleWebSearch,
1254
- loadVertexWebSearch,
1255
- loadXaiWebSearch
1256
- ];
1257
- for (const getProvider of providers) {
1258
- const provider = await getProvider();
1259
- if (provider && hasWebSearchCapability(provider)) {
1260
- logger.info(`Using ${getProviderId(provider) ?? "loaded provider"} as web search provider`);
1261
- return provider;
1304
+ return PromptSchema.parse(promptInput);
1305
+ } catch (error) {
1306
+ logger.warn(`Prompt input is not a valid prompt schema: ${error}\nFalling back to serialized JSON as raw prompt.`);
1307
+ return {
1308
+ raw: JSON.stringify(promptInput),
1309
+ label: JSON.stringify(promptInput)
1310
+ };
1262
1311
  }
1263
- if (provider) logger.debug(`Loaded provider ${getProviderId(provider) ?? "unknown"} does not support web search`);
1264
- }
1265
- return null;
1312
+ }))).flat();
1266
1313
  }
1314
+ const GEVAL_PROMPT_STEPS = `
1315
+ Given evaluation criteria that outline how you should judge a piece of text, generate 3-4 concise evaluation steps applicable to any text based on the criteria below and designed to check whether the criteria are satisfied by the text.
1316
+
1317
+ **EVALUATION CRITERIA**
1318
+ {{criteria}}
1319
+
1320
+ **OUTPUT FORMAT**
1321
+ IMPORTANT:
1322
+ - Return output ONLY as a minified JSON object (no code fences).
1323
+ - The JSON object must contain a single key, "steps", whose value is a list of strings.
1324
+ - Each string must represent one evaluation step.
1325
+ - Do NOT include any explanations, commentary, extra text, or additional formatting.
1326
+
1327
+ Format:
1328
+ {"steps": <list_of_strings>}
1329
+
1330
+ Example:
1331
+ {"steps":["<Evaluation Step 1>","<Evaluation Step 2>","<Evaluation Step 3>","<Evaluation Step 4>"]}
1332
+
1333
+ Here are the 3-4 concise evaluation steps, formatted as required in a minified JSON:
1334
+ JSON:
1335
+ `;
1336
+ const GEVAL_PROMPT_EVALUATE = `
1337
+ You will be given one Reply for a Prompt below. Your task is to rate the Reply on one metric.
1338
+ Please make sure you read and understand these instructions carefully. Please keep this document open while reviewing, and refer to it as needed.
1339
+
1340
+ **Evaluation Criteria**
1341
+ {{criteria}}
1342
+
1343
+ **Evaluation Steps**
1344
+ - {{steps}}
1345
+ Given the evaluation steps, return a JSON with two keys:
1346
+ 1) a "score" key that MUST be an integer from 0 to {{maxScore}}, where {{maxScore}} indicates that the condition described by the Evaluation Criteria is fully and clearly observed in the Reply according to the Evaluation Steps, and 0 indicates that it is not observed at all;
1347
+ 2) a "reason" key, a reason for the given score, but DO NOT QUOTE THE SCORE in your reason. Please mention specific information from Prompt and Reply in your reason, but be very concise with it!
1348
+
1349
+ **Prompt**
1350
+ {{input}}
1351
+
1352
+ **Reply**
1353
+ {{output}}
1354
+
1355
+ **OUTPUT FORMAT**
1356
+ IMPORTANT:
1357
+ - Return output ONLY as a minified JSON object (no code fences).
1358
+ - The JSON object must contain exactly two keys: "score" and "reason".
1359
+ - No additional words, explanations, or formatting are needed.
1360
+ - Absolutely no additional text, explanations, line breaks, or formatting outside the JSON object are allowed.
1361
+
1362
+ Example JSON:
1363
+ {"score":0,"reason":"The text of reply does not follow the evaluation criteria provided."}
1364
+
1365
+ Here is the final evaluation in the required minified JSON format:
1366
+ JSON:
1367
+ `;
1267
1368
  //#endregion
1268
1369
  //#region src/remoteGrading.ts
1269
1370
  async function doRemoteGrading(payload) {
@@ -1326,23 +1427,7 @@ async function doRemoteScoringWithPi(payload, passThreshold = .5) {
1326
1427
  }
1327
1428
  }
1328
1429
  //#endregion
1329
- //#region src/scheduler/providerCallExecutionContext.ts
1330
- const providerCallExecutionContext = new AsyncLocalStorage();
1331
- function getProviderCallExecutionContext() {
1332
- return providerCallExecutionContext.getStore();
1333
- }
1334
- function withProviderCallExecutionContext(context, fn) {
1335
- return providerCallExecutionContext.run(context, fn);
1336
- }
1337
- //#endregion
1338
- //#region src/matchers.ts
1339
- var LlmRubricProviderError = class extends Error {
1340
- constructor(message) {
1341
- super(message);
1342
- this.name = "LlmRubricProviderError";
1343
- }
1344
- };
1345
- const nunjucks = getNunjucksEngine(void 0, false, true);
1430
+ //#region src/matchers/llmGrading.ts
1346
1431
  const FACTUALITY_CATEGORY_DESCRIPTIONS = {
1347
1432
  A: "The submitted answer is a subset of the expert answer and is fully consistent with it.",
1348
1433
  B: "The submitted answer is a superset of the expert answer and is fully consistent with it.",
@@ -1350,409 +1435,73 @@ const FACTUALITY_CATEGORY_DESCRIPTIONS = {
1350
1435
  D: "There is a disagreement between the submitted answer and the expert answer.",
1351
1436
  E: "The answers differ, but these differences don't matter from the perspective of factuality."
1352
1437
  };
1353
- function cosineSimilarity(vecA, vecB) {
1354
- if (vecA.length !== vecB.length) throw new Error("Vectors must be of equal length");
1355
- return vecA.reduce((acc, val, idx) => acc + val * vecB[idx], 0) / (Math.sqrt(vecA.reduce((acc, val) => acc + val * val, 0)) * Math.sqrt(vecB.reduce((acc, val) => acc + val * val, 0)));
1356
- }
1357
- function dotProduct(vecA, vecB) {
1358
- if (vecA.length !== vecB.length) throw new Error("Vectors must be of equal length");
1359
- return vecA.reduce((acc, val, idx) => acc + val * vecB[idx], 0);
1360
- }
1361
- function euclideanDistance(vecA, vecB) {
1362
- if (vecA.length !== vecB.length) throw new Error("Vectors must be of equal length");
1363
- const sumSquaredDiff = vecA.reduce((acc, val, idx) => {
1364
- const diff = val - vecB[idx];
1365
- return acc + diff * diff;
1366
- }, 0);
1367
- return Math.sqrt(sumSquaredDiff);
1368
- }
1369
- /**
1370
- * Helper to call provider with consistent context propagation pattern.
1371
- * Spreads the optional context and merges with prompt label and vars.
1372
- *
1373
- * IMPORTANT: Spread order matters - context is spread first, then prompt/vars
1374
- * override. This ensures originalProvider from context is preserved while
1375
- * allowing this call to specify its own prompt metadata.
1376
- */
1377
- function callProviderWithContext(provider, prompt, label, vars, context) {
1378
- const callApiContext = {
1379
- ...context,
1380
- prompt: {
1381
- raw: prompt,
1382
- label
1383
- },
1384
- vars
1385
- };
1386
- const executionContext = getProviderCallExecutionContext();
1387
- const callApiOptions = executionContext?.abortSignal ? { abortSignal: executionContext.abortSignal } : void 0;
1388
- const callApi = () => callApiOptions ? provider.callApi(prompt, callApiContext, callApiOptions) : provider.callApi(prompt, callApiContext);
1389
- const executeCall = () => {
1390
- if (executionContext?.rateLimitRegistry && !isRateLimitWrapped(provider)) return executionContext.rateLimitRegistry.execute(provider, callApi, createProviderRateLimitOptions());
1391
- return callApi();
1392
- };
1393
- if (executionContext?.providerCallQueue) return executionContext.providerCallQueue.enqueue(provider.id(), executeCall);
1394
- return executeCall();
1395
- }
1396
- async function loadFromProviderOptions(provider) {
1397
- invariant(typeof provider === "object", `Provider must be an object, but received a ${typeof provider}: ${provider}`);
1398
- invariant(!Array.isArray(provider), `Provider must be an object, but received an array: ${JSON.stringify(provider)}`);
1399
- invariant(provider.id, "Provider supplied to assertion must have an id");
1400
- return loadApiProvider(provider.id, {
1401
- options: provider,
1402
- basePath: state.basePath
1403
- });
1404
- }
1405
- function isSimulatedUserProviderConfig(provider) {
1406
- if (typeof provider === "string") return provider === "promptfoo:simulated-user";
1407
- if (!provider || typeof provider !== "object" || Array.isArray(provider)) return false;
1408
- if (typeof provider.id === "function") return provider.id() === "promptfoo:simulated-user";
1409
- const providerId = provider.id;
1410
- if (typeof providerId === "string") return providerId === "promptfoo:simulated-user";
1411
- return Object.values(provider).some((providerTypeConfig) => isSimulatedUserProviderConfig(providerTypeConfig));
1412
- }
1413
- async function getGradingProvider(type, provider, defaultProvider) {
1414
- let finalProvider;
1415
- if (typeof provider === "string") finalProvider = await loadApiProvider(provider, { basePath: state.basePath });
1416
- else if (typeof provider === "object" && typeof provider.id === "function") finalProvider = provider;
1417
- else if (typeof provider === "object") {
1418
- const typeValue = provider[type];
1419
- if (typeValue) finalProvider = await getGradingProvider(type, typeValue, defaultProvider);
1420
- else if (provider.id) finalProvider = await loadFromProviderOptions(provider);
1421
- else if (Array.isArray(provider)) throw new Error(`Provider must be an object or string, but received an array.\n\nCheck that the provider ${JSON.stringify(provider[0], null, 2)} is not nested in an array.`);
1422
- else throw new Error(`Invalid provider definition for output type '${type}': ${JSON.stringify(provider, null, 2)}`);
1423
- } else {
1424
- const defaultTest = state.config?.defaultTest;
1425
- const defaultTestObj = typeof defaultTest === "object" ? defaultTest : null;
1426
- const cfg = [
1427
- defaultTestObj?.provider || void 0,
1428
- defaultTestObj?.options?.provider?.text || void 0,
1429
- defaultTestObj?.options?.provider || void 0
1430
- ].find((candidateProvider) => {
1431
- if (!candidateProvider) return false;
1432
- if (isSimulatedUserProviderConfig(candidateProvider)) {
1433
- logger.debug("[Grading] Skipping promptfoo:simulated-user as an implicit grader fallback");
1434
- return false;
1435
- }
1436
- return true;
1437
- });
1438
- if (cfg) {
1439
- finalProvider = await getGradingProvider(type, cfg, defaultProvider);
1440
- if (finalProvider) logger.debug(`[Grading] Using provider from defaultTest fallback: ${finalProvider.id()}`);
1441
- } else finalProvider = defaultProvider;
1442
- }
1443
- return finalProvider;
1444
- }
1445
- async function getAndCheckProvider(type, provider, defaultProvider, checkName) {
1446
- const matchedProvider = await getGradingProvider(type, provider, defaultProvider);
1447
- if (!matchedProvider) if (defaultProvider) {
1448
- logger.warn(`No provider of type ${type} found for '${checkName}', falling back to default`);
1449
- return defaultProvider;
1450
- } else throw new Error(`No provider of type ${type} found for '${checkName}'`);
1451
- let isValidProviderType = true;
1452
- if (type === "embedding") isValidProviderType = "callEmbeddingApi" in matchedProvider || "callSimilarityApi" in matchedProvider;
1453
- else if (type === "classification") isValidProviderType = "callClassificationApi" in matchedProvider;
1454
- else if (type === "moderation") isValidProviderType = "callModerationApi" in matchedProvider;
1455
- if (!isValidProviderType) if (defaultProvider) {
1456
- logger.warn(`Provider ${matchedProvider.id()} is not a valid ${type} provider for '${checkName}', falling back to default`);
1457
- return defaultProvider;
1458
- } else throw new Error(`Provider ${matchedProvider.id()} is not a valid ${type} provider for '${checkName}'`);
1459
- return matchedProvider;
1460
- }
1461
- function fail(reason, tokensUsed) {
1462
- return {
1463
- pass: false,
1464
- reason,
1465
- score: 0,
1466
- tokensUsed: {
1467
- total: tokensUsed?.total || 0,
1468
- prompt: tokensUsed?.prompt || 0,
1469
- completion: tokensUsed?.completion || 0,
1470
- cached: tokensUsed?.cached || 0,
1471
- numRequests: tokensUsed?.numRequests || 0,
1472
- completionDetails: tokensUsed?.completionDetails
1473
- }
1474
- };
1475
- }
1476
- function normalizeTokenUsage(tokensUsed) {
1477
- return {
1478
- total: tokensUsed?.total || 0,
1479
- prompt: tokensUsed?.prompt || 0,
1480
- completion: tokensUsed?.completion || 0,
1481
- cached: tokensUsed?.cached || 0,
1482
- numRequests: tokensUsed?.numRequests || 0,
1483
- completionDetails: tokensUsed?.completionDetails || {
1484
- reasoning: 0,
1485
- acceptedPrediction: 0,
1486
- rejectedPrediction: 0
1487
- }
1488
- };
1489
- }
1490
- function createMatcherTokenUsage() {
1491
- return {
1492
- total: 0,
1493
- prompt: 0,
1494
- completion: 0,
1495
- cached: 0,
1496
- numRequests: 0,
1497
- completionDetails: {
1498
- reasoning: 0,
1499
- acceptedPrediction: 0,
1500
- rejectedPrediction: 0
1501
- }
1502
- };
1503
- }
1504
- function copySimilarityTokenUsage(tokensUsed, response) {
1505
- Object.assign(tokensUsed, normalizeTokenUsage(response.tokenUsage));
1506
- }
1507
- function combineEmbeddingTokenUsage(expectedEmbedding, outputEmbedding) {
1508
- const expectedTokens = normalizeTokenUsage(expectedEmbedding.tokenUsage);
1509
- const outputTokens = normalizeTokenUsage(outputEmbedding.tokenUsage);
1510
- return {
1511
- total: (expectedTokens.total ?? 0) + (outputTokens.total ?? 0),
1512
- prompt: (expectedTokens.prompt ?? 0) + (outputTokens.prompt ?? 0),
1513
- completion: (expectedTokens.completion ?? 0) + (outputTokens.completion ?? 0),
1514
- cached: (expectedTokens.cached ?? 0) + (outputTokens.cached ?? 0),
1515
- numRequests: (expectedTokens.numRequests ?? 0) + (outputTokens.numRequests ?? 0),
1516
- completionDetails: {
1517
- reasoning: (expectedTokens.completionDetails?.reasoning || 0) + (outputTokens.completionDetails?.reasoning || 0),
1518
- acceptedPrediction: (expectedTokens.completionDetails?.acceptedPrediction || 0) + (outputTokens.completionDetails?.acceptedPrediction || 0),
1519
- rejectedPrediction: (expectedTokens.completionDetails?.rejectedPrediction || 0) + (outputTokens.completionDetails?.rejectedPrediction || 0)
1520
- }
1521
- };
1522
- }
1523
- function accumulateTokens(target, update) {
1524
- accumulateTokenUsage(target, update);
1525
- }
1526
- async function maybeRemoteSimilarityGrading({ expected, output, threshold, inverse }) {
1527
- if (!state.config?.redteam || !shouldGenerateRemote({ requireEmbeddingProvider: true })) return;
1528
- try {
1529
- return await doRemoteGrading({
1530
- task: "similar",
1531
- expected,
1532
- output,
1533
- threshold,
1534
- inverse
1535
- });
1536
- } catch (error) {
1537
- return fail(`Could not perform remote grading: ${error}`);
1538
- }
1539
- }
1540
- async function computeNativeSimilarity(provider, expected, output, metric) {
1541
- if ("callSimilarityApi" in provider) return computeSimilarityFromNativeProvider(provider, expected, output, metric);
1542
- if ("callEmbeddingApi" in provider) return computeSimilarityFromEmbeddings(provider, expected, output, metric);
1543
- throw new Error("Provider must implement callSimilarityApi or callEmbeddingApi");
1544
- }
1545
- async function computeSimilarityFromNativeProvider(provider, expected, output, metric) {
1546
- const tokensUsed = createMatcherTokenUsage();
1547
- if (metric !== "cosine") return { failure: fail(`Provider ${provider.id()} only supports cosine similarity via callSimilarityApi`, tokensUsed) };
1548
- const similarityResp = await provider.callSimilarityApi(expected, output);
1549
- copySimilarityTokenUsage(tokensUsed, similarityResp);
1550
- if (similarityResp.error) return { failure: fail(similarityResp.error, tokensUsed) };
1551
- if (similarityResp.similarity == null) return { failure: fail("Unknown error fetching similarity", tokensUsed) };
1552
- return {
1553
- similarity: similarityResp.similarity,
1554
- tokensUsed
1555
- };
1556
- }
1557
- async function computeSimilarityFromEmbeddings(provider, expected, output, metric) {
1558
- const expectedEmbedding = await provider.callEmbeddingApi(expected);
1559
- const outputEmbedding = await provider.callEmbeddingApi(output);
1560
- const tokensUsed = combineEmbeddingTokenUsage(expectedEmbedding, outputEmbedding);
1561
- if (expectedEmbedding.error || outputEmbedding.error) return { failure: fail(expectedEmbedding.error || outputEmbedding.error || "Unknown error fetching embeddings", tokensUsed) };
1562
- if (!expectedEmbedding.embedding || !outputEmbedding.embedding) return { failure: fail("Embedding not found", tokensUsed) };
1563
- return {
1564
- similarity: computeSimilarityMetric(expectedEmbedding.embedding, outputEmbedding.embedding, metric),
1565
- tokensUsed
1566
- };
1567
- }
1568
- function computeSimilarityMetric(expectedEmbedding, outputEmbedding, metric) {
1569
- switch (metric) {
1570
- case "cosine": return cosineSimilarity(expectedEmbedding, outputEmbedding);
1571
- case "dot_product": return dotProduct(expectedEmbedding, outputEmbedding);
1572
- case "euclidean": return euclideanDistance(expectedEmbedding, outputEmbedding);
1573
- default: throw new Error(`Unsupported metric: ${metric}`);
1574
- }
1575
- }
1576
- function buildSimilarityResult(similarity, threshold, inverse, metric, tokensUsed) {
1577
- return metric === "euclidean" ? buildDistanceResult(similarity, threshold, inverse, tokensUsed) : buildSimilarityScoreResult(similarity, threshold, inverse, tokensUsed);
1578
- }
1579
- function buildDistanceResult(distance, threshold, inverse, tokensUsed) {
1580
- const pass = inverse ? distance >= threshold - Number.EPSILON : distance <= threshold + Number.EPSILON;
1581
- const normalizedScore = 1 / (1 + distance);
1582
- const belowThresholdReason = `Distance ${distance.toFixed(2)} is less than or equal to threshold ${threshold}`;
1583
- const aboveThresholdReason = `Distance ${distance.toFixed(2)} is greater than threshold ${threshold}`;
1584
- return {
1585
- pass,
1586
- score: inverse ? 1 - normalizedScore : normalizedScore,
1587
- reason: pass === inverse ? aboveThresholdReason : belowThresholdReason,
1588
- tokensUsed
1589
- };
1590
- }
1591
- function buildSimilarityScoreResult(similarity, threshold, inverse, tokensUsed) {
1592
- const pass = inverse ? similarity <= threshold + Number.EPSILON : similarity >= threshold - Number.EPSILON;
1593
- const greaterThanReason = `Similarity ${similarity.toFixed(2)} is greater than or equal to threshold ${threshold}`;
1594
- const lessThanReason = `Similarity ${similarity.toFixed(2)} is less than threshold ${threshold}`;
1595
- return {
1596
- pass,
1597
- score: inverse ? 1 - similarity : similarity,
1598
- reason: pass === inverse ? lessThanReason : greaterThanReason,
1599
- tokensUsed
1600
- };
1601
- }
1602
- async function matchesSimilarity(expected, output, threshold, inverse = false, grading, metric = "cosine") {
1603
- const remoteResult = await maybeRemoteSimilarityGrading({
1604
- expected,
1605
- output,
1606
- threshold,
1607
- inverse
1608
- });
1609
- if (remoteResult) return remoteResult;
1610
- const defaults = await getDefaultProviders();
1611
- const computation = await computeNativeSimilarity(await getAndCheckProvider("embedding", grading?.provider, defaults.embeddingProvider, "similarity check"), expected, output, metric);
1612
- return "failure" in computation ? computation.failure : buildSimilarityResult(computation.similarity, threshold, inverse, metric, computation.tokensUsed);
1613
- }
1614
- /**
1615
- *
1616
- * @param expected Expected classification. If undefined, matches any classification.
1617
- * @param output Text to classify.
1618
- * @param threshold Value between 0 and 1. If the expected classification is undefined, the threshold is the minimum score for any classification. If the expected classification is defined, the threshold is the minimum score for that classification.
1619
- * @param grading
1620
- * @returns Pass if the output matches the classification with a score greater than or equal to the threshold.
1621
- */
1622
- async function matchesClassification(expected, output, threshold, grading) {
1623
- const resp = await (await getAndCheckProvider("classification", grading?.provider, null, "classification check")).callClassificationApi(output);
1624
- if (!resp.classification) return fail(resp.error || "Unknown error fetching classification");
1625
- let score;
1626
- if (expected === void 0) score = Math.max(...Object.values(resp.classification));
1627
- else score = resp.classification[expected] || 0;
1628
- if (score >= threshold - Number.EPSILON) {
1629
- const reason = expected === void 0 ? `Maximum classification score ${score.toFixed(2)} >= ${threshold}` : `Classification ${expected} has score ${score.toFixed(2)} >= ${threshold}`;
1630
- return {
1631
- pass: true,
1632
- score,
1633
- reason
1634
- };
1635
- }
1438
+ function getFactualityScoreLookup(grading) {
1636
1439
  return {
1637
- pass: false,
1638
- score,
1639
- reason: `Classification ${expected} has score ${score.toFixed(2)} < ${threshold}`
1640
- };
1641
- }
1642
- async function loadRubricPrompt(rubricPrompt, defaultPrompt) {
1643
- if (!rubricPrompt || typeof rubricPrompt === "object" && Object.keys(rubricPrompt).length === 0) return defaultPrompt;
1644
- if (typeof rubricPrompt === "string" && rubricPrompt.startsWith("file://")) {
1645
- const basePath = state.basePath || "";
1646
- const { filePath, functionName } = parseFileUrl(getNunjucksEngineForFilePath().renderString(rubricPrompt, {}));
1647
- const resolvedPath = path.resolve(basePath, filePath);
1648
- if (isJavascriptFile(filePath)) rubricPrompt = await loadFromJavaScriptFile(resolvedPath, functionName, []);
1649
- else {
1650
- if (!fs$2.existsSync(resolvedPath)) throw new Error(`File does not exist: ${resolvedPath}`);
1651
- rubricPrompt = fs$2.readFileSync(resolvedPath, "utf8");
1652
- }
1653
- } else rubricPrompt = maybeLoadFromExternalFile(rubricPrompt);
1654
- if (typeof rubricPrompt === "object") rubricPrompt = JSON.stringify(rubricPrompt);
1655
- invariant(typeof rubricPrompt === "string", "rubricPrompt must be a string");
1656
- return rubricPrompt;
1657
- }
1658
- function tryParse(content) {
1659
- try {
1660
- return JSON.parse(content);
1661
- } catch {}
1662
- return content;
1663
- }
1664
- function splitIntoSentences(text) {
1665
- return text.split("\n").filter((sentence) => sentence.trim() !== "");
1666
- }
1667
- function processContextForTemplating(context, enableObjectAccess) {
1668
- if (enableObjectAccess) return context;
1669
- return Object.fromEntries(Object.entries(context).map(([key, value]) => {
1670
- if (value && typeof value === "object") {
1671
- if (Array.isArray(value)) return [key, value.map((item) => item && typeof item === "object" ? JSON.stringify(item) : item)];
1672
- return [key, JSON.stringify(value)];
1673
- }
1674
- return [key, value];
1675
- }));
1440
+ A: grading.factuality?.subset ?? 1,
1441
+ B: grading.factuality?.superset ?? 1,
1442
+ C: grading.factuality?.agree ?? 1,
1443
+ D: grading.factuality?.disagree ?? 0,
1444
+ E: grading.factuality?.differButFactual ?? 1
1445
+ };
1676
1446
  }
1677
- async function renderLlmRubricPrompt(rubricPrompt, context) {
1678
- const processedContext = processContextForTemplating(context, getEnvBool("PROMPTFOO_DISABLE_OBJECT_STRINGIFY", false));
1679
- try {
1680
- const parsed = JSON.parse(rubricPrompt, (_k, v) => typeof v === "string" ? nunjucks.renderString(v, processedContext) : v);
1681
- return JSON.stringify(parsed);
1682
- } catch {}
1683
- return nunjucks.renderString(rubricPrompt, processedContext);
1447
+ function buildFactualityResult(option, reason, grading, resp) {
1448
+ const scoreLookup = getFactualityScoreLookup(grading);
1449
+ const passing = Object.keys(scoreLookup).filter((key) => scoreLookup[key] > 0);
1450
+ const failing = Object.keys(scoreLookup).filter((key) => scoreLookup[key] === 0);
1451
+ const pass = passing.includes(option) && !failing.includes(option);
1452
+ return {
1453
+ pass,
1454
+ score: scoreLookup[option] ?? (pass ? 1 : 0),
1455
+ reason,
1456
+ tokensUsed: normalizeMatcherTokenUsage(resp.tokenUsage)
1457
+ };
1684
1458
  }
1685
- function parseJsonGradingResponse(label, resp) {
1686
- let jsonObjects = [];
1687
- if (typeof resp.output === "string") try {
1688
- jsonObjects = extractJsonObjects(resp.output);
1689
- if (jsonObjects.length === 0) return { failure: fail(`Could not extract JSON from ${label} response`, resp.tokenUsage) };
1459
+ function parseFactualityJsonResponse(responseText) {
1460
+ try {
1461
+ const jsonData = extractFirstJsonObject(responseText);
1462
+ if (!jsonData?.category || typeof jsonData.category !== "string") return;
1463
+ const option = jsonData.category.trim().toUpperCase();
1464
+ if (!/^[A-E]$/.test(option)) throw new Error(`Invalid category value: ${option}`);
1465
+ return {
1466
+ option,
1467
+ reason: jsonData.reason?.trim() || `Category ${option}: ${FACTUALITY_CATEGORY_DESCRIPTIONS[option]}`
1468
+ };
1690
1469
  } catch (err) {
1691
- return { failure: fail(`${label} produced malformed response: ${err}\n\n${resp.output}`, resp.tokenUsage) };
1470
+ const error = err;
1471
+ if (error.message.startsWith("Invalid category value:")) throw error;
1472
+ logger.debug(`JSON parsing failed: ${error.message}`);
1473
+ return;
1692
1474
  }
1693
- else if (typeof resp.output === "object" && resp.output !== null && !Array.isArray(resp.output)) jsonObjects = [resp.output];
1694
- else return { failure: fail(`${label} produced malformed response - output must be string or object. Output: ${JSON.stringify(resp.output)}`, resp.tokenUsage) };
1695
- const parsed = jsonObjects[0];
1696
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return { failure: fail(`${label} produced malformed response. We were not able to parse the response as JSON. Output: ${JSON.stringify(resp.output)}`, resp.tokenUsage) };
1697
- return { parsed };
1698
1475
  }
1699
- async function runJsonGradingPrompt({ assertion, checkName, defaultPrompt, grading, label, providerCallContext, throwOnError, vars }) {
1700
- const prompt = await renderLlmRubricPrompt(await loadRubricPrompt(grading.rubricPrompt, defaultPrompt), vars);
1701
- const defaultProviders = await getDefaultProviders();
1702
- const defaultProvider = defaultProviders.llmRubricProvider || defaultProviders.gradingJsonProvider;
1703
- const resp = await callProviderWithContext(await getAndCheckProvider("text", grading.provider, defaultProvider, checkName), prompt, label, vars, providerCallContext);
1704
- if (resp.error || !resp.output) {
1705
- if (throwOnError) throw new Error(resp.error || "No output");
1706
- return fail(resp.error || "No output", resp.tokenUsage);
1707
- }
1708
- const { parsed, failure } = parseJsonGradingResponse(label, resp);
1709
- if (!parsed) return failure;
1710
- let pass = parsed.pass ?? true;
1711
- if (typeof pass !== "boolean") pass = /^(true|yes|pass|y)$/i.test(String(pass));
1712
- let score = parsed.score;
1713
- if (typeof score !== "number") score = Number.isFinite(Number(score)) ? Number(score) : Number(pass);
1714
- const threshold = typeof assertion?.threshold === "string" ? Number(assertion.threshold) : assertion?.threshold;
1715
- if (typeof threshold === "number" && Number.isFinite(threshold)) pass = pass && score >= threshold;
1716
- const reason = parsed.reason || (pass ? "Grading passed" : `Score ${score} below threshold ${threshold}`);
1717
- let responseMetadata = {};
1718
- if (resp.metadata && typeof resp.metadata === "object" && !Array.isArray(resp.metadata)) {
1719
- const serializedMetadata = safeJsonStringify(resp.metadata);
1720
- responseMetadata = serializedMetadata ? JSON.parse(serializedMetadata) : {};
1721
- }
1476
+ function parseLegacyFactualityResponse(responseText) {
1477
+ const answerMatch = responseText.match(/\s*\(?([a-eA-E])\)/);
1478
+ if (!answerMatch) throw new Error(`Factuality checker output did not match expected format: ${responseText}`);
1479
+ const option = answerMatch[1].toUpperCase();
1480
+ const reasonMatch = responseText.match(/\)\s*(.*)/s);
1722
1481
  return {
1723
- assertion,
1724
- pass,
1725
- score,
1726
- reason,
1727
- tokensUsed: {
1728
- total: resp.tokenUsage?.total || 0,
1729
- prompt: resp.tokenUsage?.prompt || 0,
1730
- completion: resp.tokenUsage?.completion || 0,
1731
- cached: resp.tokenUsage?.cached || 0,
1732
- numRequests: resp.tokenUsage?.numRequests || 0,
1733
- completionDetails: parsed.tokensUsed?.completionDetails || {
1734
- reasoning: 0,
1735
- acceptedPrediction: 0,
1736
- rejectedPrediction: 0
1737
- }
1738
- },
1739
- metadata: {
1740
- ...responseMetadata,
1741
- renderedGradingPrompt: prompt
1742
- }
1482
+ option,
1483
+ reason: reasonMatch?.[1] ? reasonMatch[1].trim() : responseText
1743
1484
  };
1744
1485
  }
1745
1486
  async function matchesLlmRubric(rubric, llmOutput, grading, vars, assertion, options, providerCallContext) {
1746
1487
  if (!grading) throw new Error("Cannot grade output without grading config. Specify --grader option or grading config.");
1747
- if (!grading.rubricPrompt && !state.config?.redteam?.provider && state.config?.redteam && shouldGenerateRemote({ canUseCodexDefaultProvider: true })) return {
1748
- ...await doRemoteGrading({
1749
- task: "llm-rubric",
1750
- rubric,
1751
- output: llmOutput,
1752
- vars: vars || {}
1753
- }),
1754
- assertion
1755
- };
1488
+ const shouldPreferRemote = options?.preferRemote || grading.__promptfooPreferRemote || !grading.provider;
1489
+ if (!grading.rubricPrompt && shouldPreferRemote && !state.config?.redteam?.provider && state.config?.redteam && shouldGenerateRemote({ canUseCodexDefaultProvider: true })) try {
1490
+ return {
1491
+ ...await doRemoteGrading({
1492
+ task: "llm-rubric",
1493
+ rubric,
1494
+ output: llmOutput,
1495
+ vars: vars || {}
1496
+ }),
1497
+ assertion
1498
+ };
1499
+ } catch (error) {
1500
+ return {
1501
+ ...fail(`Could not perform remote grading: ${error}`),
1502
+ assertion
1503
+ };
1504
+ }
1756
1505
  try {
1757
1506
  return await runJsonGradingPrompt({
1758
1507
  assertion,
@@ -1800,89 +1549,42 @@ async function matchesPiScore(renderedValue, llmInput, llmOutput, assertion) {
1800
1549
  assertion
1801
1550
  };
1802
1551
  }
1803
- function isFactualityCategory(category) {
1804
- return /^[A-E]$/.test(category);
1805
- }
1806
- function getFactualityScoreLookup(grading) {
1807
- return {
1808
- A: grading.factuality?.subset ?? 1,
1809
- B: grading.factuality?.superset ?? 1,
1810
- C: grading.factuality?.agree ?? 1,
1811
- D: grading.factuality?.disagree ?? 0,
1812
- E: grading.factuality?.differButFactual ?? 1
1813
- };
1814
- }
1815
- function buildFactualityCategoryResult(category, reason, grading, tokensUsed) {
1816
- const option = category.trim().toUpperCase();
1817
- if (!isFactualityCategory(option)) return fail(`Invalid category value: ${option}`, tokensUsed);
1818
- const score = getFactualityScoreLookup(grading)[option];
1819
- return {
1820
- pass: score > 0,
1821
- score,
1822
- reason: reason?.trim() || `Category ${option}: ${FACTUALITY_CATEGORY_DESCRIPTIONS[option]}`,
1823
- tokensUsed: normalizeTokenUsage(tokensUsed)
1824
- };
1825
- }
1826
- function parseJsonFactualityOutput(output) {
1827
- try {
1828
- const jsonData = extractFirstJsonObject(output);
1829
- return typeof jsonData?.category === "string" ? {
1830
- category: jsonData.category,
1831
- reason: jsonData.reason
1832
- } : null;
1833
- } catch (err) {
1834
- logger.debug(`JSON parsing failed: ${err.message}`);
1835
- return null;
1836
- }
1837
- }
1838
- function parseLegacyFactualityOutput(output) {
1839
- const answerMatch = output.match(/\s*\(?([a-eA-E])\)/);
1840
- if (!answerMatch) return { failure: `Factuality checker output did not match expected format: ${output}` };
1841
- const reasonMatch = output.match(/\)\s*(.*)/s);
1842
- return {
1843
- category: answerMatch[1],
1844
- reason: reasonMatch?.[1]?.trim() || output
1845
- };
1846
- }
1847
- function gradeFactualityOutput(output, grading, tokensUsed) {
1848
- const jsonResult = parseJsonFactualityOutput(output);
1849
- if (jsonResult) return buildFactualityCategoryResult(jsonResult.category, jsonResult.reason, grading, tokensUsed);
1850
- logger.info("Falling back to legacy pattern matching for factuality check");
1851
- const legacyResult = parseLegacyFactualityOutput(output);
1852
- return "failure" in legacyResult ? fail(legacyResult.failure, tokensUsed) : buildFactualityCategoryResult(legacyResult.category, legacyResult.reason, grading, tokensUsed);
1853
- }
1854
1552
  async function matchesFactuality(input, expected, output, grading, vars, providerCallContext) {
1855
1553
  if (!grading) throw new Error("Cannot grade output without grading config. Specify --grader option or grading config.");
1856
- const prompt = await renderLlmRubricPrompt(await loadRubricPrompt(grading?.rubricPrompt, PROMPTFOO_FACTUALITY_PROMPT), {
1857
- input,
1858
- ideal: expected,
1859
- completion: tryParse(output),
1860
- ...vars || {}
1861
- });
1862
- const resp = await callProviderWithContext(await getAndCheckProvider("text", grading.provider, (await getDefaultProviders()).gradingProvider, "factuality check"), prompt, "factuality", {
1554
+ const templateVars = {
1863
1555
  input,
1864
1556
  ideal: expected,
1865
1557
  completion: tryParse(output),
1866
1558
  ...vars || {}
1867
- }, providerCallContext);
1559
+ };
1560
+ const prompt = await renderLlmRubricPrompt(await loadRubricPrompt(grading?.rubricPrompt, PROMPTFOO_FACTUALITY_PROMPT), templateVars);
1561
+ const resp = await callProviderWithContext(await getAndCheckProvider("text", grading.provider, (await getDefaultProviders()).gradingProvider, "factuality check"), prompt, "factuality", templateVars, providerCallContext);
1868
1562
  if (resp.error || !resp.output) return fail(resp.error || "No output", resp.tokenUsage);
1869
1563
  invariant(typeof resp.output === "string", "factuality produced malformed response");
1870
- return gradeFactualityOutput(resp.output, grading, resp.tokenUsage);
1564
+ try {
1565
+ const parsedJson = parseFactualityJsonResponse(resp.output);
1566
+ if (parsedJson) return buildFactualityResult(parsedJson.option, parsedJson.reason, grading, resp);
1567
+ } catch (err) {
1568
+ return fail(err.message, resp.tokenUsage);
1569
+ }
1570
+ logger.info("Falling back to legacy pattern matching for factuality check");
1571
+ try {
1572
+ const parsedLegacy = parseLegacyFactualityResponse(resp.output);
1573
+ return buildFactualityResult(parsedLegacy.option, parsedLegacy.reason, grading, resp);
1574
+ } catch (err) {
1575
+ return fail(err.message, resp.tokenUsage);
1576
+ }
1871
1577
  }
1872
1578
  async function matchesClosedQa(input, expected, output, grading, vars, providerCallContext) {
1873
1579
  if (!grading) throw new Error("Cannot grade output without grading config. Specify --grader option or grading config.");
1874
- const prompt = await renderLlmRubricPrompt(await loadRubricPrompt(grading?.rubricPrompt, OPENAI_CLOSED_QA_PROMPT), {
1875
- input,
1876
- criteria: expected,
1877
- completion: tryParse(output),
1878
- ...vars || {}
1879
- });
1880
- const resp = await callProviderWithContext(await getAndCheckProvider("text", grading.provider, (await getDefaultProviders()).gradingProvider, "model-graded-closedqa check"), prompt, "model-graded-closedqa", {
1580
+ const templateVars = {
1881
1581
  input,
1882
1582
  criteria: expected,
1883
1583
  completion: tryParse(output),
1884
1584
  ...vars || {}
1885
- }, providerCallContext);
1585
+ };
1586
+ const prompt = await renderLlmRubricPrompt(await loadRubricPrompt(grading?.rubricPrompt, OPENAI_CLOSED_QA_PROMPT), templateVars);
1587
+ const resp = await callProviderWithContext(await getAndCheckProvider("text", grading.provider, (await getDefaultProviders()).gradingProvider, "model-graded-closedqa check"), prompt, "model-graded-closedqa", templateVars, providerCallContext);
1886
1588
  if (resp.error || !resp.output) return fail(resp.error || "No output", resp.tokenUsage);
1887
1589
  invariant(typeof resp.output === "string", "model-graded-closedqa produced malformed response");
1888
1590
  try {
@@ -1895,18 +1597,7 @@ async function matchesClosedQa(input, expected, output, grading, vars, providerC
1895
1597
  pass,
1896
1598
  score: pass ? 1 : 0,
1897
1599
  reason,
1898
- tokensUsed: {
1899
- total: resp.tokenUsage?.total || 0,
1900
- prompt: resp.tokenUsage?.prompt || 0,
1901
- completion: resp.tokenUsage?.completion || 0,
1902
- cached: resp.tokenUsage?.cached || 0,
1903
- numRequests: resp.tokenUsage?.numRequests || 0,
1904
- completionDetails: resp.tokenUsage?.completionDetails || {
1905
- reasoning: 0,
1906
- acceptedPrediction: 0,
1907
- rejectedPrediction: 0
1908
- }
1909
- }
1600
+ tokensUsed: normalizeMatcherTokenUsage(resp.tokenUsage)
1910
1601
  };
1911
1602
  } catch (err) {
1912
1603
  return fail(`Error parsing output: ${err.message}`, resp.tokenUsage);
@@ -1916,490 +1607,51 @@ async function matchesGEval(criteria, input, output, threshold, grading, provide
1916
1607
  if (!input) throw Error("No source text to estimate reply");
1917
1608
  const maxScore = 10;
1918
1609
  const textProvider = await getAndCheckProvider("text", grading?.provider, (await getDefaultProviders()).gradingProvider, "reply geval check");
1919
- const tokensUsed = {
1920
- total: 0,
1921
- prompt: 0,
1922
- completion: 0,
1923
- cached: 0,
1924
- numRequests: 0,
1925
- completionDetails: {
1926
- reasoning: 0,
1927
- acceptedPrediction: 0,
1928
- rejectedPrediction: 0
1929
- }
1930
- };
1610
+ const tokensUsed = normalizeMatcherTokenUsage(void 0);
1931
1611
  const respSteps = await callProviderWithContext(textProvider, await renderLlmRubricPrompt(await loadRubricPrompt(typeof grading?.rubricPrompt === "object" && !Array.isArray(grading?.rubricPrompt) ? grading?.rubricPrompt?.["steps"] : void 0, GEVAL_PROMPT_STEPS), { criteria }), "g-eval-steps", { criteria }, providerCallContext);
1932
- accumulateTokens(tokensUsed, respSteps.tokenUsage);
1612
+ accumulateTokenUsage(tokensUsed, respSteps.tokenUsage);
1613
+ if (respSteps.error) return fail(respSteps.error, tokensUsed);
1614
+ if (!respSteps.output) return fail("No output", tokensUsed);
1615
+ if (typeof respSteps.output !== "string") return fail("LLM-proposed evaluation steps response is not a string", tokensUsed);
1933
1616
  let steps;
1934
1617
  try {
1935
- steps = JSON.parse(respSteps.output.match(/\{"steps".+\}/g)[0]).steps;
1618
+ const stepsMatch = respSteps.output.match(/\{"steps".+\}/g);
1619
+ if (!stepsMatch) return fail(`LLM-proposed evaluation steps are not in JSON format: ${respSteps.output}`, tokensUsed);
1620
+ steps = JSON.parse(stepsMatch[0]).steps;
1936
1621
  if (!steps.length) return fail("LLM does not propose any evaluation step", tokensUsed);
1937
- } catch {
1938
- return fail(`LLM-proposed evaluation steps are not in JSON format: ${respSteps.output}`, tokensUsed);
1622
+ } catch (err) {
1623
+ return fail(`LLM-proposed evaluation steps are not in JSON format: ${err.message}\n\n${respSteps.output}`, tokensUsed);
1939
1624
  }
1940
- const resp = await callProviderWithContext(textProvider, await renderLlmRubricPrompt(await loadRubricPrompt(typeof grading?.rubricPrompt === "object" && !Array.isArray(grading?.rubricPrompt) ? grading?.rubricPrompt?.["evaluate"] : void 0, GEVAL_PROMPT_EVALUATE), {
1941
- criteria,
1942
- steps: steps.join("\n- "),
1943
- maxScore: maxScore.toString(),
1944
- input: tryParse(input),
1945
- output: tryParse(output)
1946
- }), "g-eval", {
1625
+ const evalPrompt = await loadRubricPrompt(typeof grading?.rubricPrompt === "object" && !Array.isArray(grading?.rubricPrompt) ? grading?.rubricPrompt?.["evaluate"] : void 0, GEVAL_PROMPT_EVALUATE);
1626
+ const evalVars = {
1947
1627
  criteria,
1948
1628
  steps: steps.join("\n- "),
1949
1629
  maxScore: maxScore.toString(),
1950
1630
  input: tryParse(input),
1951
1631
  output: tryParse(output)
1952
- }, providerCallContext);
1953
- accumulateTokens(tokensUsed, resp.tokenUsage);
1632
+ };
1633
+ const resp = await callProviderWithContext(textProvider, await renderLlmRubricPrompt(evalPrompt, evalVars), "g-eval", evalVars, providerCallContext);
1634
+ accumulateTokenUsage(tokensUsed, resp.tokenUsage);
1635
+ if (resp.error) return fail(resp.error, tokensUsed);
1636
+ if (!resp.output) return fail("No output", tokensUsed);
1637
+ if (typeof resp.output !== "string") return fail("LLM-proposed evaluation result response is not a string", tokensUsed);
1954
1638
  let result;
1955
1639
  try {
1956
- result = JSON.parse(resp.output.match(/\{.+\}/g)[0]);
1957
- } catch {
1958
- return fail(`LLM-proposed evaluation result is not in JSON format: ${resp.output}`, tokensUsed);
1640
+ const resultMatch = resp.output.match(/\{.+\}/g);
1641
+ if (!resultMatch) return fail(`LLM-proposed evaluation result is not in JSON format: ${resp.output}`, tokensUsed);
1642
+ result = JSON.parse(resultMatch[0]);
1643
+ } catch (err) {
1644
+ return fail(`LLM-proposed evaluation result is not in JSON format: ${err.message}\n\n${resp.output}`, tokensUsed);
1959
1645
  }
1646
+ const rawScore = typeof result.score === "number" ? result.score : Number(result.score);
1647
+ if (!Number.isFinite(rawScore)) return fail(`G-Eval result has invalid or missing score: ${JSON.stringify(result.score)}`, tokensUsed);
1960
1648
  return {
1961
- pass: result.score / maxScore >= threshold,
1962
- score: result.score / maxScore,
1649
+ pass: rawScore / maxScore >= threshold,
1650
+ score: rawScore / maxScore,
1963
1651
  reason: result.reason,
1964
1652
  tokensUsed
1965
1653
  };
1966
1654
  }
1967
- async function matchesAnswerRelevance(input, output, threshold, grading, providerCallContext) {
1968
- const embeddingProvider = await getAndCheckProvider("embedding", grading?.provider, (await getDefaultProviders()).embeddingProvider, "answer relevancy check");
1969
- const textProvider = await getAndCheckProvider("text", grading?.provider, (await getDefaultProviders()).gradingProvider, "answer relevancy check");
1970
- const tokensUsed = {
1971
- total: 0,
1972
- prompt: 0,
1973
- completion: 0,
1974
- cached: 0,
1975
- numRequests: 0,
1976
- completionDetails: {
1977
- reasoning: 0,
1978
- acceptedPrediction: 0,
1979
- rejectedPrediction: 0
1980
- }
1981
- };
1982
- const candidateQuestions = [];
1983
- for (let i = 0; i < 3; i++) {
1984
- const resp = await callProviderWithContext(textProvider, await renderLlmRubricPrompt(await loadRubricPrompt(grading?.rubricPrompt, ANSWER_RELEVANCY_GENERATE), { answer: tryParse(output) }), "answer-relevance", { answer: tryParse(output) }, providerCallContext);
1985
- accumulateTokens(tokensUsed, resp.tokenUsage);
1986
- if (resp.error || !resp.output) return fail(resp.error || "No output", tokensUsed);
1987
- invariant(typeof resp.output === "string", "answer relevancy check produced malformed response");
1988
- candidateQuestions.push(resp.output);
1989
- }
1990
- invariant(typeof embeddingProvider.callEmbeddingApi === "function", `Provider ${embeddingProvider.id} must implement callEmbeddingApi for similarity check`);
1991
- const inputEmbeddingResp = await embeddingProvider.callEmbeddingApi(input);
1992
- accumulateTokens(tokensUsed, inputEmbeddingResp.tokenUsage);
1993
- if (inputEmbeddingResp.error || !inputEmbeddingResp.embedding) return fail(inputEmbeddingResp.error || "No embedding", tokensUsed);
1994
- const inputEmbedding = inputEmbeddingResp.embedding;
1995
- const similarities = [];
1996
- const questionsWithScores = [];
1997
- for (const question of candidateQuestions) {
1998
- const resp = await embeddingProvider.callEmbeddingApi(question);
1999
- accumulateTokens(tokensUsed, resp.tokenUsage);
2000
- if (resp.error || !resp.embedding) return fail(resp.error || "No embedding", tokensUsed);
2001
- const questionSimilarity = cosineSimilarity(inputEmbedding, resp.embedding);
2002
- similarities.push(questionSimilarity);
2003
- questionsWithScores.push({
2004
- question,
2005
- similarity: questionSimilarity
2006
- });
2007
- }
2008
- const similarity = similarities.reduce((a, b) => a + b, 0) / similarities.length;
2009
- const pass = similarity >= threshold - Number.EPSILON;
2010
- const greaterThanReason = `Relevance ${similarity.toFixed(2)} is greater than threshold ${threshold}`;
2011
- const lessThanReason = `Relevance ${similarity.toFixed(2)} is less than threshold ${threshold}`;
2012
- const metadata = {
2013
- generatedQuestions: questionsWithScores,
2014
- averageSimilarity: similarity,
2015
- threshold
2016
- };
2017
- if (pass) return {
2018
- pass: true,
2019
- score: similarity,
2020
- reason: greaterThanReason,
2021
- tokensUsed,
2022
- metadata
2023
- };
2024
- return {
2025
- pass: false,
2026
- score: similarity,
2027
- reason: lessThanReason,
2028
- tokensUsed,
2029
- metadata
2030
- };
2031
- }
2032
- async function matchesContextRecall(context, groundTruth, threshold, grading, vars, providerCallContext) {
2033
- const textProvider = await getAndCheckProvider("text", grading?.provider, (await getDefaultProviders()).gradingProvider, "context recall check");
2034
- const contextString = serializeContext(context);
2035
- const resp = await callProviderWithContext(textProvider, await renderLlmRubricPrompt(await loadRubricPrompt(grading?.rubricPrompt, CONTEXT_RECALL), {
2036
- context: contextString,
2037
- groundTruth,
2038
- ...vars || {}
2039
- }), "context-recall", {
2040
- context: contextString,
2041
- groundTruth,
2042
- ...vars || {}
2043
- }, providerCallContext);
2044
- if (resp.error || !resp.output) return fail(resp.error || "No output", resp.tokenUsage);
2045
- invariant(typeof resp.output === "string", "context-recall produced malformed response");
2046
- const attributedTokenLower = CONTEXT_RECALL_ATTRIBUTED_TOKEN.toLowerCase();
2047
- const notAttributedTokenLower = CONTEXT_RECALL_NOT_ATTRIBUTED_TOKEN.toLowerCase();
2048
- const sentences = splitIntoSentences(resp.output).filter((line) => {
2049
- const lowerLine = line.toLowerCase();
2050
- return lowerLine.includes(attributedTokenLower) || lowerLine.includes(notAttributedTokenLower);
2051
- });
2052
- const sentenceAttributions = [];
2053
- let numerator = 0;
2054
- for (const sentence of sentences) {
2055
- const isAttributed = sentence.toLowerCase().includes(attributedTokenLower);
2056
- if (isAttributed) numerator++;
2057
- const sentenceMatch = sentence.match(/^\d+\.\s*([^\.]+\.)/);
2058
- const cleanSentence = sentenceMatch ? sentenceMatch[1].trim() : sentence.split(".")[0].trim();
2059
- sentenceAttributions.push({
2060
- sentence: cleanSentence,
2061
- attributed: isAttributed
2062
- });
2063
- }
2064
- const score = sentences.length > 0 ? numerator / sentences.length : 0;
2065
- const pass = score >= threshold - Number.EPSILON;
2066
- const metadata = {
2067
- sentenceAttributions,
2068
- totalSentences: sentences.length,
2069
- attributedSentences: numerator,
2070
- score
2071
- };
2072
- return {
2073
- pass,
2074
- score,
2075
- reason: pass ? `Recall ${score.toFixed(2)} is >= ${threshold}` : `Recall ${score.toFixed(2)} is < ${threshold}`,
2076
- tokensUsed: {
2077
- total: resp.tokenUsage?.total || 0,
2078
- prompt: resp.tokenUsage?.prompt || 0,
2079
- completion: resp.tokenUsage?.completion || 0,
2080
- cached: resp.tokenUsage?.cached || 0,
2081
- numRequests: resp.tokenUsage?.numRequests || 0,
2082
- completionDetails: resp.tokenUsage?.completionDetails || {
2083
- reasoning: 0,
2084
- acceptedPrediction: 0,
2085
- rejectedPrediction: 0
2086
- }
2087
- },
2088
- metadata
2089
- };
2090
- }
2091
- async function matchesContextRelevance(question, context, threshold, grading, providerCallContext) {
2092
- const textProvider = await getAndCheckProvider("text", grading?.provider, (await getDefaultProviders()).gradingProvider, "context relevance check");
2093
- const contextString = serializeContext(context);
2094
- const resp = await callProviderWithContext(textProvider, await renderLlmRubricPrompt(await loadRubricPrompt(grading?.rubricPrompt, CONTEXT_RELEVANCE), {
2095
- context: contextString,
2096
- query: question
2097
- }), "context-relevance", {
2098
- context: contextString,
2099
- query: question
2100
- }, providerCallContext);
2101
- if (resp.error || !resp.output) return fail(resp.error || "No output", resp.tokenUsage);
2102
- invariant(typeof resp.output === "string", "context-relevance produced malformed response");
2103
- const contextUnits = Array.isArray(context) ? context.filter((chunk) => chunk.trim().length > 0) : splitIntoSentences(context);
2104
- const totalContextUnits = contextUnits.length;
2105
- const extractedSentences = splitIntoSentences(resp.output);
2106
- const relevantSentences = [];
2107
- const insufficientInformation = resp.output.includes(CONTEXT_RELEVANCE_BAD);
2108
- let numerator = 0;
2109
- if (insufficientInformation) numerator = 0;
2110
- else {
2111
- numerator = extractedSentences.length;
2112
- relevantSentences.push(...extractedSentences);
2113
- }
2114
- const score = totalContextUnits > 0 ? numerator / totalContextUnits : 0;
2115
- const pass = score >= threshold - Number.EPSILON;
2116
- const metadata = {
2117
- extractedSentences: relevantSentences,
2118
- totalContextUnits,
2119
- totalContextSentences: totalContextUnits,
2120
- contextUnits,
2121
- relevantSentenceCount: numerator,
2122
- insufficientInformation,
2123
- score
2124
- };
2125
- return {
2126
- pass,
2127
- score,
2128
- reason: pass ? `Context relevance ${score.toFixed(2)} is >= ${threshold}` : `Context relevance ${score.toFixed(2)} is < ${threshold}`,
2129
- tokensUsed: {
2130
- total: resp.tokenUsage?.total || 0,
2131
- prompt: resp.tokenUsage?.prompt || 0,
2132
- completion: resp.tokenUsage?.completion || 0,
2133
- cached: resp.tokenUsage?.cached || 0,
2134
- numRequests: resp.tokenUsage?.numRequests || 0,
2135
- completionDetails: resp.tokenUsage?.completionDetails || {
2136
- reasoning: 0,
2137
- acceptedPrediction: 0,
2138
- rejectedPrediction: 0
2139
- }
2140
- },
2141
- metadata
2142
- };
2143
- }
2144
- async function matchesContextFaithfulness(query, output, context, threshold, grading, vars, providerCallContext) {
2145
- const textProvider = await getAndCheckProvider("text", grading?.provider, (await getDefaultProviders()).gradingProvider, "faithfulness check");
2146
- const tokensUsed = {
2147
- total: 0,
2148
- prompt: 0,
2149
- completion: 0,
2150
- cached: 0,
2151
- numRequests: 0,
2152
- completionDetails: {
2153
- reasoning: 0,
2154
- acceptedPrediction: 0,
2155
- rejectedPrediction: 0
2156
- }
2157
- };
2158
- if (grading?.rubricPrompt) invariant(Array.isArray(grading.rubricPrompt), "rubricPrompt must be an array");
2159
- const rawLongformPrompt = typeof grading?.rubricPrompt?.[0] === "string" ? grading?.rubricPrompt?.[0] : grading?.rubricPrompt?.[0]?.content;
2160
- const rawNliPrompt = typeof grading?.rubricPrompt?.[1] === "string" ? grading?.rubricPrompt?.[1] : grading?.rubricPrompt?.[1]?.content;
2161
- const longformPrompt = await loadRubricPrompt(rawLongformPrompt, CONTEXT_FAITHFULNESS_LONGFORM);
2162
- const nliPrompt = await loadRubricPrompt(rawNliPrompt, CONTEXT_FAITHFULNESS_NLI_STATEMENTS);
2163
- let promptText = await renderLlmRubricPrompt(longformPrompt, {
2164
- question: query,
2165
- answer: tryParse(output),
2166
- ...vars || {}
2167
- });
2168
- let resp = await callProviderWithContext(textProvider, promptText, "context-faithfulness-longform", {
2169
- question: query,
2170
- answer: tryParse(output),
2171
- ...vars || {}
2172
- }, providerCallContext);
2173
- accumulateTokens(tokensUsed, resp.tokenUsage);
2174
- if (resp.error || !resp.output) return fail(resp.error || "No output", tokensUsed);
2175
- invariant(typeof resp.output === "string", "context-faithfulness produced malformed response");
2176
- const contextString = serializeContext(context);
2177
- const statements = splitIntoSentences(resp.output);
2178
- promptText = await renderLlmRubricPrompt(nliPrompt, {
2179
- context: contextString,
2180
- statements,
2181
- ...vars || {}
2182
- });
2183
- resp = await callProviderWithContext(textProvider, promptText, "context-faithfulness-nli", {
2184
- context: contextString,
2185
- statements,
2186
- ...vars || {}
2187
- }, providerCallContext);
2188
- accumulateTokens(tokensUsed, resp.tokenUsage);
2189
- if (resp.error || !resp.output) return fail(resp.error || "No output", tokensUsed);
2190
- invariant(typeof resp.output === "string", "context-faithfulness produced malformed response");
2191
- let finalAnswer = "Final verdict for each statement in order:";
2192
- finalAnswer = finalAnswer.toLowerCase();
2193
- let verdicts = resp.output.toLowerCase().trim();
2194
- let score = 0;
2195
- if (statements.length > 0) if (verdicts.includes(finalAnswer)) {
2196
- verdicts = verdicts.slice(verdicts.indexOf(finalAnswer) + finalAnswer.length);
2197
- const parsedVerdicts = verdicts.split(".").filter((answer) => answer.trim() !== "");
2198
- if (parsedVerdicts.length > 0) score = 1 - parsedVerdicts.filter((answer) => !answer.includes("yes")).length / statements.length;
2199
- } else {
2200
- const noVerdictCount = verdicts.split("verdict: no").length - 1;
2201
- if (noVerdictCount + (verdicts.split("verdict: yes").length - 1) > 0) score = 1 - noVerdictCount / statements.length;
2202
- }
2203
- score = Math.min(1, Math.max(0, score));
2204
- const pass = score >= threshold - Number.EPSILON;
2205
- return {
2206
- pass,
2207
- score,
2208
- reason: pass ? `Faithfulness ${score.toFixed(2)} is >= ${threshold}` : `Faithfulness ${score.toFixed(2)} is < ${threshold}`,
2209
- tokensUsed
2210
- };
2211
- }
2212
- async function matchesSelectBest(criteria, outputs, grading, vars, providerCallContext) {
2213
- invariant(outputs.length >= 2, "select-best assertion must have at least two outputs to compare between");
2214
- const resp = await callProviderWithContext(await getAndCheckProvider("text", grading?.provider, (await getDefaultProviders()).gradingProvider, "select-best check"), await renderLlmRubricPrompt(await loadRubricPrompt(grading?.rubricPrompt, SELECT_BEST_PROMPT), {
2215
- criteria,
2216
- outputs: outputs.map((o) => tryParse(o)),
2217
- ...vars || {}
2218
- }), "select-best", {
2219
- criteria,
2220
- outputs: outputs.map((o) => tryParse(o)),
2221
- ...vars || {}
2222
- }, providerCallContext);
2223
- if (resp.error || !resp.output) return new Array(outputs.length).fill(fail(resp.error || "No output", resp.tokenUsage));
2224
- invariant(typeof resp.output === "string", "select-best produced malformed response");
2225
- const firstDigitMatch = resp.output.trim().match(/\d/);
2226
- const verdict = firstDigitMatch ? Number.parseInt(firstDigitMatch[0], 10) : NaN;
2227
- if (Number.isNaN(verdict) || verdict < 0 || verdict >= outputs.length) return new Array(outputs.length).fill(fail(`Invalid select-best verdict: ${verdict}`));
2228
- const tokensUsed = {
2229
- total: resp.tokenUsage?.total || 0,
2230
- prompt: resp.tokenUsage?.prompt || 0,
2231
- completion: resp.tokenUsage?.completion || 0,
2232
- cached: resp.tokenUsage?.cached || 0,
2233
- numRequests: resp.tokenUsage?.numRequests || 0,
2234
- completionDetails: resp.tokenUsage?.completionDetails || {
2235
- reasoning: 0,
2236
- acceptedPrediction: 0,
2237
- rejectedPrediction: 0
2238
- }
2239
- };
2240
- return outputs.map((_output, index) => {
2241
- if (index === verdict) return {
2242
- pass: true,
2243
- score: 1,
2244
- reason: `Output selected as the best: ${criteria}`,
2245
- tokensUsed
2246
- };
2247
- else return {
2248
- pass: false,
2249
- score: 0,
2250
- reason: `Output not selected: ${criteria}`,
2251
- tokensUsed
2252
- };
2253
- });
2254
- }
2255
- async function selectMaxScore(outputs, resultsWithGradingResults, assertion) {
2256
- invariant(outputs.length >= 2, "max-score assertion must have at least two outputs to compare between");
2257
- const value = assertion.value || {};
2258
- const options = {
2259
- method: typeof value === "object" && "method" in value ? value.method : "average",
2260
- weights: typeof value === "object" && "weights" in value ? value.weights : {},
2261
- threshold: typeof value === "object" && "threshold" in value ? value.threshold : void 0
2262
- };
2263
- const scores = resultsWithGradingResults.map((result, index) => {
2264
- const relevantResults = (result.gradingResult?.componentResults || []).filter((r) => r.assertion && r.assertion.type !== "max-score" && r.assertion.type !== "select-best");
2265
- if (relevantResults.length === 0) throw new Error("max-score requires at least one other assertion (besides max-score or select-best) to aggregate scores from");
2266
- let totalWeightedScore = 0;
2267
- let totalWeight = 0;
2268
- relevantResults.forEach((componentResult) => {
2269
- const assertionType = componentResult.assertion?.type || "unknown";
2270
- const weight = options.weights[assertionType] === void 0 ? 1 : options.weights[assertionType];
2271
- const score = componentResult.score || 0;
2272
- totalWeightedScore += score * weight;
2273
- totalWeight += weight;
2274
- });
2275
- let aggregateScore;
2276
- if (options.method === "sum") aggregateScore = totalWeightedScore;
2277
- else aggregateScore = totalWeight > 0 ? totalWeightedScore / totalWeight : 0;
2278
- return {
2279
- index,
2280
- score: aggregateScore,
2281
- componentCount: relevantResults.length,
2282
- totalWeight
2283
- };
2284
- });
2285
- let maxScore = -Infinity;
2286
- let winnerIndex = 0;
2287
- for (let i = 0; i < scores.length; i++) if (scores[i].score > maxScore) {
2288
- maxScore = scores[i].score;
2289
- winnerIndex = i;
2290
- }
2291
- const meetsThreshold = options.threshold === void 0 || maxScore >= options.threshold;
2292
- return scores.map(({ index, score, componentCount, totalWeight }) => {
2293
- const isWinner = index === winnerIndex && meetsThreshold;
2294
- return {
2295
- pass: isWinner,
2296
- score: isWinner ? 1 : 0,
2297
- reason: isWinner ? `Selected as highest scoring output (score: ${score.toFixed(3)})` : score === maxScore && !meetsThreshold ? `Not selected - score ${score.toFixed(3)} below threshold ${options.threshold}` : `Not selected (score: ${score.toFixed(3)}, max: ${maxScore.toFixed(3)})`,
2298
- namedScores: {
2299
- maxScore: score,
2300
- assertionCount: componentCount,
2301
- totalWeight
2302
- }
2303
- };
2304
- });
2305
- }
2306
- async function matchesSearchRubric(rubric, llmOutput, grading, vars, assertion, _provider, providerCallContext) {
2307
- if (!grading) throw new Error("Cannot grade output without grading config. Specify --grader option or grading config.");
2308
- const defaultProviders = await getDefaultProviders();
2309
- const defaultSearchProviders = [
2310
- defaultProviders.webSearchProvider,
2311
- defaultProviders.llmRubricProvider,
2312
- defaultProviders.gradingProvider
2313
- ];
2314
- let searchProvider = (grading.provider ? await getGradingProvider("text", grading.provider, null) : null) || defaultSearchProviders.find((provider) => Boolean(provider));
2315
- if (!hasWebSearchCapability(searchProvider)) {
2316
- const webSearchDefault = defaultSearchProviders.find((provider) => hasWebSearchCapability(provider));
2317
- if (webSearchDefault) searchProvider = webSearchDefault;
2318
- }
2319
- if (!hasWebSearchCapability(searchProvider)) {
2320
- const webSearchProvider = await loadWebSearchProvider(true);
2321
- if (webSearchProvider) searchProvider = webSearchProvider;
2322
- }
2323
- if (!searchProvider || !hasWebSearchCapability(searchProvider)) throw new Error("search-rubric assertion requires a grading provider with web search capabilities. Use --grader with a web search provider (e.g., anthropic:messages:claude-sonnet-4, openai:responses:o4-mini with tools configured, perplexity:sonar) or configure one in defaultTest.options.provider");
2324
- const prompt = await renderLlmRubricPrompt(await loadRubricPrompt(grading?.rubricPrompt, DEFAULT_WEB_SEARCH_PROMPT), {
2325
- output: tryParse(llmOutput),
2326
- rubric,
2327
- ...vars || {}
2328
- });
2329
- const resp = await callProviderWithContext(searchProvider, prompt, "search-rubric", {
2330
- output: tryParse(llmOutput),
2331
- rubric,
2332
- ...vars || {}
2333
- }, providerCallContext);
2334
- if (resp.error || !resp.output) return {
2335
- pass: false,
2336
- score: 0,
2337
- reason: `Search rubric evaluation failed: ${resp.error || "No output"}`,
2338
- tokensUsed: resp.tokenUsage,
2339
- assertion
2340
- };
2341
- try {
2342
- const result = extractFirstJsonObject(String(resp.output));
2343
- let pass = result.pass ?? false;
2344
- const score = typeof result.score === "number" ? result.score : pass ? 1 : 0;
2345
- if (assertion?.threshold !== void 0) pass = pass && score >= assertion.threshold;
2346
- return {
2347
- pass,
2348
- score,
2349
- reason: result.reason || "No reason provided",
2350
- tokensUsed: resp.tokenUsage,
2351
- assertion,
2352
- metadata: {
2353
- searchResults: result.searchResults || [],
2354
- searchProvider: searchProvider.id()
2355
- }
2356
- };
2357
- } catch {
2358
- const outputLower = String(resp.output).toLowerCase();
2359
- const pass = outputLower.includes("\"pass\":true") || outputLower.includes("\"pass\": true");
2360
- return {
2361
- pass,
2362
- score: pass ? 1 : 0,
2363
- reason: resp.output,
2364
- tokensUsed: resp.tokenUsage,
2365
- assertion
2366
- };
2367
- }
2368
- }
2369
- async function matchesModeration({ userPrompt, assistantResponse, categories = [] }, grading) {
2370
- if (!assistantResponse) return {
2371
- pass: true,
2372
- score: 1,
2373
- reason: "No output to moderate"
2374
- };
2375
- const defaultProviders = await getDefaultProviders();
2376
- const defaultModerationProvider = !getEnvString("OPENAI_API_KEY") && (getEnvString("REPLICATE_API_KEY") || getEnvString("REPLICATE_API_TOKEN")) ? await loadApiProvider(LLAMA_GUARD_REPLICATE_PROVIDER) : defaultProviders.moderationProvider;
2377
- const moderationProvider = await getAndCheckProvider("moderation", grading?.provider, defaultModerationProvider, "moderation check");
2378
- invariant(moderationProvider, "Moderation provider must be defined");
2379
- const resp = await moderationProvider.callModerationApi(userPrompt, assistantResponse);
2380
- if (resp.error) return {
2381
- pass: false,
2382
- score: 0,
2383
- reason: `Moderation API error: ${resp.error}`
2384
- };
2385
- const { flags } = resp;
2386
- if (!flags || flags.length === 0) return {
2387
- pass: true,
2388
- score: 1,
2389
- reason: "No moderation flags detected"
2390
- };
2391
- const filteredFlags = categories.length === 0 ? flags : flags.filter((flag) => categories.includes(flag.code));
2392
- if (filteredFlags.length > 0) return {
2393
- pass: false,
2394
- score: 0,
2395
- reason: `Moderation flags detected: ${filteredFlags.map((flag) => flag.description).join(", ")}`
2396
- };
2397
- return {
2398
- pass: true,
2399
- score: 1,
2400
- reason: "No relevant moderation flags detected"
2401
- };
2402
- }
2403
1655
  //#endregion
2404
1656
  //#region src/integrations/huggingfaceDatasets.ts
2405
1657
  /**
@@ -2985,7 +2237,7 @@ var RedteamPluginBase = class RedteamPluginBase {
2985
2237
  const rejectedPromptLengths = [];
2986
2238
  let rejectedPromptLimit;
2987
2239
  for (const prompt of parsedPrompts) {
2988
- const violation = getGeneratedPromptOverLimit("__prompt" in prompt ? String(prompt.__prompt) : JSON.stringify(prompt), this.config.maxCharsPerMessage);
2240
+ const violation = getGeneratedPromptOverLimit("__prompt" in prompt ? prompt.__prompt : JSON.stringify(prompt), this.config.maxCharsPerMessage);
2989
2241
  if (violation) {
2990
2242
  rejectedPromptLengths.push(violation.length);
2991
2243
  rejectedPromptLimit = violation.limit;
@@ -3149,10 +2401,17 @@ var RedteamGraderBase = class {
3149
2401
  },
3150
2402
  rubric: finalRubric
3151
2403
  };
3152
- const grade = await matchesLlmRubric(finalRubric, llmOutput, {
2404
+ const defaultTest = typeof state.config?.defaultTest === "object" ? state.config.defaultTest : void 0;
2405
+ const hasConfiguredGradingProvider = Boolean(state.config?.redteam?.provider || defaultTest?.options?.provider);
2406
+ const grading = {
3153
2407
  ...test.options,
3154
2408
  provider: await redteamProviderManager.getGradingProvider({ jsonOnly: true })
3155
- });
2409
+ };
2410
+ if (!hasConfiguredGradingProvider) {
2411
+ Object.defineProperty(grading, "__promptfooPreferRemote", { value: true });
2412
+ logger.debug("[Redteam] No configured grading provider detected, preferring remote grading");
2413
+ }
2414
+ const grade = await matchesLlmRubric(finalRubric, llmOutput, grading);
3156
2415
  logger.debug(`Redteam grading result for ${this.id}: - ${JSON.stringify(grade)}`);
3157
2416
  let suggestions;
3158
2417
  if (!grade.pass) suggestions = this.getSuggestions({
@@ -15971,6 +15230,6 @@ function getGraderById(id) {
15971
15230
  return grader;
15972
15231
  }
15973
15232
  //#endregion
15974
- export { matchesGEval as $, DivergentRepetitionPlugin as A, sampleArray as B, getPiiLeakTestsForCategory as C, HarmbenchPlugin as D, ImitationPlugin as E, AegisPlugin as F, loadRubricPrompt as G, callProviderWithContext as H, RedteamGraderBase as I, matchesClosedQa as J, matchesAnswerRelevance as K, RedteamPluginBase as L, CrossSessionLeakPlugin as M, ContractPlugin as N, HallucinationPlugin as O, BeavertailsPlugin as P, matchesFactuality as Q, getCustomPolicies as R, PlinyPlugin as S, IntentPlugin as T, fail as U, fetchHuggingFaceDataset as V, getAndCheckProvider as W, matchesContextRecall as X, matchesContextFaithfulness as Y, matchesContextRelevance as Z, PoliticsPlugin as _, loadFromJavaScriptFile as _t, UnverifiableClaimsPlugin as a, matchesSimilarity as at, isValidPolicyObject as b, ToolDiscoveryPlugin as c, withProviderCallExecutionContext as ct, TeenSafetyDangerousContentPlugin as d, processPrompts as dt, matchesLlmRubric as et, TeenSafetyAgeRestrictedGoodsAndServicesPlugin as f, readPrompts as ft, PromptExtractionPlugin as g, getFinalTest as gt, RbacPlugin as h, coerceString as ht, VLGuardPlugin as i, matchesSelectBest as it, DebugAccessPlugin as j, ExcessiveAgencyPlugin as k, TeenSafetyHarmfulBodyIdealsPlugin as l, doRemoteGrading as lt, ShellInjectionPlugin as m, SUGGEST_PROMPTS_SYSTEM_MESSAGE as mt, getGraderById as n, matchesPiScore as nt, UnsafeBenchPlugin as o, matchesTrajectoryGoalSuccess as ot, SqlInjectionPlugin as p, readProviderPromptMap as pt, matchesClassification as q, VLSUPlugin as r, matchesSearchRubric as rt, ToxicChatPlugin as s, selectMaxScore as st, GRADERS as t, matchesModeration as tt, TeenSafetyDangerousRoleplayPlugin as u, getDefaultProviders as ut, PolicyPlugin as v, processFileReference as vt, OverreliancePlugin as w, makeInlinePolicyIdSync as x, determinePolicyTypeFromId as y, resolveContext as yt, retryWithDeduplication as z };
15233
+ export { SELECT_BEST_PROMPT as $, DivergentRepetitionPlugin as A, sampleArray as B, getPiiLeakTestsForCategory as C, DEFAULT_ANTHROPIC_MODEL as Ct, HarmbenchPlugin as D, withProviderCallExecutionContext as Dt, ImitationPlugin as E, getGradingProvider as Et, AegisPlugin as F, matchesLlmRubric as G, matchesClosedQa as H, RedteamGraderBase as I, doRemoteGrading as J, matchesPiScore as K, RedteamPluginBase as L, CrossSessionLeakPlugin as M, ContractPlugin as N, HallucinationPlugin as O, BeavertailsPlugin as P, DEFAULT_WEB_SEARCH_PROMPT as Q, getCustomPolicies as R, PlinyPlugin as S, getDefaultProviders as St, IntentPlugin as T, getAndCheckProvider as Tt, matchesFactuality as U, fetchHuggingFaceDataset as V, matchesGEval as W, readPrompts as X, processPrompts as Y, readProviderPromptMap as Z, PoliticsPlugin as _, tryParse as _t, UnverifiableClaimsPlugin as a, CONTEXT_RECALL_ATTRIBUTED_TOKEN as at, isValidPolicyObject as b, loadFromJavaScriptFile as bt, ToolDiscoveryPlugin as c, CONTEXT_RELEVANCE_BAD as ct, TeenSafetyDangerousContentPlugin as d, cosineSimilarity as dt, SUGGEST_PROMPTS_SYSTEM_MESSAGE as et, TeenSafetyAgeRestrictedGoodsAndServicesPlugin as f, dotProduct as ft, PromptExtractionPlugin as g, splitIntoSentences as gt, RbacPlugin as h, normalizeMatcherTokenUsage as ht, VLGuardPlugin as i, CONTEXT_RECALL as it, DebugAccessPlugin as j, ExcessiveAgencyPlugin as k, TeenSafetyHarmfulBodyIdealsPlugin as l, loadRubricPrompt as lt, ShellInjectionPlugin as m, fail as mt, getGraderById as n, CONTEXT_FAITHFULNESS_LONGFORM as nt, UnsafeBenchPlugin as o, CONTEXT_RECALL_NOT_ATTRIBUTED_TOKEN as ot, SqlInjectionPlugin as p, euclideanDistance as pt, matchesTrajectoryGoalSuccess as q, VLSUPlugin as r, CONTEXT_FAITHFULNESS_NLI_STATEMENTS as rt, ToxicChatPlugin as s, CONTEXT_RELEVANCE as st, GRADERS as t, ANSWER_RELEVANCY_GENERATE as tt, TeenSafetyDangerousRoleplayPlugin as u, renderLlmRubricPrompt as ut, PolicyPlugin as v, coerceString as vt, OverreliancePlugin as w, callProviderWithContext as wt, makeInlinePolicyIdSync as x, processFileReference as xt, determinePolicyTypeFromId as y, getFinalTest as yt, retryWithDeduplication as z };
15975
15234
 
15976
- //# sourceMappingURL=graders-eIHhRqoC.js.map
15235
+ //# sourceMappingURL=graders-CgPn32yp.js.map