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.
- package/dist/src/{ListApp-DQkFNqE9.js → ListApp-BRUsT43Y.js} +1 -1
- package/dist/src/{accounts-Dy17bs4D.cjs → accounts-BIFntVWB.cjs} +4 -4
- package/dist/src/{accounts-F9d_5sMC.js → accounts-CLJHCDDb.js} +6 -6
- package/dist/src/{accounts-DhMYUUbu.js → accounts-CaLNYnf7.js} +4 -4
- package/dist/src/{accounts-DdJ2pHMI.js → accounts-bnyHT7Ju.js} +5 -5
- package/dist/src/{agentic-utils-w68v6_Dz.js → agentic-utils-B5krlibj.js} +3 -3
- package/dist/src/{agentic-utils-P172hM8B.js → agentic-utils-Ba67xmgs.js} +2 -2
- package/dist/src/{agentic-utils-qFlm6zes.js → agentic-utils-BclbiXiq.js} +3 -3
- package/dist/src/{agentic-utils-BpX5b23w.cjs → agentic-utils-D2x0wGhB.cjs} +2 -2
- package/dist/src/{agents-CgaMXvLM.js → agents-BGqaTDnr.js} +5 -5
- package/dist/src/{agents-8FDnTriG.js → agents-BV9yFpXX.js} +5 -5
- package/dist/src/{agents-aYPQLf8W.js → agents-BYdMl1UE.js} +4 -4
- package/dist/src/{agents-pQeBEXMm.js → agents-DhxWMCtH.js} +5 -5
- package/dist/src/{agents-D7-HGxUj.cjs → agents-DiWmQYH9.cjs} +4 -4
- package/dist/src/{agents-BahDpe5G.cjs → agents-WULPVjbH.cjs} +4 -4
- package/dist/src/{agents-DJ35I3Nt.js → agents-emVcx3yh.js} +5 -5
- package/dist/src/{agents-C-R_jfzI.js → agents-n6vPqV3i.js} +4 -4
- package/dist/src/{aimlapi-BCq3MHeL.js → aimlapi-BxqK9HF_.js} +7 -7
- package/dist/src/{aimlapi-qcK4OT55.cjs → aimlapi-BzLjZI_m.cjs} +6 -6
- package/dist/src/{aimlapi-BD6J9oKt.js → aimlapi-DR4pgeiC.js} +6 -6
- package/dist/src/{aimlapi-sgYnkE54.js → aimlapi-uPGp0Zdo.js} +7 -7
- package/dist/src/app/app/tsconfig.app.tsbuildinfo +1 -1
- package/dist/src/app/assets/Report-vjzrbgce.js +1 -0
- package/dist/src/app/assets/index-B3NQ8HTd.js +385 -0
- package/dist/src/app/assets/{index-BXGkeMwh.css → index-Cli2yAXv.css} +1 -1
- package/dist/src/app/index.html +27 -2
- package/dist/src/{audio-DcVKoInv.js → audio-BvpTOArF.js} +4 -4
- package/dist/src/{audio-BQtNuYBj.cjs → audio-C0vDeS0j.cjs} +3 -3
- package/dist/src/{audio-B7izf48x.js → audio-CScmnmEB.js} +4 -4
- package/dist/src/{audio-COrn8rM6.js → audio-Da8U9IS5.js} +3 -3
- package/dist/src/{base-fZ9wgg50.js → base-BOMaNEes.js} +3 -3
- package/dist/src/{base-PYJvBE1i.js → base-BTux96b1.js} +2 -2
- package/dist/src/{base-D-670DX8.cjs → base-Tw6uhH8K.cjs} +2 -2
- package/dist/src/{base-yrI1Yal4.js → base-dYsl2hmL.js} +3 -3
- package/dist/src/{blobs-D2FAd1Q5.cjs → blobs-B95F_7vE.cjs} +2 -2
- package/dist/src/{blobs-C-F78Kfn.js → blobs-BW4U31ue.js} +2 -2
- package/dist/src/{blobs-BCZavS8s.js → blobs-D_gg8nbm.js} +3 -3
- package/dist/src/{blobs-BQWqnnvL.js → blobs-DjLby-uP.js} +3 -3
- package/dist/src/{cache-mb7c8hbp.js → cache-BI5BY7ey.js} +4 -4
- package/dist/src/{cache-DbLsVWB2.cjs → cache-BRkhlH3k.cjs} +1 -1
- package/dist/src/cache-BlC6aeJ0.js +3 -0
- package/dist/src/{cache-D5NZmMiT.js → cache-Bzttsk0X.js} +2 -2
- package/dist/src/{cache-C4Xb-hNb.js → cache-Cr-qWIbP.js} +3 -3
- package/dist/src/{cache-BIyPcp5v.cjs → cache-DGg-yTZG.cjs} +2 -2
- package/dist/src/{chat-Dr3DUQ0D.js → chat-BLOdH60v.js} +12 -12
- package/dist/src/{chat-BfPaS15_.js → chat-Cx_LkwvZ.js} +12 -12
- package/dist/src/{chat-mW0ORo8G.js → chat-D9nudO9b.js} +4 -4
- package/dist/src/{chat-I9izLm49.js → chat-DChSH_Es.js} +12 -12
- package/dist/src/{chat-MKxMnZJZ.js → chat-DG2LkwLq.js} +2 -2
- package/dist/src/{chat-BPXSW8Bv.cjs → chat-DH97tVV9.cjs} +2 -2
- package/dist/src/{chat-0bwXjVP0.js → chat-aMQZw6R7.js} +4 -4
- package/dist/src/{chat-CclRbxGf.cjs → chat-vYqqv1gP.cjs} +11 -11
- package/dist/src/{chatkit-zUIVoDos.js → chatkit-B8X34dQc.js} +4 -4
- package/dist/src/{chatkit-Cv6AhukM.js → chatkit-BXu42Qwt.js} +3 -3
- package/dist/src/{chatkit-CJnHRRMM.js → chatkit-CbMRoeYw.js} +4 -4
- package/dist/src/{chatkit-BoWoSgXl.cjs → chatkit-D44VyUyB.cjs} +3 -3
- package/dist/src/{claude-agent-sdk-CPJo3dBQ.cjs → claude-agent-sdk-BRq0bbIK.cjs} +8 -8
- package/dist/src/{claude-agent-sdk-BQNuLaAK.js → claude-agent-sdk-BjriSVRZ.js} +7 -7
- package/dist/src/{claude-agent-sdk-Dtq_L-Sc.js → claude-agent-sdk-BzNZeZ0N.js} +7 -7
- package/dist/src/{claude-agent-sdk-nfAIcxNf.js → claude-agent-sdk-DYv_AJ8u.js} +7 -7
- package/dist/src/cloud-CoD5OacT.js +3 -0
- package/dist/src/{cloud-DQZ5sVjW.js → cloud-Da0bofJd.js} +3 -3
- package/dist/src/{cloudflare-ai-BIB567w6.js → cloudflare-ai-CXC4b1EU.js} +4 -4
- package/dist/src/{cloudflare-ai-DlKr0rY7.js → cloudflare-ai-CyBoIs1Q.js} +6 -6
- package/dist/src/{cloudflare-ai-DGLte7Py.js → cloudflare-ai-DGOwgexC.js} +6 -6
- package/dist/src/{cloudflare-ai-Dl3N9OVD.cjs → cloudflare-ai-DJv5qnyb.cjs} +4 -4
- package/dist/src/{cloudflare-gateway-BDZrYydE.js → cloudflare-gateway-1sAoOyft.js} +5 -5
- package/dist/src/{cloudflare-gateway-CiIZHU0Q.js → cloudflare-gateway-D-dnkzCF.js} +5 -5
- package/dist/src/{cloudflare-gateway-BYDp495F.cjs → cloudflare-gateway-DKVjkDav.cjs} +3 -3
- package/dist/src/{cloudflare-gateway-DI1HNP5F.js → cloudflare-gateway-TJkVrZlB.js} +3 -3
- package/dist/src/codex-app-server-CCLjqCh9.js +1915 -0
- package/dist/src/codex-app-server-CCe0TiDc.js +1915 -0
- package/dist/src/codex-app-server-CPW1LFwh.js +1916 -0
- package/dist/src/codex-app-server-VMRnjZ68.cjs +1920 -0
- package/dist/src/codex-sdk-1jm_qPHf.js +3 -0
- package/dist/src/{codex-sdk-C2_M2pl_.cjs → codex-sdk-Bd8UbO9q.cjs} +5 -5
- package/dist/src/{codex-sdk-CpqiOqDO.js → codex-sdk-BgEFQ70r.js} +6 -6
- package/dist/src/{codex-sdk-Rtky3M4I.js → codex-sdk-Bzb_TqX9.js} +6 -6
- package/dist/src/{codex-sdk-CWEnH70W.cjs → codex-sdk-Danroptg.cjs} +1 -1
- package/dist/src/{codex-sdk-CErXn7qh.js → codex-sdk-DfvDTN33.js} +5 -5
- package/dist/src/{cometapi-CtJ-mS8R.js → cometapi-B5ImDlSm.js} +8 -8
- package/dist/src/{cometapi-UVOryo4W.cjs → cometapi-BgAkuYCw.cjs} +7 -7
- package/dist/src/{cometapi-BUlt_ELa.js → cometapi-CC7hWxmX.js} +8 -8
- package/dist/src/{cometapi-DT-jlVCB.js → cometapi-CCbpHkuF.js} +7 -7
- package/dist/src/{completion-x0a_c2y1.js → completion-2iuYVxwi.js} +6 -6
- package/dist/src/{completion-Dnxn7E-j.js → completion-CrD6MQ93.js} +5 -5
- package/dist/src/{completion-BozdoXba.cjs → completion-DtQ72Bm3.cjs} +5 -5
- package/dist/src/{completion-HUe8wDhZ.js → completion-Vq_ad618.js} +6 -6
- package/dist/src/{createHash-ChI45QR1.js → createHash-DPpsZgFF.js} +1 -1
- package/dist/src/{createHash-CwDVU5xr.js → createHash-Un4Q_huE.js} +1 -1
- package/dist/src/{createHash-B7KvgoOD.cjs → createHash-VvBIc-AW.cjs} +1 -1
- package/dist/src/{docker-DCgsveLD.js → docker--3qzPa-6.js} +6 -6
- package/dist/src/{docker-DS4_Osau.cjs → docker-D3AY-5F5.cjs} +5 -5
- package/dist/src/{docker-CQmlA2NU.js → docker-DCsCDvwM.js} +6 -6
- package/dist/src/{docker-ClnmCf1Z.js → docker-Dorv4_Dg.js} +5 -5
- package/dist/src/{embedding-I45KG3o7.cjs → embedding-BXhN5lCH.cjs} +5 -5
- package/dist/src/{embedding-nFbumxcv.js → embedding-ChS1ivFS.js} +5 -5
- package/dist/src/{embedding-D3xTseo7.js → embedding-DNRvZwRN.js} +6 -6
- package/dist/src/{embedding-DD9wa3ae.js → embedding-D_bI4NDq.js} +6 -6
- package/dist/src/{errors-Cw810C93.js → errors-DFHe4L-n.js} +1 -1
- package/dist/src/{esm-Dh4dOLlt.js → esm-B6whoAcf.js} +2 -2
- package/dist/src/{esm-C7PnfdF8.js → esm-BRkfNsYs.js} +1 -1
- package/dist/src/{esm-tVgYPY-f.js → esm-BX8fwlAO.js} +2 -2
- package/dist/src/{esm-CtEPLdAj.cjs → esm-B_rGuPTo.cjs} +1 -1
- package/dist/src/{eval-CzJFfFO9.js → eval-BQPLBJbw.js} +1 -1
- package/dist/src/{eval-u4UVafl6.js → eval-DJ_4A-tr.js} +14 -14
- package/dist/src/evalResult-BBJAHAtw.cjs +2 -0
- package/dist/src/evalResult-BBK58h2B.js +3 -0
- package/dist/src/{evalResult-KZqXl4XP.cjs → evalResult-Cx-8OWkb.cjs} +28 -10
- package/dist/src/{evalResult-D3hVYFis.js → evalResult-D6P5I5il.js} +29 -11
- package/dist/src/{evalResult-Bgm9ZH31.js → evalResult-pSvGWFMo.js} +29 -11
- package/dist/src/{evaluator-IvuDYSvQ.js → evaluator-D-UIbbYq.js} +845 -98
- package/dist/src/evaluator-DgLKaZk8.js +3 -0
- package/dist/src/{extractor-Dk6bRWkv.js → extractor-BM3jRERL.js} +5 -5
- package/dist/src/{extractor-WVPOrH43.cjs → extractor-Dxr2J_wK.cjs} +5 -5
- package/dist/src/{extractor-DNSeBVOJ.js → extractor-DxyiFhPk.js} +6 -6
- package/dist/src/{extractor-CAfTSraf.js → extractor-YlZbUMsL.js} +6 -6
- package/dist/src/fetch-8viavNv8.js +3 -0
- package/dist/src/{fetch-BEWnXrrG.js → fetch-B6ch2nU2.js} +9 -20
- package/dist/src/{fetch-Di00EQrc.js → fetch-D9xxyC1p.js} +221 -232
- package/dist/src/{fetch-CJU5ELPa.cjs → fetch-NuqXW1Xb.cjs} +221 -244
- package/dist/src/{fetch-B0Z3Oe4k.js → fetch-Y5qX_kST.js} +8 -19
- package/dist/src/{fileExtensions-BArZuxsI.js → fileExtensions-8CjoL7vB.js} +1 -1
- package/dist/src/{fileExtensions-DnqA1y9x.js → fileExtensions-BGh-W-HT.js} +1 -1
- package/dist/src/{fileExtensions-bYh77CN8.cjs → fileExtensions-D9h-8Wxg.cjs} +1 -1
- package/dist/src/{fileExtensions-AWa2ZML4.js → fileExtensions-DysCsxNG.js} +1 -1
- package/dist/src/{formatDuration-DZzPsexs.js → formatDuration-Ch4A7G3o.js} +1 -1
- package/dist/src/{genaiTracer-yRuxj9-L.cjs → genaiTracer-BokHC-MW.cjs} +1 -1
- package/dist/src/{genaiTracer-DWdZ28hY.js → genaiTracer-C3ZPQU60.js} +1 -1
- package/dist/src/{genaiTracer-XnrcgDCe.js → genaiTracer-CFny3gOy.js} +1 -1
- package/dist/src/{genaiTracer-COYDi-tC.js → genaiTracer-DxODqT9e.js} +1 -1
- package/dist/src/{graders-Zy3x0zqX.js → graders-BoUqsCEm.js} +1303 -2044
- package/dist/src/{graders--zknU_uk.cjs → graders-Bw1wk_21.cjs} +1553 -2240
- package/dist/src/graders-C84JI-m5.js +2 -0
- package/dist/src/graders-CBbd0K0Q.cjs +2 -0
- package/dist/src/graders-CbQqpHSN.js +3 -0
- package/dist/src/{graders-eIHhRqoC.js → graders-CgPn32yp.js} +1300 -2041
- package/dist/src/{graders-pvbReLLn.js → graders-CwrbifOo.js} +747 -1488
- package/dist/src/graders-DS42d3ZG.js +2 -0
- package/dist/src/{image-9302QVqR.js → image-BeWaInPF.js} +3 -3
- package/dist/src/{image-DVz2RiMF.js → image-BmilRNqO.js} +7 -7
- package/dist/src/{image-x6KqLQl4.cjs → image-CxJoa3aW.cjs} +6 -6
- package/dist/src/{image-De2FBmYV.cjs → image-D10dNAav.cjs} +3 -3
- package/dist/src/{image-dnoUgPrC.js → image-Dr_3I3nK.js} +4 -4
- package/dist/src/{image-B5Mv-Z3h.js → image-DsGRlkh7.js} +7 -7
- package/dist/src/{image-qUpPvmNZ.js → image-a_SGUobh.js} +6 -6
- package/dist/src/{image-u7-rKnYU.js → image-qjO6FWPs.js} +4 -4
- package/dist/src/index.cjs +1052 -296
- package/dist/src/index.d.cts +124 -13
- package/dist/src/index.d.ts +125 -14
- package/dist/src/index.js +1018 -262
- package/dist/src/{interactiveCheck-CLERUB0c.js → interactiveCheck-CCICw2cy.js} +2 -2
- package/dist/src/{invariant-BtWWVVhl.js → invariant-B2Rf6avk.js} +1 -1
- package/dist/src/{invariant-vgHWClmd.js → invariant-DIYf9sP1.js} +1 -1
- package/dist/src/{knowledgeBase-RhFPGWDc.js → knowledgeBase-BBETc5-S.js} +6 -6
- package/dist/src/{knowledgeBase-Bpoe_nLu.cjs → knowledgeBase-C8qOo26M.cjs} +5 -5
- package/dist/src/{knowledgeBase-lm9RXSAm.js → knowledgeBase-CzAi2rUI.js} +6 -6
- package/dist/src/{knowledgeBase-Dgc7CBWF.js → knowledgeBase-Dr3Kib7F.js} +5 -5
- package/dist/src/{litellm-C2kqjxqp.js → litellm-BLSiANhk.js} +5 -5
- package/dist/src/{litellm-CoyI4IAl.cjs → litellm-CaUmV7Mk.cjs} +4 -4
- package/dist/src/{litellm-p37R1dzQ.js → litellm-DQGo_juI.js} +4 -4
- package/dist/src/{litellm-DRjpcSa7.js → litellm-DRc4qWfc.js} +5 -5
- package/dist/src/{logger-DksKw1Qc.js → logger-BbY6ypFL.js} +2 -2
- package/dist/src/{logger-B88EkIn6.js → logger-KD8JjCRJ.js} +2 -2
- package/dist/src/{luma-ray-KgTCXrZC.js → luma-ray-B-tNZzqW.js} +6 -6
- package/dist/src/{luma-ray-B863CmuZ.js → luma-ray-CtS3OlGq.js} +5 -5
- package/dist/src/{luma-ray-BTTLtqQ8.js → luma-ray-PJJgUjOc.js} +6 -6
- package/dist/src/{luma-ray-BxVKaW2a.cjs → luma-ray-if-Ml4R9.cjs} +5 -5
- package/dist/src/main.js +242 -198
- package/dist/src/{messages-zWbkLLHz.js → messages-B9dSjrNf.js} +264 -16
- package/dist/src/{messages-811uVVW5.cjs → messages-BnsVHUnm.cjs} +266 -15
- package/dist/src/{messages-MYTQ2TWp.js → messages-CI69Lasb.js} +264 -16
- package/dist/src/{messages-BTQz42fn.js → messages-CewuNcNS.js} +264 -16
- package/dist/src/{meteor-Co1VQ1u5.cjs → meteor-BBGcGeCa.cjs} +1 -1
- package/dist/src/{meteor-DuAFv6gF.js → meteor-BKTM-7KS.js} +1 -1
- package/dist/src/{meteor-DHdzY1Ss.js → meteor-CeGo0Lu2.js} +2 -2
- package/dist/src/{meteor-CU5UAE-H.js → meteor-Wc_aUVvu.js} +2 -2
- package/dist/src/{modelslab-wu9yi5GE.js → modelslab-BCLOtfek.js} +7 -7
- package/dist/src/{modelslab-Dk1JAtVo.cjs → modelslab-BkapYJhh.cjs} +6 -6
- package/dist/src/{modelslab-DIq-6y7x.js → modelslab-D73OnKSx.js} +6 -6
- package/dist/src/{modelslab-D0erNWKe.js → modelslab-zpz9JcK0.js} +7 -7
- package/dist/src/{nova-reel-CCFRfeRb.js → nova-reel-B8F_TK5w.js} +6 -6
- package/dist/src/{nova-reel-DQrm74ng.js → nova-reel-Bx0NFV2f.js} +5 -5
- package/dist/src/{nova-reel-gr11WG7f.js → nova-reel-CNGJTLtG.js} +6 -6
- package/dist/src/{nova-reel-CrLXVKQf.cjs → nova-reel-DkT7tnoB.cjs} +5 -5
- package/dist/src/{nova-sonic-BYdp-QLs.js → nova-sonic-BaXRN1cr.js} +4 -4
- package/dist/src/{nova-sonic-TDgrlTk7.js → nova-sonic-BeTRaFOh.js} +4 -4
- package/dist/src/{nova-sonic-B_ZXcUJB.js → nova-sonic-CL7Zqv0G.js} +3 -3
- package/dist/src/{nova-sonic-i5tUvXKn.cjs → nova-sonic-YT426juD.cjs} +3 -3
- package/dist/src/{openai-DhVEmgeZ.js → openai-BMHD2Huo.js} +2 -2
- package/dist/src/{openai-Qsvz25mV.js → openai-BT-JvDse.js} +2 -2
- package/dist/src/{openai-URNyItar.cjs → openai-Cy1XLs0c.cjs} +1 -1
- package/dist/src/{openai-iYtrXzOX.js → openai-D4fxGvRx.js} +1 -1
- package/dist/src/{openclaw-CwzlQSQX.js → openclaw-Bq7RVR3k.js} +7 -6
- package/dist/src/{openclaw-CLWrW03k.js → openclaw-DA8U4DsD.js} +8 -7
- package/dist/src/{openclaw-CnQ363Wi.js → openclaw-DObVgpjC.js} +8 -7
- package/dist/src/{openclaw-wX9rtfke.cjs → openclaw-DUBZP3GL.cjs} +8 -7
- package/dist/src/{opencode-sdk-BUu5Nevv.js → opencode-sdk-BB40Wir1.js} +4 -4
- package/dist/src/{opencode-sdk-GI2KaAXq.js → opencode-sdk-BM1UAIv1.js} +3 -3
- package/dist/src/{opencode-sdk-BZ2idgYA.cjs → opencode-sdk-CeqiOcOU.cjs} +4 -4
- package/dist/src/{opencode-sdk-BxD8vXp_.js → opencode-sdk-ChdK7F7z.js} +4 -4
- package/dist/src/{otlpReceiver-DmVulbhC.js → otlpReceiver-C6thJRXi.js} +4 -4
- package/dist/src/{otlpReceiver-B2z58l4e.js → otlpReceiver-CcdIikOu.js} +3 -3
- package/dist/src/{otlpReceiver-BfcVq2Nq.cjs → otlpReceiver-DNSQj6bf.cjs} +3 -3
- package/dist/src/{otlpReceiver-BntK801g.js → otlpReceiver-UYMQx3sy.js} +4 -4
- package/dist/src/{providerRegistry-CPQ_CmVO.js → providerRegistry-1gB5vtzQ.js} +2 -2
- package/dist/src/{providerRegistry-CQMdTmHP.cjs → providerRegistry-BESeALrr.cjs} +1 -1
- package/dist/src/{providerRegistry-Bvh8mv85.js → providerRegistry-DoACwqhD.js} +1 -1
- package/dist/src/{providerRegistry-CWoPjKFZ.js → providerRegistry-PMsleEzs.js} +2 -2
- package/dist/src/{providers-Bp4S-FvO.js → providers-BuyzKt7C.js} +1 -1
- package/dist/src/{providers-DV3ax9e_.cjs → providers-C7lNVBjX.cjs} +1 -1
- package/dist/src/{providers-u9Enmfok.js → providers-CCE2COJi2.js} +1 -1
- package/dist/src/{providers-DruaQfwu.js → providers-CJh7iriU.js} +18103 -17952
- package/dist/src/{providers-iUt5fbAN.js → providers-Ctcc592x.js} +1 -1
- package/dist/src/{providers-Domz_llv.js → providers-DRrerKra.js} +432 -281
- package/dist/src/{providers-BV_KMZje.js → providers-DT-GtF2t.js} +19094 -18943
- package/dist/src/{providers-1eKkXBKp.cjs → providers-eDShy16E.cjs} +17946 -17795
- package/dist/src/{pythonUtils-Cldx7huE.js → pythonUtils-C4tltmIn.js} +3 -3
- package/dist/src/{pythonUtils-tAJvvpS-.cjs → pythonUtils-CoLaCwNY.cjs} +3 -3
- package/dist/src/{pythonUtils-C2UQ30Rz.js → pythonUtils-DMO68Jg7.js} +3 -3
- package/dist/src/{pythonUtils-CnndUbW-.js → pythonUtils-DNqbnRdx.js} +3 -3
- package/dist/src/{quiverai-DR0SnIQV.js → quiverai-BSS9a7wV.js} +3 -3
- package/dist/src/{quiverai-CtWi6x_g.js → quiverai-Bk1KrvL6.js} +4 -4
- package/dist/src/{quiverai-DFotyafY.cjs → quiverai-Bpx6MZ7T.cjs} +3 -3
- package/dist/src/{quiverai-aPPvXOgn.js → quiverai-CPKhWgaT.js} +4 -4
- package/dist/src/{render-DHIZ6_k8.js → render-7uNJ2V14.js} +2 -2
- package/dist/src/{render-CH-62LbA.js → render-DlscvAUJ.js} +1 -1
- package/dist/src/{render-CMEpfLaO.js → render-eui5p5mL.js} +2 -2
- package/dist/src/{render-CgVDrJmM.js → render-nj-UaPdn.js} +2 -2
- package/dist/src/{render-DfQSFxGE.cjs → render-tG6ir9_g.cjs} +1 -1
- package/dist/src/{responses--OsX2aYW.js → responses-1ztiVYsx.js} +49 -15
- package/dist/src/{responses-DL9m8CyY.js → responses-B8haB-mD.js} +49 -15
- package/dist/src/{responses-C-flexAY.js → responses-BiaBguAu.js} +49 -15
- package/dist/src/{responses-Bi9vBuW_.cjs → responses-CF-ayauu.cjs} +48 -14
- package/dist/src/rubyUtils-4hjGxvju.js +3 -0
- package/dist/src/{rubyUtils-DVLeA2jg.js → rubyUtils-BI0p46eZ.js} +3 -3
- package/dist/src/{rubyUtils-DsGrTx8R.js → rubyUtils-CIQFnVz4.js} +3 -3
- package/dist/src/rubyUtils-CO-tuszQ.cjs +2 -0
- package/dist/src/{rubyUtils-CYSQEG4a.js → rubyUtils-DGnoCYL2.js} +3 -3
- package/dist/src/{rubyUtils-B6eljPuh.cjs → rubyUtils-DoifqkiA.cjs} +4 -3
- package/dist/src/{sagemaker-BveBvuxm.js → sagemaker-BDLeW29y.js} +12 -12
- package/dist/src/{sagemaker-D67yzMzs.js → sagemaker-C5T60MKf.js} +13 -13
- package/dist/src/{sagemaker-BVkaG2-l.js → sagemaker-ClS_NB07.js} +13 -13
- package/dist/src/{sagemaker-XnfhheQv.cjs → sagemaker-ljtY12VM.cjs} +12 -12
- package/dist/src/{scanner-1DqWi1Ej.js → scanner-nOCWNIXa.js} +7 -7
- package/dist/src/server/index.js +1067 -265
- package/dist/src/{server-Dx2TyCH2.cjs → server-BEECpeGG.cjs} +5 -5
- package/dist/src/{server-BNYztJkh.js → server-ByiF3qlg.js} +9 -8
- package/dist/src/{server-BSB45Nt9.js → server-ByxbqAcQ.js} +8 -7
- package/dist/src/{server-DaA2eR26.cjs → server-C0XKRNB_.cjs} +1 -1
- package/dist/src/server-C_15p79-.js +3 -0
- package/dist/src/{server-D6Il2Sob.js → server-gyd6d4Hc.js} +5 -5
- package/dist/src/{signal-CE5G3a7x.js → signal-DTtUuU3l.js} +3 -3
- package/dist/src/{slack-acRb0IqQ.js → slack-4zZX1OKP.js} +1 -1
- package/dist/src/{slack-1Rhq0EoV.cjs → slack-BLlsDpfG.cjs} +1 -1
- package/dist/src/{slack-D5Wpy8LM.js → slack-BPYLQLgb.js} +2 -2
- package/dist/src/{slack-DDUe-5MC.js → slack-Bamy_7te.js} +2 -2
- package/dist/src/{store-DAAyxcy6.cjs → store-2K0kDi80.cjs} +2 -2
- package/dist/src/{store-Dn9HUkdW.js → store-2OXm_eBY.js} +3 -3
- package/dist/src/store-BELqNwvz.js +3 -0
- package/dist/src/{store-M0b1WfYb.js → store-BPkzEyFM.js} +2 -2
- package/dist/src/{store-CYEy5J2D.js → store-CPh25336.js} +3 -3
- package/dist/src/store-uQZ4AjPe.cjs +2 -0
- package/dist/src/{tables-CsWou1Bx.js → tables-BMSOS2Gg.js} +3 -3
- package/dist/src/{tables-DUfh1F7Z.cjs → tables-CXbaZ9y1.cjs} +2 -2
- package/dist/src/{tables-C4CH3zRr.js → tables-NlvH23ky.js} +3 -3
- package/dist/src/{tables-DQ4WU5tX.js → tables-WgdUZ8Ck.js} +2 -2
- package/dist/src/{telemetry-dbaJ0E98.js → telemetry--iqaGyaS.js} +5 -4
- package/dist/src/{telemetry-Dsw_faFj.cjs → telemetry-CEQxGnMZ.cjs} +7 -6
- package/dist/src/{telemetry-Dvqxv3YC.js → telemetry-CgdVGV8N.js} +4 -3
- package/dist/src/{telemetry-CQPez_Jp.js → telemetry-DWdGHvEf.js} +5 -4
- package/dist/src/telemetry-DjNoC_n3.cjs +2 -0
- package/dist/src/telemetry-ZdPZc0fm.js +3 -0
- package/dist/src/{text-BVi-cLPJ.cjs → text-BiNME7QG.cjs} +1 -1
- package/dist/src/{text-KvuD2Iko.js → text-D4lz-Jg_.js} +1 -1
- package/dist/src/{text-DHxdyQqT.js → text-DDQP0tuQ.js} +1 -1
- package/dist/src/{text-CZr46tp_.js → text-NWvfMfkF.js} +1 -1
- package/dist/src/{tokenUsageUtils-CXrvO-wA.js → tokenUsageUtils-2wIvAhB3.js} +1 -1
- package/dist/src/{tokenUsageUtils-C-bmyHoE.js → tokenUsageUtils-4c780gFd.js} +1 -1
- package/dist/src/tokenUsageUtils-BjVkdk18.js +142 -0
- package/dist/src/{tokenUsageUtils-Bb7DkZPz.cjs → tokenUsageUtils-C9odhsbW.cjs} +1 -1
- package/dist/src/{transcription-DuWDupG7.js → transcription-84t4ALo2.js} +5 -5
- package/dist/src/{transcription-CJspiD2c.js → transcription-Bm2emLmJ.js} +6 -6
- package/dist/src/{transcription-BvjmiYB1.cjs → transcription-CZ4LG5hQ.cjs} +5 -5
- package/dist/src/{transcription-V2HaAmy2.js → transcription-D7Q0vJsh.js} +6 -6
- package/dist/src/{transform-zDhMmzwX.js → transform-B-b6Cq-q.js} +5 -5
- package/dist/src/transform-BQt0BeAW.js +3 -0
- package/dist/src/{transform-DgKlRr73.cjs → transform-Bq5oqC0s.cjs} +1 -1
- package/dist/src/{transform-CUnzlsbn.cjs → transform-C9izGX54.cjs} +4 -4
- package/dist/src/{transform-DYX1_Xnh.js → transform-CwbAZ84V.js} +5 -5
- package/dist/src/{transform-CTeuTR3S.cjs → transform-Dg4LcO1Y.cjs} +6 -6
- package/dist/src/{transform-CG0ehZNG.js → transform-DtooZqYY.js} +6 -6
- package/dist/src/{transform-UN5UGu8U.js → transform-DzCF-wqV.js} +5 -5
- package/dist/src/{transform-lQrDE1BQ.js → transform-_DpNB4qp.js} +5 -5
- package/dist/src/{transform-Bbg6A8Jk.js → transform-eGiUAv86.js} +4 -4
- package/dist/src/{transformersAvailability-Cju9mHgR.cjs → transformersAvailability-B22swDxr.cjs} +1 -1
- package/dist/src/{transformersAvailability-CcHusyhw.js → transformersAvailability-lvCCvuPT.js} +1 -1
- package/dist/src/{transformersAvailability-DLlROWhg.js → transformersAvailability-rJGPccjr.js} +1 -1
- package/dist/src/{types-Bgh5SOn6.js → types-BDjGOq4E.js} +4 -2
- package/dist/src/{types-Dm9JM6Vb.js → types-BVH9hjgW.js} +4 -2
- package/dist/src/{types-CeaeaZdP.cjs → types-CgG2rKiW.cjs} +151 -149
- package/dist/src/{types-BGQDAP8i.js → types-DNRZVOue.js} +152 -150
- package/dist/src/{util-C8e5uydV.js → util-3pBZZb_H.js} +142 -17
- package/dist/src/{util-CN3SrLT4.cjs → util-A5_ZsQUn.cjs} +65 -43
- package/dist/src/{util-D3q0WQ-0.js → util-B9CNhyac.js} +66 -44
- package/dist/src/{util-DxWpWjhc.js → util-BQOCAHQC.js} +700 -575
- package/dist/src/{util-BYvQUPp7.js → util-BVXcTwXu.js} +3 -3
- package/dist/src/{util-D9TisOyk.js → util-BlFVL0UF.js} +65 -43
- package/dist/src/{util-C9J8ahRn.js → util-C-kmRosx.js} +66 -44
- package/dist/src/{util-DvU2Pw8c.js → util-DFPeFkiV.js} +3 -3
- package/dist/src/{util-DDs-7g6-.js → util-DN0-b81k.js} +3 -3
- package/dist/src/{util-olYL5C6N.cjs → util-Dpmm_dAI.cjs} +3 -3
- package/dist/src/{util-oGMLA7vc.js → util-Dub0f_ej.js} +700 -575
- package/dist/src/{util-Bxn8emtE.cjs → util-DvpHnLt0.cjs} +718 -570
- package/dist/src/{utils-DJfvjyMj.js → utils-BUMN8orw.js} +3 -3
- package/dist/src/{utils-B05gLxER.cjs → utils-DkVeShIB.cjs} +2 -2
- package/dist/src/{utils-BLJKfv0y.js → utils-kt7lv30R.js} +3 -3
- package/dist/src/{utils-hXtCYanr.js → utils-o8S5huU2.js} +2 -2
- package/dist/src/version-0frU0UTr.js +16 -0
- package/dist/src/version-CbpiUINz.js +17 -0
- package/dist/src/version-CbuBKu2U.js +16 -0
- package/dist/src/version-D9zu9FWB.cjs +27 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +22 -20
- package/dist/src/app/assets/Report-CQYFezYu.js +0 -1
- package/dist/src/app/assets/index-BzJt18Jz.js +0 -385
- package/dist/src/cache-Cr9oLMUa.js +0 -3
- package/dist/src/cloud-Hphvo8kr.js +0 -3
- package/dist/src/codex-sdk-BAmYE7qy.js +0 -3
- package/dist/src/evalResult-D8MT9p0s.js +0 -3
- package/dist/src/evalResult-Dvc-iucu.cjs +0 -2
- package/dist/src/evaluator-CVessDWe.js +0 -3
- package/dist/src/fetch-C7bGKDlQ.js +0 -3
- package/dist/src/graders-BOAzQEUe.cjs +0 -2
- package/dist/src/graders-D4BTsZdG2.js +0 -3
- package/dist/src/graders-DOJK1XpV.js +0 -2
- package/dist/src/graders-NAv9LcBn.js +0 -2
- package/dist/src/rubyUtils-D1L2d3jb.js +0 -3
- package/dist/src/rubyUtils-DUbq4tff.cjs +0 -2
- package/dist/src/server-DCtHUqlp.js +0 -3
- package/dist/src/store-CWOSz6D_.cjs +0 -2
- package/dist/src/store-DCDBhv7B.js +0 -3
- package/dist/src/telemetry-C1IqxcdW.js +0 -3
- package/dist/src/telemetry-C4ZEa_es.cjs +0 -2
- package/dist/src/transform-M6ITAESf.js +0 -3
- /package/dist/src/{evalResult-DElBuddX.js → evalResult-spPqh1G_.js} +0 -0
|
@@ -1,25 +1,24 @@
|
|
|
1
|
-
import { O as isCI, S as getEnvBool, T as getEnvString, a as logger, h as extractJsonObjects, k as state, m as extractFirstJsonObject, y as safeJsonStringify } from "./logger-
|
|
2
|
-
import { d as sleep, h as REQUEST_TIMEOUT_MS, r as fetchWithTimeout, t as fetchWithProxy } from "./fetch-
|
|
3
|
-
import { t as invariant } from "./invariant-
|
|
4
|
-
import { o as getUserEmail } from "./accounts-
|
|
5
|
-
import { r as importModule } from "./esm-
|
|
6
|
-
import { a as getNunjucksEngine, r as extractVariablesFromTemplate } from "./render-
|
|
7
|
-
import { c as getRemoteGenerationUrl, h as hasCodexDefaultCredentials, m as getCodexDefaultProviders, p as shouldGenerateRemote } from "./server-
|
|
8
|
-
import { C as isValidReusablePolicyId,
|
|
9
|
-
import { i as isJavascriptFile } from "./fileExtensions-
|
|
10
|
-
import { n as sha256 } from "./createHash-
|
|
11
|
-
import { i as PROMPT_DELIMITER, n as maybeFilePath, r as normalizeInput } from "./utils-
|
|
12
|
-
import { a as isCacheEnabled, i as getCache, r as fetchWithCache } from "./cache-
|
|
13
|
-
import { r as accumulateTokenUsage } from "./tokenUsageUtils-
|
|
14
|
-
import { A as removePrefix, B as isRateLimitWrapped, C as extractInputVarsFromPrompt, D as getShortPluginId, H as MAX_CHARS_PER_MESSAGE_MODIFIER_KEY, I as redteamProviderManager, J as MistralChatCompletionProvider, K as REDTEAM_MEMORY_POISONING_PLUGIN_ID, O as isBasicRefusal, S as extractGoalFromPrompt, T as extractVariablesFromJson, U as getGeneratedPromptOverLimit, W as getMaxCharsPerMessageModifierValue, X as DefaultEmbeddingProvider$2, Y as MistralEmbeddingProvider, Z as DefaultGradingProvider$3, at as AzureModerationProvider, b as checkExfilTracking, et as DefaultGradingJsonProvider$2, it as DefaultSynthesizeProvider$1, k as isEmptyResponse, n as loadApiProvider, nt as DefaultLlmRubricProvider, o as getFileHashes, ot as AzureEmbeddingProvider, pt as getPoliciesFromCloud, q as OpenAiModerationProvider, rt as DefaultSuggestionsProvider$2, s as parseScriptParts, st as AzureChatCompletionProvider, tt as DefaultGradingProvider$2, w as extractPromptFromTags, x as extractAllPromptsFromTags, z as createProviderRateLimitOptions } from "./providers-
|
|
15
|
-
import { r as runPython } from "./pythonUtils-
|
|
16
|
-
import {
|
|
17
|
-
import { t as OpenAiChatCompletionProvider } from "./chat-
|
|
18
|
-
import { x as hasGoogleDefaultCredentials } from "./transform-
|
|
19
|
-
import { t as AnthropicMessagesProvider } from "./messages-
|
|
20
|
-
import { t as OpenAiResponsesProvider } from "./responses-
|
|
21
|
-
import { t as OpenAiEmbeddingProvider } from "./embedding-
|
|
22
|
-
import { n as transform } from "./transform-DYX1_Xnh.js";
|
|
1
|
+
import { O as isCI, S as getEnvBool, T as getEnvString, a as logger, h as extractJsonObjects, k as state, m as extractFirstJsonObject, y as safeJsonStringify } from "./logger-KD8JjCRJ.js";
|
|
2
|
+
import { d as sleep, h as REQUEST_TIMEOUT_MS, r as fetchWithTimeout, t as fetchWithProxy } from "./fetch-Y5qX_kST.js";
|
|
3
|
+
import { t as invariant } from "./invariant-DIYf9sP1.js";
|
|
4
|
+
import { o as getUserEmail } from "./accounts-bnyHT7Ju.js";
|
|
5
|
+
import { r as importModule } from "./esm-B6whoAcf.js";
|
|
6
|
+
import { a as getNunjucksEngine, r as extractVariablesFromTemplate } from "./render-7uNJ2V14.js";
|
|
7
|
+
import { c as getRemoteGenerationUrl, h as hasCodexDefaultCredentials, m as getCodexDefaultProviders, p as shouldGenerateRemote } from "./server-ByxbqAcQ.js";
|
|
8
|
+
import { C as isValidReusablePolicyId, ft as CODING_AGENT_PLUGINS, ht as PromptSchema, k as MULTI_TURN_STRATEGIES, mt as CODING_AGENT_PLUGIN_DISPLAY_NAMES, pt as CODING_AGENT_PLUGIN_DESCRIPTIONS, x as PolicyObjectSchema } from "./types-BDjGOq4E.js";
|
|
9
|
+
import { i as isJavascriptFile } from "./fileExtensions-BGh-W-HT.js";
|
|
10
|
+
import { n as sha256 } from "./createHash-4gFQpDDv.js";
|
|
11
|
+
import { i as PROMPT_DELIMITER, n as maybeFilePath, r as normalizeInput } from "./utils-BUMN8orw.js";
|
|
12
|
+
import { a as isCacheEnabled, i as getCache, r as fetchWithCache } from "./cache-Cr-qWIbP.js";
|
|
13
|
+
import { r as accumulateTokenUsage } from "./tokenUsageUtils-BjVkdk18.js";
|
|
14
|
+
import { A as removePrefix, B as isRateLimitWrapped, C as extractInputVarsFromPrompt, D as getShortPluginId, H as MAX_CHARS_PER_MESSAGE_MODIFIER_KEY, I as redteamProviderManager, J as MistralChatCompletionProvider, K as REDTEAM_MEMORY_POISONING_PLUGIN_ID, O as isBasicRefusal, S as extractGoalFromPrompt, T as extractVariablesFromJson, U as getGeneratedPromptOverLimit, W as getMaxCharsPerMessageModifierValue, X as DefaultEmbeddingProvider$2, Y as MistralEmbeddingProvider, Z as DefaultGradingProvider$3, at as AzureModerationProvider, b as checkExfilTracking, et as DefaultGradingJsonProvider$2, it as DefaultSynthesizeProvider$1, k as isEmptyResponse, n as loadApiProvider, nt as DefaultLlmRubricProvider, o as getFileHashes, ot as AzureEmbeddingProvider, pt as getPoliciesFromCloud, q as OpenAiModerationProvider, rt as DefaultSuggestionsProvider$2, s as parseScriptParts, st as AzureChatCompletionProvider, tt as DefaultGradingProvider$2, w as extractPromptFromTags, x as extractAllPromptsFromTags, z as createProviderRateLimitOptions } from "./providers-DRrerKra.js";
|
|
15
|
+
import { r as runPython } from "./pythonUtils-C4tltmIn.js";
|
|
16
|
+
import { E as getNunjucksEngineForFilePath, L as parseFileUrl, M as maybeLoadToolsFromExternalFile, N as parsePathOrGlob, O as maybeLoadConfigFromExternalFile, k as maybeLoadFromExternalFile } from "./util-3pBZZb_H.js";
|
|
17
|
+
import { t as OpenAiChatCompletionProvider } from "./chat-DChSH_Es.js";
|
|
18
|
+
import { x as hasGoogleDefaultCredentials } from "./transform-DtooZqYY.js";
|
|
19
|
+
import { t as AnthropicMessagesProvider } from "./messages-CewuNcNS.js";
|
|
20
|
+
import { t as OpenAiResponsesProvider } from "./responses-1ztiVYsx.js";
|
|
21
|
+
import { t as OpenAiEmbeddingProvider } from "./embedding-D_bI4NDq.js";
|
|
23
22
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
24
23
|
import * as fs$2 from "fs";
|
|
25
24
|
import fs from "fs";
|
|
@@ -337,55 +336,120 @@ async function getCustomPolicies(policyPluginsWithRefs, teamId) {
|
|
|
337
336
|
return policiesById;
|
|
338
337
|
}
|
|
339
338
|
//#endregion
|
|
340
|
-
//#region src/
|
|
339
|
+
//#region src/scheduler/providerCallExecutionContext.ts
|
|
340
|
+
const providerCallExecutionContext = new AsyncLocalStorage();
|
|
341
|
+
function getProviderCallExecutionContext() {
|
|
342
|
+
return providerCallExecutionContext.getStore();
|
|
343
|
+
}
|
|
344
|
+
function withProviderCallExecutionContext(context, fn) {
|
|
345
|
+
return providerCallExecutionContext.run(context, fn);
|
|
346
|
+
}
|
|
347
|
+
//#endregion
|
|
348
|
+
//#region src/matchers/providers.ts
|
|
341
349
|
/**
|
|
342
|
-
*
|
|
343
|
-
*
|
|
344
|
-
*
|
|
350
|
+
* Helper to call provider with consistent context propagation pattern.
|
|
351
|
+
* Spreads the optional context and merges with prompt label and vars.
|
|
352
|
+
* Also reuses evaluator scheduler context for cancellation, rate limits,
|
|
353
|
+
* and grouped grading provider calls when present.
|
|
345
354
|
*
|
|
346
|
-
*
|
|
347
|
-
*
|
|
348
|
-
*
|
|
349
|
-
* @param prompt - The prompt text
|
|
350
|
-
* @param fallbackContext - Optional fallback context (e.g., prompt for context-recall)
|
|
351
|
-
* @param providerResponse - Optional full provider response for contextTransform
|
|
352
|
-
* @returns The resolved context string or array of strings
|
|
353
|
-
* @throws Error if context cannot be resolved or transform fails
|
|
355
|
+
* IMPORTANT: Spread order matters - context is spread first, then prompt/vars
|
|
356
|
+
* override. This ensures originalProvider from context is preserved while
|
|
357
|
+
* allowing this call to specify its own prompt metadata.
|
|
354
358
|
*/
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
359
|
+
function callProviderWithContext(provider, prompt, label, vars, context) {
|
|
360
|
+
const callApiContext = {
|
|
361
|
+
...context,
|
|
362
|
+
prompt: {
|
|
363
|
+
raw: prompt,
|
|
364
|
+
label
|
|
365
|
+
},
|
|
366
|
+
vars
|
|
367
|
+
};
|
|
368
|
+
const executionContext = getProviderCallExecutionContext();
|
|
369
|
+
const callApiOptions = executionContext?.abortSignal ? { abortSignal: executionContext.abortSignal } : void 0;
|
|
370
|
+
const callApi = () => callApiOptions ? provider.callApi(prompt, callApiContext, callApiOptions) : provider.callApi(prompt, callApiContext);
|
|
371
|
+
const executeCall = () => {
|
|
372
|
+
if (executionContext?.rateLimitRegistry && !isRateLimitWrapped(provider)) return executionContext.rateLimitRegistry.execute(provider, callApi, createProviderRateLimitOptions());
|
|
373
|
+
return callApi();
|
|
374
|
+
};
|
|
375
|
+
if (executionContext?.providerCallQueue) return executionContext.providerCallQueue.enqueue(provider.id(), executeCall);
|
|
376
|
+
return executeCall();
|
|
377
|
+
}
|
|
378
|
+
async function loadFromProviderOptions(provider) {
|
|
379
|
+
invariant(typeof provider === "object", `Provider must be an object, but received a ${typeof provider}: ${provider}`);
|
|
380
|
+
invariant(!Array.isArray(provider), `Provider must be an object, but received an array: ${JSON.stringify(provider)}`);
|
|
381
|
+
invariant(provider.id, "Provider supplied to assertion must have an id");
|
|
382
|
+
return loadApiProvider(provider.id, {
|
|
383
|
+
options: provider,
|
|
384
|
+
basePath: state.basePath
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
function isSimulatedUserProviderConfig(provider) {
|
|
388
|
+
if (typeof provider === "string") return provider === "promptfoo:simulated-user";
|
|
389
|
+
if (!provider || typeof provider !== "object" || Array.isArray(provider)) return false;
|
|
390
|
+
if (typeof provider.id === "function") return provider.id() === "promptfoo:simulated-user";
|
|
391
|
+
const providerId = provider.id;
|
|
392
|
+
if (typeof providerId === "string") return providerId === "promptfoo:simulated-user";
|
|
393
|
+
return Object.values(provider).some((providerTypeConfig) => isSimulatedUserProviderConfig(providerTypeConfig));
|
|
394
|
+
}
|
|
395
|
+
async function getGradingProvider(type, provider, defaultProvider) {
|
|
396
|
+
let finalProvider;
|
|
397
|
+
if (typeof provider === "string") finalProvider = await loadApiProvider(provider, { basePath: state.basePath });
|
|
398
|
+
else if (provider != null && typeof provider === "object" && typeof provider.id === "function") finalProvider = provider;
|
|
399
|
+
else if (provider != null && typeof provider === "object") {
|
|
400
|
+
const typeValue = provider[type];
|
|
401
|
+
if (typeValue) finalProvider = await getGradingProvider(type, typeValue, defaultProvider);
|
|
402
|
+
else if (provider.id) finalProvider = await loadFromProviderOptions(provider);
|
|
403
|
+
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.`);
|
|
404
|
+
else throw new Error(`Invalid provider definition for output type '${type}': ${JSON.stringify(provider, null, 2)}`);
|
|
405
|
+
} else {
|
|
406
|
+
const defaultTest = state.config?.defaultTest;
|
|
407
|
+
const defaultTestObj = typeof defaultTest === "object" ? defaultTest : null;
|
|
408
|
+
const cfg = [
|
|
409
|
+
defaultTestObj?.provider || void 0,
|
|
410
|
+
defaultTestObj?.options?.provider?.text || void 0,
|
|
411
|
+
defaultTestObj?.options?.provider || void 0
|
|
412
|
+
].find((candidateProvider) => {
|
|
413
|
+
if (!candidateProvider) return false;
|
|
414
|
+
if (isSimulatedUserProviderConfig(candidateProvider)) {
|
|
415
|
+
logger.debug("[Grading] Skipping promptfoo:simulated-user as an implicit grader fallback");
|
|
416
|
+
return false;
|
|
364
417
|
}
|
|
365
|
-
|
|
366
|
-
}
|
|
367
|
-
} else if (fallbackContext) contextValue = fallbackContext;
|
|
368
|
-
if (assertion.contextTransform) try {
|
|
369
|
-
const outputForTransform = providerResponse?.providerTransformedOutput ?? output;
|
|
370
|
-
const transformed = await transform(assertion.contextTransform, outputForTransform, {
|
|
371
|
-
vars: test.vars,
|
|
372
|
-
prompt: { label: prompt },
|
|
373
|
-
...providerResponse && providerResponse.metadata && { metadata: providerResponse.metadata }
|
|
418
|
+
return true;
|
|
374
419
|
});
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
420
|
+
if (cfg) {
|
|
421
|
+
finalProvider = await getGradingProvider(type, cfg, defaultProvider);
|
|
422
|
+
if (finalProvider) logger.debug("[Grading] Using provider from defaultTest fallback", { providerId: finalProvider.id() });
|
|
423
|
+
} else finalProvider = defaultProvider;
|
|
379
424
|
}
|
|
380
|
-
|
|
381
|
-
return contextValue;
|
|
425
|
+
return finalProvider;
|
|
382
426
|
}
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
427
|
+
async function getAndCheckProvider(type, provider, defaultProvider, checkName) {
|
|
428
|
+
const matchedProvider = await getGradingProvider(type, provider, defaultProvider);
|
|
429
|
+
if (!matchedProvider) if (defaultProvider) {
|
|
430
|
+
logger.warn("[Grading] Falling back to default provider", {
|
|
431
|
+
checkName,
|
|
432
|
+
type
|
|
433
|
+
});
|
|
434
|
+
return defaultProvider;
|
|
435
|
+
} else throw new Error(`No provider of type ${type} found for '${checkName}'`);
|
|
436
|
+
let isValidProviderType = true;
|
|
437
|
+
if (type === "embedding") isValidProviderType = "callEmbeddingApi" in matchedProvider || "callSimilarityApi" in matchedProvider;
|
|
438
|
+
else if (type === "classification") isValidProviderType = "callClassificationApi" in matchedProvider;
|
|
439
|
+
else if (type === "moderation") isValidProviderType = "callModerationApi" in matchedProvider;
|
|
440
|
+
if (!isValidProviderType) {
|
|
441
|
+
if (provider) throw new Error(`Provider ${matchedProvider.id()} is not a valid ${type} provider for '${checkName}'`);
|
|
442
|
+
if (defaultProvider) {
|
|
443
|
+
logger.warn("[Grading] Falling back to default provider after type check failed", {
|
|
444
|
+
checkName,
|
|
445
|
+
providerId: matchedProvider.id(),
|
|
446
|
+
type
|
|
447
|
+
});
|
|
448
|
+
return defaultProvider;
|
|
449
|
+
}
|
|
450
|
+
throw new Error(`Provider ${matchedProvider.id()} is not a valid ${type} provider for '${checkName}'`);
|
|
451
|
+
}
|
|
452
|
+
return matchedProvider;
|
|
389
453
|
}
|
|
390
454
|
//#endregion
|
|
391
455
|
//#region src/assertions/utils.ts
|
|
@@ -430,223 +494,162 @@ function coerceString(value) {
|
|
|
430
494
|
return JSON.stringify(value);
|
|
431
495
|
}
|
|
432
496
|
//#endregion
|
|
433
|
-
//#region src/
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
const
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
const
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
5. John is interested in computer programming.
|
|
492
|
-
Explanation: The context states that John is pursuing a degree in Computer Science, which implies an interest in computer programming. Verdict: Yes.
|
|
493
|
-
Final verdict for each statement in order: No. No. Yes. No. Yes.
|
|
494
|
-
context:\n{{context}}
|
|
495
|
-
statements:\n{{statements|join("\\n")}}
|
|
496
|
-
Answer:
|
|
497
|
-
`;
|
|
497
|
+
//#region src/matchers/shared.ts
|
|
498
|
+
/**
|
|
499
|
+
* Normalize token usage for matcher results. Unlike the evaluator-level
|
|
500
|
+
* normalizeTokenUsage, this excludes the `assertions` field and preserves
|
|
501
|
+
* the existing completionDetails shape (passing through whatever the
|
|
502
|
+
* provider returned, or undefined if not present).
|
|
503
|
+
*/
|
|
504
|
+
function normalizeMatcherTokenUsage(tokenUsage) {
|
|
505
|
+
return {
|
|
506
|
+
total: tokenUsage?.total || 0,
|
|
507
|
+
prompt: tokenUsage?.prompt || 0,
|
|
508
|
+
completion: tokenUsage?.completion || 0,
|
|
509
|
+
cached: tokenUsage?.cached || 0,
|
|
510
|
+
numRequests: tokenUsage?.numRequests || 0,
|
|
511
|
+
completionDetails: tokenUsage?.completionDetails || {
|
|
512
|
+
reasoning: 0,
|
|
513
|
+
acceptedPrediction: 0,
|
|
514
|
+
rejectedPrediction: 0
|
|
515
|
+
}
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
function fail(reason, tokensUsed) {
|
|
519
|
+
return {
|
|
520
|
+
pass: false,
|
|
521
|
+
reason,
|
|
522
|
+
score: 0,
|
|
523
|
+
tokensUsed: normalizeMatcherTokenUsage(tokensUsed)
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
function cosineSimilarity(vecA, vecB) {
|
|
527
|
+
if (vecA.length !== vecB.length) throw new Error("Vectors must be of equal length");
|
|
528
|
+
const dotProduct = vecA.reduce((acc, val, idx) => acc + val * vecB[idx], 0);
|
|
529
|
+
const vecAMagnitude = Math.sqrt(vecA.reduce((acc, val) => acc + val * val, 0));
|
|
530
|
+
const vecBMagnitude = Math.sqrt(vecB.reduce((acc, val) => acc + val * val, 0));
|
|
531
|
+
if (vecAMagnitude === 0 || vecBMagnitude === 0) return 0;
|
|
532
|
+
return dotProduct / (vecAMagnitude * vecBMagnitude);
|
|
533
|
+
}
|
|
534
|
+
function dotProduct(vecA, vecB) {
|
|
535
|
+
if (vecA.length !== vecB.length) throw new Error("Vectors must be of equal length");
|
|
536
|
+
return vecA.reduce((acc, val, idx) => acc + val * vecB[idx], 0);
|
|
537
|
+
}
|
|
538
|
+
function euclideanDistance(vecA, vecB) {
|
|
539
|
+
if (vecA.length !== vecB.length) throw new Error("Vectors must be of equal length");
|
|
540
|
+
const sumSquaredDiff = vecA.reduce((acc, val, idx) => {
|
|
541
|
+
const diff = val - vecB[idx];
|
|
542
|
+
return acc + diff * diff;
|
|
543
|
+
}, 0);
|
|
544
|
+
return Math.sqrt(sumSquaredDiff);
|
|
545
|
+
}
|
|
546
|
+
function tryParse(content) {
|
|
547
|
+
try {
|
|
548
|
+
return JSON.parse(content);
|
|
549
|
+
} catch {}
|
|
550
|
+
return content;
|
|
551
|
+
}
|
|
552
|
+
function splitIntoSentences(text) {
|
|
553
|
+
return text.split("\n").filter((sentence) => sentence.trim() !== "");
|
|
554
|
+
}
|
|
498
555
|
//#endregion
|
|
499
|
-
//#region src/
|
|
500
|
-
const
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
<Output>Hello world</Output>
|
|
507
|
-
<Rubric>Content contains a greeting</Rubric>
|
|
508
|
-
{"reason": "the content contains the word 'Hello'", "pass": true, "score": 1.0}
|
|
509
|
-
|
|
510
|
-
<Output>Avast ye swabs, repel the invaders!</Output>
|
|
511
|
-
<Rubric>Does not speak like a pirate</Rubric>
|
|
512
|
-
{"reason": "'avast ye' is a common pirate term", "pass": false, "score": 0.0}`
|
|
513
|
-
}, {
|
|
514
|
-
role: "user",
|
|
515
|
-
content: "<Output>\n{{ output }}\n</Output>\n<Rubric>\n{{ rubric }}\n</Rubric>"
|
|
516
|
-
}]);
|
|
517
|
-
const PROMPTFOO_FACTUALITY_PROMPT = JSON.stringify([{
|
|
518
|
-
role: "system",
|
|
519
|
-
content: dedent`
|
|
520
|
-
You are a precise factuality evaluator that compares a submitted answer to an expert answer.
|
|
521
|
-
|
|
522
|
-
Your task is to analyze the factual content while ignoring differences in style, grammar, or punctuation.
|
|
523
|
-
You must categorize the submission into one of these options:
|
|
524
|
-
|
|
525
|
-
(A) The submitted answer is a subset of the expert answer and is fully consistent with it.
|
|
526
|
-
(B) The submitted answer is a superset of the expert answer and is fully consistent with it.
|
|
527
|
-
(C) The submitted answer contains all the same details as the expert answer.
|
|
528
|
-
(D) There is a disagreement between the submitted answer and the expert answer.
|
|
529
|
-
(E) The answers differ, but these differences don't matter from the perspective of factuality.
|
|
530
|
-
|
|
531
|
-
Respond ONLY with a JSON object in this format:
|
|
532
|
-
{
|
|
533
|
-
"category": "[LETTER]",
|
|
534
|
-
"reason": "[DETAILED EXPLANATION]"
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
- The "category" must be a single letter A, B, C, D, or E.
|
|
538
|
-
- Provide a clear, detailed explanation in the "reason" field.
|
|
539
|
-
- Your response must be valid JSON with no additional text.`
|
|
540
|
-
}, {
|
|
541
|
-
role: "user",
|
|
542
|
-
content: dedent`
|
|
543
|
-
I need you to compare these answers:
|
|
544
|
-
|
|
545
|
-
<question>
|
|
546
|
-
{{input}}
|
|
547
|
-
</question>
|
|
548
|
-
|
|
549
|
-
<expert_answer>
|
|
550
|
-
{{ideal}}
|
|
551
|
-
</expert_answer>
|
|
552
|
-
|
|
553
|
-
<submitted_answer>
|
|
554
|
-
{{completion}}
|
|
555
|
-
</submitted_answer>
|
|
556
|
-
|
|
557
|
-
Please analyze the factual relationship between these answers according to the categories you've been given.`
|
|
558
|
-
}]);
|
|
559
|
-
const OPENAI_CLOSED_QA_PROMPT = JSON.stringify([{
|
|
560
|
-
role: "system",
|
|
561
|
-
content: `You are assessing a submitted answer on a given task based on a criterion. Here is the data:
|
|
562
|
-
[BEGIN DATA]
|
|
563
|
-
***
|
|
564
|
-
[Task]: {{input}}
|
|
565
|
-
***
|
|
566
|
-
[Submission]: {{completion}}
|
|
567
|
-
***
|
|
568
|
-
[Criterion]: {{criteria}}
|
|
569
|
-
***
|
|
570
|
-
[END DATA]
|
|
571
|
-
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.
|
|
572
|
-
|
|
573
|
-
Reasoning:`
|
|
574
|
-
}]);
|
|
575
|
-
const SUGGEST_PROMPTS_SYSTEM_MESSAGE = {
|
|
576
|
-
role: "system",
|
|
577
|
-
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.
|
|
578
|
-
|
|
579
|
-
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.
|
|
580
|
-
|
|
581
|
-
Your output is going to be copied directly into the program. It should contain the prompt ONLY`
|
|
556
|
+
//#region src/matchers/rubric.ts
|
|
557
|
+
const nunjucks = getNunjucksEngine(void 0, false, true);
|
|
558
|
+
var LlmRubricProviderError = class extends Error {
|
|
559
|
+
constructor(message) {
|
|
560
|
+
super(message);
|
|
561
|
+
this.name = "LlmRubricProviderError";
|
|
562
|
+
}
|
|
582
563
|
};
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
{
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
}
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
564
|
+
async function loadRubricPrompt(rubricPrompt, defaultPrompt) {
|
|
565
|
+
if (!rubricPrompt) return defaultPrompt;
|
|
566
|
+
if (typeof rubricPrompt === "object" && Object.keys(rubricPrompt).length === 0) return defaultPrompt;
|
|
567
|
+
if (typeof rubricPrompt === "string" && rubricPrompt.startsWith("file://")) {
|
|
568
|
+
const basePath = state.basePath || "";
|
|
569
|
+
const { filePath, functionName } = parseFileUrl(getNunjucksEngineForFilePath().renderString(rubricPrompt, {}));
|
|
570
|
+
const resolvedPath = path.resolve(basePath, filePath);
|
|
571
|
+
if (isJavascriptFile(filePath)) rubricPrompt = await loadFromJavaScriptFile(resolvedPath, functionName, []);
|
|
572
|
+
else {
|
|
573
|
+
if (!fs$2.existsSync(resolvedPath)) throw new Error(`File does not exist: ${resolvedPath}`);
|
|
574
|
+
rubricPrompt = fs$2.readFileSync(resolvedPath, "utf8");
|
|
575
|
+
}
|
|
576
|
+
} else rubricPrompt = maybeLoadFromExternalFile(rubricPrompt);
|
|
577
|
+
if (typeof rubricPrompt === "object") rubricPrompt = JSON.stringify(rubricPrompt);
|
|
578
|
+
invariant(typeof rubricPrompt === "string", "rubricPrompt must be a string");
|
|
579
|
+
return rubricPrompt;
|
|
580
|
+
}
|
|
581
|
+
function processContextForTemplating(context, enableObjectAccess) {
|
|
582
|
+
if (enableObjectAccess) return context;
|
|
583
|
+
return Object.fromEntries(Object.entries(context).map(([key, value]) => {
|
|
584
|
+
if (value && typeof value === "object") {
|
|
585
|
+
if (Array.isArray(value)) return [key, value.map((item) => item && typeof item === "object" ? JSON.stringify(item) : item)];
|
|
586
|
+
return [key, JSON.stringify(value)];
|
|
587
|
+
}
|
|
588
|
+
return [key, value];
|
|
589
|
+
}));
|
|
590
|
+
}
|
|
591
|
+
async function renderLlmRubricPrompt(rubricPrompt, context) {
|
|
592
|
+
const processedContext = processContextForTemplating(context, getEnvBool("PROMPTFOO_DISABLE_OBJECT_STRINGIFY", false));
|
|
593
|
+
try {
|
|
594
|
+
const parsed = JSON.parse(rubricPrompt, (_k, v) => typeof v === "string" ? nunjucks.renderString(v, processedContext) : v);
|
|
595
|
+
return JSON.stringify(parsed);
|
|
596
|
+
} catch (err) {
|
|
597
|
+
logger.debug(`[Rubric] Rubric prompt is not valid JSON, using Nunjucks rendering: ${err.message}`);
|
|
598
|
+
}
|
|
599
|
+
return nunjucks.renderString(rubricPrompt, processedContext);
|
|
600
|
+
}
|
|
601
|
+
function parseJsonGradingResponse(label, resp) {
|
|
602
|
+
let jsonObjects = [];
|
|
603
|
+
if (typeof resp.output === "string") try {
|
|
604
|
+
jsonObjects = extractJsonObjects(resp.output);
|
|
605
|
+
if (jsonObjects.length === 0) return { failure: fail(`Could not extract JSON from ${label} response`, resp.tokenUsage) };
|
|
606
|
+
} catch (err) {
|
|
607
|
+
return { failure: fail(`${label} produced malformed response: ${err}\n\n${resp.output}`, resp.tokenUsage) };
|
|
608
|
+
}
|
|
609
|
+
else if (typeof resp.output === "object" && resp.output !== null && !Array.isArray(resp.output)) jsonObjects = [resp.output];
|
|
610
|
+
else return { failure: fail(`${label} produced malformed response - output must be string or object. Output: ${JSON.stringify(resp.output)}`, resp.tokenUsage) };
|
|
611
|
+
const parsed = jsonObjects[0];
|
|
612
|
+
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) };
|
|
613
|
+
return { parsed };
|
|
614
|
+
}
|
|
615
|
+
async function runJsonGradingPrompt({ assertion, checkName, defaultPrompt, grading, label, providerCallContext, throwOnError, vars }) {
|
|
616
|
+
const prompt = await renderLlmRubricPrompt(await loadRubricPrompt(grading.rubricPrompt, defaultPrompt), vars);
|
|
617
|
+
const defaultProviders = await getDefaultProviders();
|
|
618
|
+
const defaultProvider = defaultProviders.llmRubricProvider || defaultProviders.gradingJsonProvider;
|
|
619
|
+
const resp = await callProviderWithContext(await getAndCheckProvider("text", grading.provider, defaultProvider, checkName), prompt, label, vars, providerCallContext);
|
|
620
|
+
if (resp.error || !resp.output) {
|
|
621
|
+
if (throwOnError) throw new Error(resp.error || "No output");
|
|
622
|
+
return fail(resp.error || "No output", resp.tokenUsage);
|
|
623
|
+
}
|
|
624
|
+
const { parsed, failure } = parseJsonGradingResponse(label, resp);
|
|
625
|
+
if (!parsed) return failure;
|
|
626
|
+
let pass = parsed.pass ?? true;
|
|
627
|
+
if (typeof pass !== "boolean") pass = /^(true|yes|pass|y)$/i.test(String(pass));
|
|
628
|
+
let score = parsed.score;
|
|
629
|
+
if (typeof score !== "number") score = Number.isFinite(Number(score)) ? Number(score) : Number(pass);
|
|
630
|
+
const threshold = typeof assertion?.threshold === "string" ? Number(assertion.threshold) : assertion?.threshold;
|
|
631
|
+
if (typeof threshold === "number" && Number.isFinite(threshold)) pass = pass && score >= threshold;
|
|
632
|
+
const reason = parsed.reason || (pass ? "Grading passed" : `Score ${score} below threshold ${threshold}`);
|
|
633
|
+
let responseMetadata = {};
|
|
634
|
+
if (resp.metadata && typeof resp.metadata === "object" && !Array.isArray(resp.metadata)) {
|
|
635
|
+
const serializedMetadata = safeJsonStringify(resp.metadata);
|
|
636
|
+
responseMetadata = serializedMetadata ? JSON.parse(serializedMetadata) : {};
|
|
637
|
+
}
|
|
638
|
+
return {
|
|
639
|
+
assertion,
|
|
640
|
+
pass,
|
|
641
|
+
score,
|
|
642
|
+
reason,
|
|
643
|
+
tokensUsed: normalizeMatcherTokenUsage({
|
|
644
|
+
...resp.tokenUsage,
|
|
645
|
+
completionDetails: resp.tokenUsage?.completionDetails || parsed.tokensUsed?.completionDetails
|
|
646
|
+
}),
|
|
647
|
+
metadata: {
|
|
648
|
+
...responseMetadata,
|
|
649
|
+
renderedGradingPrompt: prompt
|
|
650
|
+
}
|
|
651
|
+
};
|
|
652
|
+
}
|
|
650
653
|
//#endregion
|
|
651
654
|
//#region src/prompts/processors/csv.ts
|
|
652
655
|
/**
|
|
@@ -939,97 +942,315 @@ const pythonPromptFunctionLegacy = async (filePath, context) => {
|
|
|
939
942
|
logger.debug(`Python prompt script ${filePath} returned: ${results}`);
|
|
940
943
|
return results;
|
|
941
944
|
};
|
|
942
|
-
/**
|
|
943
|
-
* Processes a Python file to extract or execute a function as a prompt.
|
|
944
|
-
* @param filePath - Path to the Python file.
|
|
945
|
-
* @param prompt - The raw prompt data.
|
|
946
|
-
* @param functionName - Optional function name to execute.
|
|
947
|
-
* @returns Array of prompts extracted or executed from the file.
|
|
948
|
-
*/
|
|
949
|
-
function processPythonFile(filePath, prompt, functionName) {
|
|
950
|
-
const fileContent = fs$2.readFileSync(filePath, "utf-8");
|
|
951
|
-
return [{
|
|
952
|
-
raw: fileContent,
|
|
953
|
-
label: prompt.label ?? (functionName ? `${filePath}:${functionName}` : `${filePath}: ${fileContent}`),
|
|
954
|
-
function: functionName ? (context) => pythonPromptFunction(filePath, functionName, {
|
|
955
|
-
...context,
|
|
956
|
-
config: prompt.config
|
|
957
|
-
}) : (context) => pythonPromptFunctionLegacy(filePath, {
|
|
958
|
-
...context,
|
|
959
|
-
config: prompt.config
|
|
960
|
-
}),
|
|
961
|
-
config: prompt.config
|
|
962
|
-
}];
|
|
963
|
-
}
|
|
964
|
-
//#endregion
|
|
965
|
-
//#region src/prompts/processors/string.ts
|
|
966
|
-
/**
|
|
967
|
-
* Processes a string as a literal prompt.
|
|
968
|
-
* @param prompt - The raw prompt data.
|
|
969
|
-
* @returns Array of prompts created from the string.
|
|
970
|
-
*/
|
|
971
|
-
function processString(prompt) {
|
|
972
|
-
invariant(typeof prompt.raw === "string", `prompt.raw must be a string, but got ${JSON.stringify(prompt.raw)}`);
|
|
973
|
-
return [{
|
|
974
|
-
id: prompt.id,
|
|
975
|
-
raw: prompt.raw,
|
|
976
|
-
label: prompt.label ?? `${prompt.raw}`,
|
|
977
|
-
config: prompt.config
|
|
978
|
-
}];
|
|
979
|
-
}
|
|
980
|
-
//#endregion
|
|
981
|
-
//#region src/prompts/processors/text.ts
|
|
982
|
-
/**
|
|
983
|
-
* Processes a text file to extract prompts, splitting by a delimiter.
|
|
984
|
-
* @param filePath - Path to the text file.
|
|
985
|
-
* @param prompt - The raw prompt data.
|
|
986
|
-
* @returns Array of prompts extracted from the file.
|
|
987
|
-
*/
|
|
988
|
-
function processTxtFile(filePath, { label }) {
|
|
989
|
-
const lines = fs$2.readFileSync(filePath, "utf-8").split(/\r?\n/);
|
|
990
|
-
const prompts = [];
|
|
991
|
-
let buffer = [];
|
|
992
|
-
const flush = () => {
|
|
993
|
-
const raw = buffer.join("\n").trim();
|
|
994
|
-
if (raw.length > 0) prompts.push({
|
|
995
|
-
raw,
|
|
996
|
-
label: label ? `${label}: ${filePath}: ${raw}` : `${filePath}: ${raw}`
|
|
997
|
-
});
|
|
998
|
-
buffer = [];
|
|
999
|
-
};
|
|
1000
|
-
for (const line of lines) if (line.trim() === PROMPT_DELIMITER) flush();
|
|
1001
|
-
else buffer.push(line);
|
|
1002
|
-
flush();
|
|
1003
|
-
return prompts;
|
|
1004
|
-
}
|
|
1005
|
-
//#endregion
|
|
1006
|
-
//#region src/prompts/processors/yaml.ts
|
|
1007
|
-
/**
|
|
1008
|
-
* Processes a YAML file to extract prompts.
|
|
1009
|
-
* This function reads a YAML file, parses it, and maps each entry to a `Prompt` object.
|
|
1010
|
-
* Each prompt is labeled with the file path and the YAML content.
|
|
1011
|
-
* Any file:// references within the YAML content are recursively resolved.
|
|
1012
|
-
*
|
|
1013
|
-
* @param filePath - The path to the YAML file.
|
|
1014
|
-
* @param prompt - The raw prompt data, used for labeling.
|
|
1015
|
-
* @returns An array of `Prompt` objects extracted from the YAML file.
|
|
1016
|
-
* @throws Will throw an error if the file cannot be read or parsed.
|
|
1017
|
-
*/
|
|
1018
|
-
function processYamlFile(filePath, prompt) {
|
|
1019
|
-
const fileContents = fs$2.readFileSync(filePath, "utf8");
|
|
1020
|
-
let maybeParsed = fileContents;
|
|
1021
|
-
try {
|
|
1022
|
-
const resolved = maybeLoadConfigFromExternalFile(yaml.load(fileContents));
|
|
1023
|
-
maybeParsed = JSON.stringify(resolved);
|
|
1024
|
-
} catch (e) {
|
|
1025
|
-
logger.debug(`Error parsing YAML file ${filePath}: ${e}`);
|
|
1026
|
-
}
|
|
1027
|
-
return [{
|
|
1028
|
-
raw: maybeParsed,
|
|
1029
|
-
label: prompt.label || `${filePath}: ${maybeParsed?.slice(0, 80)}`,
|
|
1030
|
-
config: prompt.config
|
|
1031
|
-
}];
|
|
1032
|
-
}
|
|
945
|
+
/**
|
|
946
|
+
* Processes a Python file to extract or execute a function as a prompt.
|
|
947
|
+
* @param filePath - Path to the Python file.
|
|
948
|
+
* @param prompt - The raw prompt data.
|
|
949
|
+
* @param functionName - Optional function name to execute.
|
|
950
|
+
* @returns Array of prompts extracted or executed from the file.
|
|
951
|
+
*/
|
|
952
|
+
function processPythonFile(filePath, prompt, functionName) {
|
|
953
|
+
const fileContent = fs$2.readFileSync(filePath, "utf-8");
|
|
954
|
+
return [{
|
|
955
|
+
raw: fileContent,
|
|
956
|
+
label: prompt.label ?? (functionName ? `${filePath}:${functionName}` : `${filePath}: ${fileContent}`),
|
|
957
|
+
function: functionName ? (context) => pythonPromptFunction(filePath, functionName, {
|
|
958
|
+
...context,
|
|
959
|
+
config: prompt.config
|
|
960
|
+
}) : (context) => pythonPromptFunctionLegacy(filePath, {
|
|
961
|
+
...context,
|
|
962
|
+
config: prompt.config
|
|
963
|
+
}),
|
|
964
|
+
config: prompt.config
|
|
965
|
+
}];
|
|
966
|
+
}
|
|
967
|
+
//#endregion
|
|
968
|
+
//#region src/prompts/processors/string.ts
|
|
969
|
+
/**
|
|
970
|
+
* Processes a string as a literal prompt.
|
|
971
|
+
* @param prompt - The raw prompt data.
|
|
972
|
+
* @returns Array of prompts created from the string.
|
|
973
|
+
*/
|
|
974
|
+
function processString(prompt) {
|
|
975
|
+
invariant(typeof prompt.raw === "string", `prompt.raw must be a string, but got ${JSON.stringify(prompt.raw)}`);
|
|
976
|
+
return [{
|
|
977
|
+
id: prompt.id,
|
|
978
|
+
raw: prompt.raw,
|
|
979
|
+
label: prompt.label ?? `${prompt.raw}`,
|
|
980
|
+
config: prompt.config
|
|
981
|
+
}];
|
|
982
|
+
}
|
|
983
|
+
//#endregion
|
|
984
|
+
//#region src/prompts/processors/text.ts
|
|
985
|
+
/**
|
|
986
|
+
* Processes a text file to extract prompts, splitting by a delimiter.
|
|
987
|
+
* @param filePath - Path to the text file.
|
|
988
|
+
* @param prompt - The raw prompt data.
|
|
989
|
+
* @returns Array of prompts extracted from the file.
|
|
990
|
+
*/
|
|
991
|
+
function processTxtFile(filePath, { label }) {
|
|
992
|
+
const lines = fs$2.readFileSync(filePath, "utf-8").split(/\r?\n/);
|
|
993
|
+
const prompts = [];
|
|
994
|
+
let buffer = [];
|
|
995
|
+
const flush = () => {
|
|
996
|
+
const raw = buffer.join("\n").trim();
|
|
997
|
+
if (raw.length > 0) prompts.push({
|
|
998
|
+
raw,
|
|
999
|
+
label: label ? `${label}: ${filePath}: ${raw}` : `${filePath}: ${raw}`
|
|
1000
|
+
});
|
|
1001
|
+
buffer = [];
|
|
1002
|
+
};
|
|
1003
|
+
for (const line of lines) if (line.trim() === PROMPT_DELIMITER) flush();
|
|
1004
|
+
else buffer.push(line);
|
|
1005
|
+
flush();
|
|
1006
|
+
return prompts;
|
|
1007
|
+
}
|
|
1008
|
+
//#endregion
|
|
1009
|
+
//#region src/prompts/processors/yaml.ts
|
|
1010
|
+
/**
|
|
1011
|
+
* Processes a YAML file to extract prompts.
|
|
1012
|
+
* This function reads a YAML file, parses it, and maps each entry to a `Prompt` object.
|
|
1013
|
+
* Each prompt is labeled with the file path and the YAML content.
|
|
1014
|
+
* Any file:// references within the YAML content are recursively resolved.
|
|
1015
|
+
*
|
|
1016
|
+
* @param filePath - The path to the YAML file.
|
|
1017
|
+
* @param prompt - The raw prompt data, used for labeling.
|
|
1018
|
+
* @returns An array of `Prompt` objects extracted from the YAML file.
|
|
1019
|
+
* @throws Will throw an error if the file cannot be read or parsed.
|
|
1020
|
+
*/
|
|
1021
|
+
function processYamlFile(filePath, prompt) {
|
|
1022
|
+
const fileContents = fs$2.readFileSync(filePath, "utf8");
|
|
1023
|
+
let maybeParsed = fileContents;
|
|
1024
|
+
try {
|
|
1025
|
+
const resolved = maybeLoadConfigFromExternalFile(yaml.load(fileContents));
|
|
1026
|
+
maybeParsed = JSON.stringify(resolved);
|
|
1027
|
+
} catch (e) {
|
|
1028
|
+
logger.debug(`Error parsing YAML file ${filePath}: ${e}`);
|
|
1029
|
+
}
|
|
1030
|
+
return [{
|
|
1031
|
+
raw: maybeParsed,
|
|
1032
|
+
label: prompt.label || `${filePath}: ${maybeParsed?.slice(0, 80)}`,
|
|
1033
|
+
config: prompt.config
|
|
1034
|
+
}];
|
|
1035
|
+
}
|
|
1036
|
+
//#endregion
|
|
1037
|
+
//#region src/external/prompts/ragas.ts
|
|
1038
|
+
const ANSWER_RELEVANCY_GENERATE = `Generate question for the given answer.
|
|
1039
|
+
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
|
|
1040
|
+
Question: When is the scheduled launch date and time for the PSLV-C56 mission, and where will it be launched from?
|
|
1041
|
+
|
|
1042
|
+
Answer:{{answer}}
|
|
1043
|
+
Question:`;
|
|
1044
|
+
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.
|
|
1045
|
+
Think in steps and reason before coming to conclusion.
|
|
1046
|
+
|
|
1047
|
+
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.
|
|
1048
|
+
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
|
|
1049
|
+
classification
|
|
1050
|
+
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]
|
|
1051
|
+
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]
|
|
1052
|
+
3. He published 4 papers in 1905. There is no mention about papers he wrote in given the context. So [Not Attributed]
|
|
1053
|
+
4. Einstein moved to Switzerland in 1895. There is not supporting evidence for this in the given the context. So [Not Attributed]
|
|
1054
|
+
|
|
1055
|
+
context:{{context}}
|
|
1056
|
+
answer:{{groundTruth}}
|
|
1057
|
+
classification:
|
|
1058
|
+
`;
|
|
1059
|
+
const CONTEXT_RECALL_ATTRIBUTED_TOKEN = "[Attributed]";
|
|
1060
|
+
const CONTEXT_RECALL_NOT_ATTRIBUTED_TOKEN = "[Not Attributed]";
|
|
1061
|
+
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.
|
|
1062
|
+
|
|
1063
|
+
query: {{query}}
|
|
1064
|
+
context: {{context}}
|
|
1065
|
+
candidate sentences:
|
|
1066
|
+
`;
|
|
1067
|
+
const CONTEXT_RELEVANCE_BAD = "Insufficient Information";
|
|
1068
|
+
const CONTEXT_FAITHFULNESS_LONGFORM = `Given a question and answer, create one or more statements from each sentence in the given answer.
|
|
1069
|
+
question: Who was Albert Einstein and what is he best known for?
|
|
1070
|
+
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.
|
|
1071
|
+
statements:\nAlbert Einstein was born in Germany.\nAlbert Einstein was best known for his theory of relativity.
|
|
1072
|
+
question: Cadmium Chloride is slightly soluble in this chemical, it is also called what?
|
|
1073
|
+
answer: alcohol
|
|
1074
|
+
statements:\nCadmium Chloride is slightly soluble in alcohol.
|
|
1075
|
+
question: Were Shahul and Jithin of the same nationality?
|
|
1076
|
+
answer: They were from different countries.
|
|
1077
|
+
statements:\nShahul and Jithin were from different countries.
|
|
1078
|
+
question:{{question}}
|
|
1079
|
+
answer: {{answer}}
|
|
1080
|
+
statements:\n`;
|
|
1081
|
+
const CONTEXT_FAITHFULNESS_NLI_STATEMENTS = `Prompt: Natural language inference
|
|
1082
|
+
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.
|
|
1083
|
+
|
|
1084
|
+
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.
|
|
1085
|
+
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
|
|
1086
|
+
Answer:
|
|
1087
|
+
1. John is majoring in Biology.
|
|
1088
|
+
Explanation: John's major is explicitly mentioned as Computer Science. There is no information suggesting he is majoring in Biology. Verdict: No.
|
|
1089
|
+
2. John is taking a course on Artificial Intelligence.
|
|
1090
|
+
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.
|
|
1091
|
+
3. John is a dedicated student.
|
|
1092
|
+
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.
|
|
1093
|
+
4. John has a part-time job.
|
|
1094
|
+
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.
|
|
1095
|
+
5. John is interested in computer programming.
|
|
1096
|
+
Explanation: The context states that John is pursuing a degree in Computer Science, which implies an interest in computer programming. Verdict: Yes.
|
|
1097
|
+
Final verdict for each statement in order: No. No. Yes. No. Yes.
|
|
1098
|
+
context:\n{{context}}
|
|
1099
|
+
statements:\n{{statements|join("\\n")}}
|
|
1100
|
+
Answer:
|
|
1101
|
+
`;
|
|
1102
|
+
//#endregion
|
|
1103
|
+
//#region src/prompts/grading.ts
|
|
1104
|
+
const DEFAULT_GRADING_PROMPT = JSON.stringify([{
|
|
1105
|
+
role: "system",
|
|
1106
|
+
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}
|
|
1107
|
+
|
|
1108
|
+
Examples:
|
|
1109
|
+
|
|
1110
|
+
<Output>Hello world</Output>
|
|
1111
|
+
<Rubric>Content contains a greeting</Rubric>
|
|
1112
|
+
{"reason": "the content contains the word 'Hello'", "pass": true, "score": 1.0}
|
|
1113
|
+
|
|
1114
|
+
<Output>Avast ye swabs, repel the invaders!</Output>
|
|
1115
|
+
<Rubric>Does not speak like a pirate</Rubric>
|
|
1116
|
+
{"reason": "'avast ye' is a common pirate term", "pass": false, "score": 0.0}`
|
|
1117
|
+
}, {
|
|
1118
|
+
role: "user",
|
|
1119
|
+
content: "<Output>\n{{ output }}\n</Output>\n<Rubric>\n{{ rubric }}\n</Rubric>"
|
|
1120
|
+
}]);
|
|
1121
|
+
const PROMPTFOO_FACTUALITY_PROMPT = JSON.stringify([{
|
|
1122
|
+
role: "system",
|
|
1123
|
+
content: dedent`
|
|
1124
|
+
You are a precise factuality evaluator that compares a submitted answer to an expert answer.
|
|
1125
|
+
|
|
1126
|
+
Your task is to analyze the factual content while ignoring differences in style, grammar, or punctuation.
|
|
1127
|
+
You must categorize the submission into one of these options:
|
|
1128
|
+
|
|
1129
|
+
(A) The submitted answer is a subset of the expert answer and is fully consistent with it.
|
|
1130
|
+
(B) The submitted answer is a superset of the expert answer and is fully consistent with it.
|
|
1131
|
+
(C) The submitted answer contains all the same details as the expert answer.
|
|
1132
|
+
(D) There is a disagreement between the submitted answer and the expert answer.
|
|
1133
|
+
(E) The answers differ, but these differences don't matter from the perspective of factuality.
|
|
1134
|
+
|
|
1135
|
+
Respond ONLY with a JSON object in this format:
|
|
1136
|
+
{
|
|
1137
|
+
"category": "[LETTER]",
|
|
1138
|
+
"reason": "[DETAILED EXPLANATION]"
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
- The "category" must be a single letter A, B, C, D, or E.
|
|
1142
|
+
- Provide a clear, detailed explanation in the "reason" field.
|
|
1143
|
+
- Your response must be valid JSON with no additional text.`
|
|
1144
|
+
}, {
|
|
1145
|
+
role: "user",
|
|
1146
|
+
content: dedent`
|
|
1147
|
+
I need you to compare these answers:
|
|
1148
|
+
|
|
1149
|
+
<question>
|
|
1150
|
+
{{input}}
|
|
1151
|
+
</question>
|
|
1152
|
+
|
|
1153
|
+
<expert_answer>
|
|
1154
|
+
{{ideal}}
|
|
1155
|
+
</expert_answer>
|
|
1156
|
+
|
|
1157
|
+
<submitted_answer>
|
|
1158
|
+
{{completion}}
|
|
1159
|
+
</submitted_answer>
|
|
1160
|
+
|
|
1161
|
+
Please analyze the factual relationship between these answers according to the categories you've been given.`
|
|
1162
|
+
}]);
|
|
1163
|
+
const OPENAI_CLOSED_QA_PROMPT = JSON.stringify([{
|
|
1164
|
+
role: "system",
|
|
1165
|
+
content: `You are assessing a submitted answer on a given task based on a criterion. Here is the data:
|
|
1166
|
+
[BEGIN DATA]
|
|
1167
|
+
***
|
|
1168
|
+
[Task]: {{input}}
|
|
1169
|
+
***
|
|
1170
|
+
[Submission]: {{completion}}
|
|
1171
|
+
***
|
|
1172
|
+
[Criterion]: {{criteria}}
|
|
1173
|
+
***
|
|
1174
|
+
[END DATA]
|
|
1175
|
+
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.
|
|
1176
|
+
|
|
1177
|
+
Reasoning:`
|
|
1178
|
+
}]);
|
|
1179
|
+
const SUGGEST_PROMPTS_SYSTEM_MESSAGE = {
|
|
1180
|
+
role: "system",
|
|
1181
|
+
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.
|
|
1182
|
+
|
|
1183
|
+
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.
|
|
1184
|
+
|
|
1185
|
+
Your output is going to be copied directly into the program. It should contain the prompt ONLY`
|
|
1186
|
+
};
|
|
1187
|
+
const SELECT_BEST_PROMPT = JSON.stringify([{
|
|
1188
|
+
role: "system",
|
|
1189
|
+
content: `You are comparing multiple pieces of text to see which best fits the following criteria: {{criteria}}
|
|
1190
|
+
|
|
1191
|
+
Here are the pieces of text:
|
|
1192
|
+
|
|
1193
|
+
{% for output in outputs %}
|
|
1194
|
+
<Text index="{{ loop.index0 }}">
|
|
1195
|
+
{{ output }}
|
|
1196
|
+
</Text>
|
|
1197
|
+
{% endfor %}
|
|
1198
|
+
|
|
1199
|
+
Output the index of the text that best fits the criteria. You must output a single integer.`
|
|
1200
|
+
}]);
|
|
1201
|
+
const DEFAULT_WEB_SEARCH_PROMPT = JSON.stringify([{
|
|
1202
|
+
role: "system",
|
|
1203
|
+
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}
|
|
1204
|
+
|
|
1205
|
+
You MUST search the web when:
|
|
1206
|
+
- The rubric asks about current information (prices, weather, news, etc.)
|
|
1207
|
+
- Facts need to be verified against recent data
|
|
1208
|
+
- The rubric references time-sensitive information
|
|
1209
|
+
|
|
1210
|
+
Examples:
|
|
1211
|
+
|
|
1212
|
+
<Output>The current CEO of Microsoft is Satya Nadella</Output>
|
|
1213
|
+
<Rubric>Contains accurate information about Microsoft's leadership</Rubric>
|
|
1214
|
+
{"reason": "I searched and confirmed Satya Nadella is indeed the current CEO of Microsoft", "pass": true, "score": 1.0}
|
|
1215
|
+
|
|
1216
|
+
<Output>Bitcoin is trading at $45,000</Output>
|
|
1217
|
+
<Rubric>Provides current Bitcoin price within 10% accuracy</Rubric>
|
|
1218
|
+
{"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}`
|
|
1219
|
+
}, {
|
|
1220
|
+
role: "user",
|
|
1221
|
+
content: "<Output>\n{{ output }}\n</Output>\n<Rubric>\n{{ rubric }}\n</Rubric>"
|
|
1222
|
+
}]);
|
|
1223
|
+
const TRAJECTORY_GOAL_SUCCESS_PROMPT = JSON.stringify([{
|
|
1224
|
+
role: "system",
|
|
1225
|
+
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}
|
|
1226
|
+
|
|
1227
|
+
Judge end-to-end success, not stylistic perfection.
|
|
1228
|
+
Use the trajectory as evidence for what the agent actually did.
|
|
1229
|
+
Give partial credit when the agent made progress but did not fully achieve the goal.
|
|
1230
|
+
|
|
1231
|
+
Examples:
|
|
1232
|
+
|
|
1233
|
+
<Goal>Find the order status and tell the user whether it has shipped</Goal>
|
|
1234
|
+
<Trajectory>{"stepCount":2,"steps":[{"index":1,"type":"tool","name":"search_orders"},{"index":2,"type":"message","name":"agent response"}]}</Trajectory>
|
|
1235
|
+
<Output>Your order shipped yesterday and should arrive on Tuesday.</Output>
|
|
1236
|
+
{"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}
|
|
1237
|
+
|
|
1238
|
+
<Goal>Find the order status and tell the user whether it has shipped</Goal>
|
|
1239
|
+
<Trajectory>{"stepCount":1,"steps":[{"index":1,"type":"message","name":"agent response"}]}</Trajectory>
|
|
1240
|
+
<Output>I cannot check your order right now.</Output>
|
|
1241
|
+
{"reason":"The agent did not show evidence of checking the order and did not provide the requested status.","pass":false,"score":0.0}`
|
|
1242
|
+
}, {
|
|
1243
|
+
role: "user",
|
|
1244
|
+
content: dedent`<Goal>
|
|
1245
|
+
{{ goal }}
|
|
1246
|
+
</Goal>
|
|
1247
|
+
<Trajectory>
|
|
1248
|
+
{{ trajectory }}
|
|
1249
|
+
</Trajectory>
|
|
1250
|
+
<Output>
|
|
1251
|
+
{{ output }}
|
|
1252
|
+
</Output>`
|
|
1253
|
+
}]);
|
|
1033
1254
|
//#endregion
|
|
1034
1255
|
//#region src/prompts/index.ts
|
|
1035
1256
|
/**
|
|
@@ -1165,164 +1386,44 @@ IMPORTANT:
|
|
|
1165
1386
|
Format:
|
|
1166
1387
|
{"steps": <list_of_strings>}
|
|
1167
1388
|
|
|
1168
|
-
Example:
|
|
1169
|
-
{"steps":["<Evaluation Step 1>","<Evaluation Step 2>","<Evaluation Step 3>","<Evaluation Step 4>"]}
|
|
1170
|
-
|
|
1171
|
-
Here are the 3-4 concise evaluation steps, formatted as required in a minified JSON:
|
|
1172
|
-
JSON:
|
|
1173
|
-
`;
|
|
1174
|
-
const GEVAL_PROMPT_EVALUATE = `
|
|
1175
|
-
You will be given one Reply for a Prompt below. Your task is to rate the Reply on one metric.
|
|
1176
|
-
Please make sure you read and understand these instructions carefully. Please keep this document open while reviewing, and refer to it as needed.
|
|
1177
|
-
|
|
1178
|
-
**Evaluation Criteria**
|
|
1179
|
-
{{criteria}}
|
|
1180
|
-
|
|
1181
|
-
**Evaluation Steps**
|
|
1182
|
-
- {{steps}}
|
|
1183
|
-
Given the evaluation steps, return a JSON with two keys:
|
|
1184
|
-
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;
|
|
1185
|
-
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!
|
|
1186
|
-
|
|
1187
|
-
**Prompt**
|
|
1188
|
-
{{input}}
|
|
1189
|
-
|
|
1190
|
-
**Reply**
|
|
1191
|
-
{{output}}
|
|
1192
|
-
|
|
1193
|
-
**OUTPUT FORMAT**
|
|
1194
|
-
IMPORTANT:
|
|
1195
|
-
- Return output ONLY as a minified JSON object (no code fences).
|
|
1196
|
-
- The JSON object must contain exactly two keys: "score" and "reason".
|
|
1197
|
-
- No additional words, explanations, or formatting are needed.
|
|
1198
|
-
- Absolutely no additional text, explanations, line breaks, or formatting outside the JSON object are allowed.
|
|
1199
|
-
|
|
1200
|
-
Example JSON:
|
|
1201
|
-
{"score":0,"reason":"The text of reply does not follow the evaluation criteria provided."}
|
|
1202
|
-
|
|
1203
|
-
Here is the final evaluation in the required minified JSON format:
|
|
1204
|
-
JSON:
|
|
1205
|
-
`;
|
|
1206
|
-
//#endregion
|
|
1207
|
-
//#region src/providers/webSearchUtils.ts
|
|
1208
|
-
function hasTool(provider, predicate) {
|
|
1209
|
-
return Array.isArray(provider.config?.tools) && provider.config.tools.some(predicate);
|
|
1210
|
-
}
|
|
1211
|
-
function getProviderId(provider) {
|
|
1212
|
-
if (typeof provider.id !== "function") return null;
|
|
1213
|
-
try {
|
|
1214
|
-
return provider.id();
|
|
1215
|
-
} catch (err) {
|
|
1216
|
-
logger.debug(`Failed to read provider id: ${err}`);
|
|
1217
|
-
return null;
|
|
1218
|
-
}
|
|
1219
|
-
}
|
|
1220
|
-
function isOpenAiResponsesProvider(provider, id) {
|
|
1221
|
-
return id.includes("openai:responses") || provider.constructor?.name === "OpenAiResponsesProvider";
|
|
1222
|
-
}
|
|
1223
|
-
/**
|
|
1224
|
-
* Check if a provider has web search capabilities
|
|
1225
|
-
* @param provider The provider to check
|
|
1226
|
-
* @returns true if the provider supports web search
|
|
1227
|
-
*/
|
|
1228
|
-
function hasWebSearchCapability(provider) {
|
|
1229
|
-
if (!provider) return false;
|
|
1230
|
-
const id = getProviderId(provider);
|
|
1231
|
-
if (!id) return false;
|
|
1232
|
-
if (id.includes("perplexity")) return true;
|
|
1233
|
-
if ((id.includes("google") || id.includes("gemini") || id.includes("vertex")) && hasTool(provider, (t) => t.googleSearch !== void 0)) return true;
|
|
1234
|
-
if (id.includes("xai") && provider.config?.search_parameters?.mode === "on") return true;
|
|
1235
|
-
if (isOpenAiResponsesProvider(provider, id) && hasTool(provider, (t) => t.type === "web_search_preview")) return true;
|
|
1236
|
-
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;
|
|
1237
|
-
if (id.includes("anthropic") && hasTool(provider, (t) => t.type === "web_search_20250305")) return true;
|
|
1238
|
-
return false;
|
|
1239
|
-
}
|
|
1240
|
-
/**
|
|
1241
|
-
* Load a provider with web search capabilities.
|
|
1242
|
-
* Tries multiple providers in order of preference until one succeeds.
|
|
1243
|
-
* Uses the latest and most capable models from each provider with specific checkpoint IDs.
|
|
1244
|
-
*
|
|
1245
|
-
* @param preferAnthropic Whether to try Anthropic first (true) or OpenAI first (false)
|
|
1246
|
-
* @returns A provider with web search capabilities or null
|
|
1247
|
-
*/
|
|
1248
|
-
async function loadWebSearchProvider(preferAnthropic = false) {
|
|
1249
|
-
const loadAnthropicWebSearch = async () => {
|
|
1250
|
-
try {
|
|
1251
|
-
return await loadApiProvider("anthropic:messages:claude-opus-4-6", { options: { config: { tools: [{
|
|
1252
|
-
type: "web_search_20250305",
|
|
1253
|
-
name: "web_search",
|
|
1254
|
-
max_uses: 5
|
|
1255
|
-
}] } } });
|
|
1256
|
-
} catch (err) {
|
|
1257
|
-
logger.debug(`Failed to load Anthropic web search provider: ${err}`);
|
|
1258
|
-
return null;
|
|
1259
|
-
}
|
|
1260
|
-
};
|
|
1261
|
-
const loadOpenAIWebSearch = async () => {
|
|
1262
|
-
try {
|
|
1263
|
-
return await loadApiProvider("openai:responses:gpt-5.4-2026-03-05", { options: { config: { tools: [{ type: "web_search_preview" }] } } });
|
|
1264
|
-
} catch (err) {
|
|
1265
|
-
logger.debug(`Failed to load OpenAI web search provider: ${err}`);
|
|
1266
|
-
return null;
|
|
1267
|
-
}
|
|
1268
|
-
};
|
|
1269
|
-
const loadPerplexity = async () => {
|
|
1270
|
-
try {
|
|
1271
|
-
return await loadApiProvider("perplexity:sonar-pro");
|
|
1272
|
-
} catch (err) {
|
|
1273
|
-
logger.debug(`Failed to load Perplexity provider: ${err}`);
|
|
1274
|
-
return null;
|
|
1275
|
-
}
|
|
1276
|
-
};
|
|
1277
|
-
const loadGoogleWebSearch = async () => {
|
|
1278
|
-
try {
|
|
1279
|
-
return await loadApiProvider("google:gemini-3-pro-preview", { options: { config: { tools: [{ googleSearch: {} }] } } });
|
|
1280
|
-
} catch (err) {
|
|
1281
|
-
logger.debug(`Failed to load Google web search provider: ${err}`);
|
|
1282
|
-
return null;
|
|
1283
|
-
}
|
|
1284
|
-
};
|
|
1285
|
-
const loadVertexWebSearch = async () => {
|
|
1286
|
-
try {
|
|
1287
|
-
return await loadApiProvider("vertex:gemini-3-pro-preview", { options: { config: { tools: [{ googleSearch: {} }] } } });
|
|
1288
|
-
} catch (err) {
|
|
1289
|
-
logger.debug(`Failed to load Vertex web search provider: ${err}`);
|
|
1290
|
-
return null;
|
|
1291
|
-
}
|
|
1292
|
-
};
|
|
1293
|
-
const loadXaiWebSearch = async () => {
|
|
1294
|
-
try {
|
|
1295
|
-
return await loadApiProvider("xai:grok-4-1-fast-reasoning", { options: { config: { search_parameters: { mode: "on" } } } });
|
|
1296
|
-
} catch (err) {
|
|
1297
|
-
logger.debug(`Failed to load xAI web search provider: ${err}`);
|
|
1298
|
-
return null;
|
|
1299
|
-
}
|
|
1300
|
-
};
|
|
1301
|
-
const providers = preferAnthropic ? [
|
|
1302
|
-
loadAnthropicWebSearch,
|
|
1303
|
-
loadOpenAIWebSearch,
|
|
1304
|
-
loadPerplexity,
|
|
1305
|
-
loadGoogleWebSearch,
|
|
1306
|
-
loadVertexWebSearch,
|
|
1307
|
-
loadXaiWebSearch
|
|
1308
|
-
] : [
|
|
1309
|
-
loadOpenAIWebSearch,
|
|
1310
|
-
loadAnthropicWebSearch,
|
|
1311
|
-
loadPerplexity,
|
|
1312
|
-
loadGoogleWebSearch,
|
|
1313
|
-
loadVertexWebSearch,
|
|
1314
|
-
loadXaiWebSearch
|
|
1315
|
-
];
|
|
1316
|
-
for (const getProvider of providers) {
|
|
1317
|
-
const provider = await getProvider();
|
|
1318
|
-
if (provider && hasWebSearchCapability(provider)) {
|
|
1319
|
-
logger.info(`Using ${getProviderId(provider) ?? "loaded provider"} as web search provider`);
|
|
1320
|
-
return provider;
|
|
1321
|
-
}
|
|
1322
|
-
if (provider) logger.debug(`Loaded provider ${getProviderId(provider) ?? "unknown"} does not support web search`);
|
|
1323
|
-
}
|
|
1324
|
-
return null;
|
|
1325
|
-
}
|
|
1389
|
+
Example:
|
|
1390
|
+
{"steps":["<Evaluation Step 1>","<Evaluation Step 2>","<Evaluation Step 3>","<Evaluation Step 4>"]}
|
|
1391
|
+
|
|
1392
|
+
Here are the 3-4 concise evaluation steps, formatted as required in a minified JSON:
|
|
1393
|
+
JSON:
|
|
1394
|
+
`;
|
|
1395
|
+
const GEVAL_PROMPT_EVALUATE = `
|
|
1396
|
+
You will be given one Reply for a Prompt below. Your task is to rate the Reply on one metric.
|
|
1397
|
+
Please make sure you read and understand these instructions carefully. Please keep this document open while reviewing, and refer to it as needed.
|
|
1398
|
+
|
|
1399
|
+
**Evaluation Criteria**
|
|
1400
|
+
{{criteria}}
|
|
1401
|
+
|
|
1402
|
+
**Evaluation Steps**
|
|
1403
|
+
- {{steps}}
|
|
1404
|
+
Given the evaluation steps, return a JSON with two keys:
|
|
1405
|
+
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;
|
|
1406
|
+
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!
|
|
1407
|
+
|
|
1408
|
+
**Prompt**
|
|
1409
|
+
{{input}}
|
|
1410
|
+
|
|
1411
|
+
**Reply**
|
|
1412
|
+
{{output}}
|
|
1413
|
+
|
|
1414
|
+
**OUTPUT FORMAT**
|
|
1415
|
+
IMPORTANT:
|
|
1416
|
+
- Return output ONLY as a minified JSON object (no code fences).
|
|
1417
|
+
- The JSON object must contain exactly two keys: "score" and "reason".
|
|
1418
|
+
- No additional words, explanations, or formatting are needed.
|
|
1419
|
+
- Absolutely no additional text, explanations, line breaks, or formatting outside the JSON object are allowed.
|
|
1420
|
+
|
|
1421
|
+
Example JSON:
|
|
1422
|
+
{"score":0,"reason":"The text of reply does not follow the evaluation criteria provided."}
|
|
1423
|
+
|
|
1424
|
+
Here is the final evaluation in the required minified JSON format:
|
|
1425
|
+
JSON:
|
|
1426
|
+
`;
|
|
1326
1427
|
//#endregion
|
|
1327
1428
|
//#region src/remoteGrading.ts
|
|
1328
1429
|
async function doRemoteGrading(payload) {
|
|
@@ -1385,23 +1486,7 @@ async function doRemoteScoringWithPi(payload, passThreshold = .5) {
|
|
|
1385
1486
|
}
|
|
1386
1487
|
}
|
|
1387
1488
|
//#endregion
|
|
1388
|
-
//#region src/
|
|
1389
|
-
const providerCallExecutionContext = new AsyncLocalStorage();
|
|
1390
|
-
function getProviderCallExecutionContext() {
|
|
1391
|
-
return providerCallExecutionContext.getStore();
|
|
1392
|
-
}
|
|
1393
|
-
function withProviderCallExecutionContext(context, fn) {
|
|
1394
|
-
return providerCallExecutionContext.run(context, fn);
|
|
1395
|
-
}
|
|
1396
|
-
//#endregion
|
|
1397
|
-
//#region src/matchers.ts
|
|
1398
|
-
var LlmRubricProviderError = class extends Error {
|
|
1399
|
-
constructor(message) {
|
|
1400
|
-
super(message);
|
|
1401
|
-
this.name = "LlmRubricProviderError";
|
|
1402
|
-
}
|
|
1403
|
-
};
|
|
1404
|
-
const nunjucks = getNunjucksEngine(void 0, false, true);
|
|
1489
|
+
//#region src/matchers/llmGrading.ts
|
|
1405
1490
|
const FACTUALITY_CATEGORY_DESCRIPTIONS = {
|
|
1406
1491
|
A: "The submitted answer is a subset of the expert answer and is fully consistent with it.",
|
|
1407
1492
|
B: "The submitted answer is a superset of the expert answer and is fully consistent with it.",
|
|
@@ -1409,409 +1494,73 @@ const FACTUALITY_CATEGORY_DESCRIPTIONS = {
|
|
|
1409
1494
|
D: "There is a disagreement between the submitted answer and the expert answer.",
|
|
1410
1495
|
E: "The answers differ, but these differences don't matter from the perspective of factuality."
|
|
1411
1496
|
};
|
|
1412
|
-
function
|
|
1413
|
-
if (vecA.length !== vecB.length) throw new Error("Vectors must be of equal length");
|
|
1414
|
-
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)));
|
|
1415
|
-
}
|
|
1416
|
-
function dotProduct(vecA, vecB) {
|
|
1417
|
-
if (vecA.length !== vecB.length) throw new Error("Vectors must be of equal length");
|
|
1418
|
-
return vecA.reduce((acc, val, idx) => acc + val * vecB[idx], 0);
|
|
1419
|
-
}
|
|
1420
|
-
function euclideanDistance(vecA, vecB) {
|
|
1421
|
-
if (vecA.length !== vecB.length) throw new Error("Vectors must be of equal length");
|
|
1422
|
-
const sumSquaredDiff = vecA.reduce((acc, val, idx) => {
|
|
1423
|
-
const diff = val - vecB[idx];
|
|
1424
|
-
return acc + diff * diff;
|
|
1425
|
-
}, 0);
|
|
1426
|
-
return Math.sqrt(sumSquaredDiff);
|
|
1427
|
-
}
|
|
1428
|
-
/**
|
|
1429
|
-
* Helper to call provider with consistent context propagation pattern.
|
|
1430
|
-
* Spreads the optional context and merges with prompt label and vars.
|
|
1431
|
-
*
|
|
1432
|
-
* IMPORTANT: Spread order matters - context is spread first, then prompt/vars
|
|
1433
|
-
* override. This ensures originalProvider from context is preserved while
|
|
1434
|
-
* allowing this call to specify its own prompt metadata.
|
|
1435
|
-
*/
|
|
1436
|
-
function callProviderWithContext(provider, prompt, label, vars, context) {
|
|
1437
|
-
const callApiContext = {
|
|
1438
|
-
...context,
|
|
1439
|
-
prompt: {
|
|
1440
|
-
raw: prompt,
|
|
1441
|
-
label
|
|
1442
|
-
},
|
|
1443
|
-
vars
|
|
1444
|
-
};
|
|
1445
|
-
const executionContext = getProviderCallExecutionContext();
|
|
1446
|
-
const callApiOptions = executionContext?.abortSignal ? { abortSignal: executionContext.abortSignal } : void 0;
|
|
1447
|
-
const callApi = () => callApiOptions ? provider.callApi(prompt, callApiContext, callApiOptions) : provider.callApi(prompt, callApiContext);
|
|
1448
|
-
const executeCall = () => {
|
|
1449
|
-
if (executionContext?.rateLimitRegistry && !isRateLimitWrapped(provider)) return executionContext.rateLimitRegistry.execute(provider, callApi, createProviderRateLimitOptions());
|
|
1450
|
-
return callApi();
|
|
1451
|
-
};
|
|
1452
|
-
if (executionContext?.providerCallQueue) return executionContext.providerCallQueue.enqueue(provider.id(), executeCall);
|
|
1453
|
-
return executeCall();
|
|
1454
|
-
}
|
|
1455
|
-
async function loadFromProviderOptions(provider) {
|
|
1456
|
-
invariant(typeof provider === "object", `Provider must be an object, but received a ${typeof provider}: ${provider}`);
|
|
1457
|
-
invariant(!Array.isArray(provider), `Provider must be an object, but received an array: ${JSON.stringify(provider)}`);
|
|
1458
|
-
invariant(provider.id, "Provider supplied to assertion must have an id");
|
|
1459
|
-
return loadApiProvider(provider.id, {
|
|
1460
|
-
options: provider,
|
|
1461
|
-
basePath: state.basePath
|
|
1462
|
-
});
|
|
1463
|
-
}
|
|
1464
|
-
function isSimulatedUserProviderConfig(provider) {
|
|
1465
|
-
if (typeof provider === "string") return provider === "promptfoo:simulated-user";
|
|
1466
|
-
if (!provider || typeof provider !== "object" || Array.isArray(provider)) return false;
|
|
1467
|
-
if (typeof provider.id === "function") return provider.id() === "promptfoo:simulated-user";
|
|
1468
|
-
const providerId = provider.id;
|
|
1469
|
-
if (typeof providerId === "string") return providerId === "promptfoo:simulated-user";
|
|
1470
|
-
return Object.values(provider).some((providerTypeConfig) => isSimulatedUserProviderConfig(providerTypeConfig));
|
|
1471
|
-
}
|
|
1472
|
-
async function getGradingProvider(type, provider, defaultProvider) {
|
|
1473
|
-
let finalProvider;
|
|
1474
|
-
if (typeof provider === "string") finalProvider = await loadApiProvider(provider, { basePath: state.basePath });
|
|
1475
|
-
else if (typeof provider === "object" && typeof provider.id === "function") finalProvider = provider;
|
|
1476
|
-
else if (typeof provider === "object") {
|
|
1477
|
-
const typeValue = provider[type];
|
|
1478
|
-
if (typeValue) finalProvider = await getGradingProvider(type, typeValue, defaultProvider);
|
|
1479
|
-
else if (provider.id) finalProvider = await loadFromProviderOptions(provider);
|
|
1480
|
-
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.`);
|
|
1481
|
-
else throw new Error(`Invalid provider definition for output type '${type}': ${JSON.stringify(provider, null, 2)}`);
|
|
1482
|
-
} else {
|
|
1483
|
-
const defaultTest = state.config?.defaultTest;
|
|
1484
|
-
const defaultTestObj = typeof defaultTest === "object" ? defaultTest : null;
|
|
1485
|
-
const cfg = [
|
|
1486
|
-
defaultTestObj?.provider || void 0,
|
|
1487
|
-
defaultTestObj?.options?.provider?.text || void 0,
|
|
1488
|
-
defaultTestObj?.options?.provider || void 0
|
|
1489
|
-
].find((candidateProvider) => {
|
|
1490
|
-
if (!candidateProvider) return false;
|
|
1491
|
-
if (isSimulatedUserProviderConfig(candidateProvider)) {
|
|
1492
|
-
logger.debug("[Grading] Skipping promptfoo:simulated-user as an implicit grader fallback");
|
|
1493
|
-
return false;
|
|
1494
|
-
}
|
|
1495
|
-
return true;
|
|
1496
|
-
});
|
|
1497
|
-
if (cfg) {
|
|
1498
|
-
finalProvider = await getGradingProvider(type, cfg, defaultProvider);
|
|
1499
|
-
if (finalProvider) logger.debug(`[Grading] Using provider from defaultTest fallback: ${finalProvider.id()}`);
|
|
1500
|
-
} else finalProvider = defaultProvider;
|
|
1501
|
-
}
|
|
1502
|
-
return finalProvider;
|
|
1503
|
-
}
|
|
1504
|
-
async function getAndCheckProvider(type, provider, defaultProvider, checkName) {
|
|
1505
|
-
const matchedProvider = await getGradingProvider(type, provider, defaultProvider);
|
|
1506
|
-
if (!matchedProvider) if (defaultProvider) {
|
|
1507
|
-
logger.warn(`No provider of type ${type} found for '${checkName}', falling back to default`);
|
|
1508
|
-
return defaultProvider;
|
|
1509
|
-
} else throw new Error(`No provider of type ${type} found for '${checkName}'`);
|
|
1510
|
-
let isValidProviderType = true;
|
|
1511
|
-
if (type === "embedding") isValidProviderType = "callEmbeddingApi" in matchedProvider || "callSimilarityApi" in matchedProvider;
|
|
1512
|
-
else if (type === "classification") isValidProviderType = "callClassificationApi" in matchedProvider;
|
|
1513
|
-
else if (type === "moderation") isValidProviderType = "callModerationApi" in matchedProvider;
|
|
1514
|
-
if (!isValidProviderType) if (defaultProvider) {
|
|
1515
|
-
logger.warn(`Provider ${matchedProvider.id()} is not a valid ${type} provider for '${checkName}', falling back to default`);
|
|
1516
|
-
return defaultProvider;
|
|
1517
|
-
} else throw new Error(`Provider ${matchedProvider.id()} is not a valid ${type} provider for '${checkName}'`);
|
|
1518
|
-
return matchedProvider;
|
|
1519
|
-
}
|
|
1520
|
-
function fail(reason, tokensUsed) {
|
|
1521
|
-
return {
|
|
1522
|
-
pass: false,
|
|
1523
|
-
reason,
|
|
1524
|
-
score: 0,
|
|
1525
|
-
tokensUsed: {
|
|
1526
|
-
total: tokensUsed?.total || 0,
|
|
1527
|
-
prompt: tokensUsed?.prompt || 0,
|
|
1528
|
-
completion: tokensUsed?.completion || 0,
|
|
1529
|
-
cached: tokensUsed?.cached || 0,
|
|
1530
|
-
numRequests: tokensUsed?.numRequests || 0,
|
|
1531
|
-
completionDetails: tokensUsed?.completionDetails
|
|
1532
|
-
}
|
|
1533
|
-
};
|
|
1534
|
-
}
|
|
1535
|
-
function normalizeTokenUsage(tokensUsed) {
|
|
1536
|
-
return {
|
|
1537
|
-
total: tokensUsed?.total || 0,
|
|
1538
|
-
prompt: tokensUsed?.prompt || 0,
|
|
1539
|
-
completion: tokensUsed?.completion || 0,
|
|
1540
|
-
cached: tokensUsed?.cached || 0,
|
|
1541
|
-
numRequests: tokensUsed?.numRequests || 0,
|
|
1542
|
-
completionDetails: tokensUsed?.completionDetails || {
|
|
1543
|
-
reasoning: 0,
|
|
1544
|
-
acceptedPrediction: 0,
|
|
1545
|
-
rejectedPrediction: 0
|
|
1546
|
-
}
|
|
1547
|
-
};
|
|
1548
|
-
}
|
|
1549
|
-
function createMatcherTokenUsage() {
|
|
1550
|
-
return {
|
|
1551
|
-
total: 0,
|
|
1552
|
-
prompt: 0,
|
|
1553
|
-
completion: 0,
|
|
1554
|
-
cached: 0,
|
|
1555
|
-
numRequests: 0,
|
|
1556
|
-
completionDetails: {
|
|
1557
|
-
reasoning: 0,
|
|
1558
|
-
acceptedPrediction: 0,
|
|
1559
|
-
rejectedPrediction: 0
|
|
1560
|
-
}
|
|
1561
|
-
};
|
|
1562
|
-
}
|
|
1563
|
-
function copySimilarityTokenUsage(tokensUsed, response) {
|
|
1564
|
-
Object.assign(tokensUsed, normalizeTokenUsage(response.tokenUsage));
|
|
1565
|
-
}
|
|
1566
|
-
function combineEmbeddingTokenUsage(expectedEmbedding, outputEmbedding) {
|
|
1567
|
-
const expectedTokens = normalizeTokenUsage(expectedEmbedding.tokenUsage);
|
|
1568
|
-
const outputTokens = normalizeTokenUsage(outputEmbedding.tokenUsage);
|
|
1569
|
-
return {
|
|
1570
|
-
total: (expectedTokens.total ?? 0) + (outputTokens.total ?? 0),
|
|
1571
|
-
prompt: (expectedTokens.prompt ?? 0) + (outputTokens.prompt ?? 0),
|
|
1572
|
-
completion: (expectedTokens.completion ?? 0) + (outputTokens.completion ?? 0),
|
|
1573
|
-
cached: (expectedTokens.cached ?? 0) + (outputTokens.cached ?? 0),
|
|
1574
|
-
numRequests: (expectedTokens.numRequests ?? 0) + (outputTokens.numRequests ?? 0),
|
|
1575
|
-
completionDetails: {
|
|
1576
|
-
reasoning: (expectedTokens.completionDetails?.reasoning || 0) + (outputTokens.completionDetails?.reasoning || 0),
|
|
1577
|
-
acceptedPrediction: (expectedTokens.completionDetails?.acceptedPrediction || 0) + (outputTokens.completionDetails?.acceptedPrediction || 0),
|
|
1578
|
-
rejectedPrediction: (expectedTokens.completionDetails?.rejectedPrediction || 0) + (outputTokens.completionDetails?.rejectedPrediction || 0)
|
|
1579
|
-
}
|
|
1580
|
-
};
|
|
1581
|
-
}
|
|
1582
|
-
function accumulateTokens(target, update) {
|
|
1583
|
-
accumulateTokenUsage(target, update);
|
|
1584
|
-
}
|
|
1585
|
-
async function maybeRemoteSimilarityGrading({ expected, output, threshold, inverse }) {
|
|
1586
|
-
if (!state.config?.redteam || !shouldGenerateRemote({ requireEmbeddingProvider: true })) return;
|
|
1587
|
-
try {
|
|
1588
|
-
return await doRemoteGrading({
|
|
1589
|
-
task: "similar",
|
|
1590
|
-
expected,
|
|
1591
|
-
output,
|
|
1592
|
-
threshold,
|
|
1593
|
-
inverse
|
|
1594
|
-
});
|
|
1595
|
-
} catch (error) {
|
|
1596
|
-
return fail(`Could not perform remote grading: ${error}`);
|
|
1597
|
-
}
|
|
1598
|
-
}
|
|
1599
|
-
async function computeNativeSimilarity(provider, expected, output, metric) {
|
|
1600
|
-
if ("callSimilarityApi" in provider) return computeSimilarityFromNativeProvider(provider, expected, output, metric);
|
|
1601
|
-
if ("callEmbeddingApi" in provider) return computeSimilarityFromEmbeddings(provider, expected, output, metric);
|
|
1602
|
-
throw new Error("Provider must implement callSimilarityApi or callEmbeddingApi");
|
|
1603
|
-
}
|
|
1604
|
-
async function computeSimilarityFromNativeProvider(provider, expected, output, metric) {
|
|
1605
|
-
const tokensUsed = createMatcherTokenUsage();
|
|
1606
|
-
if (metric !== "cosine") return { failure: fail(`Provider ${provider.id()} only supports cosine similarity via callSimilarityApi`, tokensUsed) };
|
|
1607
|
-
const similarityResp = await provider.callSimilarityApi(expected, output);
|
|
1608
|
-
copySimilarityTokenUsage(tokensUsed, similarityResp);
|
|
1609
|
-
if (similarityResp.error) return { failure: fail(similarityResp.error, tokensUsed) };
|
|
1610
|
-
if (similarityResp.similarity == null) return { failure: fail("Unknown error fetching similarity", tokensUsed) };
|
|
1611
|
-
return {
|
|
1612
|
-
similarity: similarityResp.similarity,
|
|
1613
|
-
tokensUsed
|
|
1614
|
-
};
|
|
1615
|
-
}
|
|
1616
|
-
async function computeSimilarityFromEmbeddings(provider, expected, output, metric) {
|
|
1617
|
-
const expectedEmbedding = await provider.callEmbeddingApi(expected);
|
|
1618
|
-
const outputEmbedding = await provider.callEmbeddingApi(output);
|
|
1619
|
-
const tokensUsed = combineEmbeddingTokenUsage(expectedEmbedding, outputEmbedding);
|
|
1620
|
-
if (expectedEmbedding.error || outputEmbedding.error) return { failure: fail(expectedEmbedding.error || outputEmbedding.error || "Unknown error fetching embeddings", tokensUsed) };
|
|
1621
|
-
if (!expectedEmbedding.embedding || !outputEmbedding.embedding) return { failure: fail("Embedding not found", tokensUsed) };
|
|
1622
|
-
return {
|
|
1623
|
-
similarity: computeSimilarityMetric(expectedEmbedding.embedding, outputEmbedding.embedding, metric),
|
|
1624
|
-
tokensUsed
|
|
1625
|
-
};
|
|
1626
|
-
}
|
|
1627
|
-
function computeSimilarityMetric(expectedEmbedding, outputEmbedding, metric) {
|
|
1628
|
-
switch (metric) {
|
|
1629
|
-
case "cosine": return cosineSimilarity(expectedEmbedding, outputEmbedding);
|
|
1630
|
-
case "dot_product": return dotProduct(expectedEmbedding, outputEmbedding);
|
|
1631
|
-
case "euclidean": return euclideanDistance(expectedEmbedding, outputEmbedding);
|
|
1632
|
-
default: throw new Error(`Unsupported metric: ${metric}`);
|
|
1633
|
-
}
|
|
1634
|
-
}
|
|
1635
|
-
function buildSimilarityResult(similarity, threshold, inverse, metric, tokensUsed) {
|
|
1636
|
-
return metric === "euclidean" ? buildDistanceResult(similarity, threshold, inverse, tokensUsed) : buildSimilarityScoreResult(similarity, threshold, inverse, tokensUsed);
|
|
1637
|
-
}
|
|
1638
|
-
function buildDistanceResult(distance, threshold, inverse, tokensUsed) {
|
|
1639
|
-
const pass = inverse ? distance >= threshold - Number.EPSILON : distance <= threshold + Number.EPSILON;
|
|
1640
|
-
const normalizedScore = 1 / (1 + distance);
|
|
1641
|
-
const belowThresholdReason = `Distance ${distance.toFixed(2)} is less than or equal to threshold ${threshold}`;
|
|
1642
|
-
const aboveThresholdReason = `Distance ${distance.toFixed(2)} is greater than threshold ${threshold}`;
|
|
1643
|
-
return {
|
|
1644
|
-
pass,
|
|
1645
|
-
score: inverse ? 1 - normalizedScore : normalizedScore,
|
|
1646
|
-
reason: pass === inverse ? aboveThresholdReason : belowThresholdReason,
|
|
1647
|
-
tokensUsed
|
|
1648
|
-
};
|
|
1649
|
-
}
|
|
1650
|
-
function buildSimilarityScoreResult(similarity, threshold, inverse, tokensUsed) {
|
|
1651
|
-
const pass = inverse ? similarity <= threshold + Number.EPSILON : similarity >= threshold - Number.EPSILON;
|
|
1652
|
-
const greaterThanReason = `Similarity ${similarity.toFixed(2)} is greater than or equal to threshold ${threshold}`;
|
|
1653
|
-
const lessThanReason = `Similarity ${similarity.toFixed(2)} is less than threshold ${threshold}`;
|
|
1654
|
-
return {
|
|
1655
|
-
pass,
|
|
1656
|
-
score: inverse ? 1 - similarity : similarity,
|
|
1657
|
-
reason: pass === inverse ? lessThanReason : greaterThanReason,
|
|
1658
|
-
tokensUsed
|
|
1659
|
-
};
|
|
1660
|
-
}
|
|
1661
|
-
async function matchesSimilarity(expected, output, threshold, inverse = false, grading, metric = "cosine") {
|
|
1662
|
-
const remoteResult = await maybeRemoteSimilarityGrading({
|
|
1663
|
-
expected,
|
|
1664
|
-
output,
|
|
1665
|
-
threshold,
|
|
1666
|
-
inverse
|
|
1667
|
-
});
|
|
1668
|
-
if (remoteResult) return remoteResult;
|
|
1669
|
-
const defaults = await getDefaultProviders();
|
|
1670
|
-
const computation = await computeNativeSimilarity(await getAndCheckProvider("embedding", grading?.provider, defaults.embeddingProvider, "similarity check"), expected, output, metric);
|
|
1671
|
-
return "failure" in computation ? computation.failure : buildSimilarityResult(computation.similarity, threshold, inverse, metric, computation.tokensUsed);
|
|
1672
|
-
}
|
|
1673
|
-
/**
|
|
1674
|
-
*
|
|
1675
|
-
* @param expected Expected classification. If undefined, matches any classification.
|
|
1676
|
-
* @param output Text to classify.
|
|
1677
|
-
* @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.
|
|
1678
|
-
* @param grading
|
|
1679
|
-
* @returns Pass if the output matches the classification with a score greater than or equal to the threshold.
|
|
1680
|
-
*/
|
|
1681
|
-
async function matchesClassification(expected, output, threshold, grading) {
|
|
1682
|
-
const resp = await (await getAndCheckProvider("classification", grading?.provider, null, "classification check")).callClassificationApi(output);
|
|
1683
|
-
if (!resp.classification) return fail(resp.error || "Unknown error fetching classification");
|
|
1684
|
-
let score;
|
|
1685
|
-
if (expected === void 0) score = Math.max(...Object.values(resp.classification));
|
|
1686
|
-
else score = resp.classification[expected] || 0;
|
|
1687
|
-
if (score >= threshold - Number.EPSILON) {
|
|
1688
|
-
const reason = expected === void 0 ? `Maximum classification score ${score.toFixed(2)} >= ${threshold}` : `Classification ${expected} has score ${score.toFixed(2)} >= ${threshold}`;
|
|
1689
|
-
return {
|
|
1690
|
-
pass: true,
|
|
1691
|
-
score,
|
|
1692
|
-
reason
|
|
1693
|
-
};
|
|
1694
|
-
}
|
|
1497
|
+
function getFactualityScoreLookup(grading) {
|
|
1695
1498
|
return {
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
if (!rubricPrompt || typeof rubricPrompt === "object" && Object.keys(rubricPrompt).length === 0) return defaultPrompt;
|
|
1703
|
-
if (typeof rubricPrompt === "string" && rubricPrompt.startsWith("file://")) {
|
|
1704
|
-
const basePath = state.basePath || "";
|
|
1705
|
-
const { filePath, functionName } = parseFileUrl(getNunjucksEngineForFilePath().renderString(rubricPrompt, {}));
|
|
1706
|
-
const resolvedPath = path.resolve(basePath, filePath);
|
|
1707
|
-
if (isJavascriptFile(filePath)) rubricPrompt = await loadFromJavaScriptFile(resolvedPath, functionName, []);
|
|
1708
|
-
else {
|
|
1709
|
-
if (!fs$2.existsSync(resolvedPath)) throw new Error(`File does not exist: ${resolvedPath}`);
|
|
1710
|
-
rubricPrompt = fs$2.readFileSync(resolvedPath, "utf8");
|
|
1711
|
-
}
|
|
1712
|
-
} else rubricPrompt = maybeLoadFromExternalFile(rubricPrompt);
|
|
1713
|
-
if (typeof rubricPrompt === "object") rubricPrompt = JSON.stringify(rubricPrompt);
|
|
1714
|
-
invariant(typeof rubricPrompt === "string", "rubricPrompt must be a string");
|
|
1715
|
-
return rubricPrompt;
|
|
1716
|
-
}
|
|
1717
|
-
function tryParse(content) {
|
|
1718
|
-
try {
|
|
1719
|
-
return JSON.parse(content);
|
|
1720
|
-
} catch {}
|
|
1721
|
-
return content;
|
|
1722
|
-
}
|
|
1723
|
-
function splitIntoSentences(text) {
|
|
1724
|
-
return text.split("\n").filter((sentence) => sentence.trim() !== "");
|
|
1725
|
-
}
|
|
1726
|
-
function processContextForTemplating(context, enableObjectAccess) {
|
|
1727
|
-
if (enableObjectAccess) return context;
|
|
1728
|
-
return Object.fromEntries(Object.entries(context).map(([key, value]) => {
|
|
1729
|
-
if (value && typeof value === "object") {
|
|
1730
|
-
if (Array.isArray(value)) return [key, value.map((item) => item && typeof item === "object" ? JSON.stringify(item) : item)];
|
|
1731
|
-
return [key, JSON.stringify(value)];
|
|
1732
|
-
}
|
|
1733
|
-
return [key, value];
|
|
1734
|
-
}));
|
|
1499
|
+
A: grading.factuality?.subset ?? 1,
|
|
1500
|
+
B: grading.factuality?.superset ?? 1,
|
|
1501
|
+
C: grading.factuality?.agree ?? 1,
|
|
1502
|
+
D: grading.factuality?.disagree ?? 0,
|
|
1503
|
+
E: grading.factuality?.differButFactual ?? 1
|
|
1504
|
+
};
|
|
1735
1505
|
}
|
|
1736
|
-
|
|
1737
|
-
const
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1506
|
+
function buildFactualityResult(option, reason, grading, resp) {
|
|
1507
|
+
const scoreLookup = getFactualityScoreLookup(grading);
|
|
1508
|
+
const passing = Object.keys(scoreLookup).filter((key) => scoreLookup[key] > 0);
|
|
1509
|
+
const failing = Object.keys(scoreLookup).filter((key) => scoreLookup[key] === 0);
|
|
1510
|
+
const pass = passing.includes(option) && !failing.includes(option);
|
|
1511
|
+
return {
|
|
1512
|
+
pass,
|
|
1513
|
+
score: scoreLookup[option] ?? (pass ? 1 : 0),
|
|
1514
|
+
reason,
|
|
1515
|
+
tokensUsed: normalizeMatcherTokenUsage(resp.tokenUsage)
|
|
1516
|
+
};
|
|
1743
1517
|
}
|
|
1744
|
-
function
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1518
|
+
function parseFactualityJsonResponse(responseText) {
|
|
1519
|
+
try {
|
|
1520
|
+
const jsonData = extractFirstJsonObject(responseText);
|
|
1521
|
+
if (!jsonData?.category || typeof jsonData.category !== "string") return;
|
|
1522
|
+
const option = jsonData.category.trim().toUpperCase();
|
|
1523
|
+
if (!/^[A-E]$/.test(option)) throw new Error(`Invalid category value: ${option}`);
|
|
1524
|
+
return {
|
|
1525
|
+
option,
|
|
1526
|
+
reason: jsonData.reason?.trim() || `Category ${option}: ${FACTUALITY_CATEGORY_DESCRIPTIONS[option]}`
|
|
1527
|
+
};
|
|
1749
1528
|
} catch (err) {
|
|
1750
|
-
|
|
1529
|
+
const error = err;
|
|
1530
|
+
if (error.message.startsWith("Invalid category value:")) throw error;
|
|
1531
|
+
logger.debug(`JSON parsing failed: ${error.message}`);
|
|
1532
|
+
return;
|
|
1751
1533
|
}
|
|
1752
|
-
else if (typeof resp.output === "object" && resp.output !== null && !Array.isArray(resp.output)) jsonObjects = [resp.output];
|
|
1753
|
-
else return { failure: fail(`${label} produced malformed response - output must be string or object. Output: ${JSON.stringify(resp.output)}`, resp.tokenUsage) };
|
|
1754
|
-
const parsed = jsonObjects[0];
|
|
1755
|
-
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) };
|
|
1756
|
-
return { parsed };
|
|
1757
1534
|
}
|
|
1758
|
-
|
|
1759
|
-
const
|
|
1760
|
-
|
|
1761
|
-
const
|
|
1762
|
-
const
|
|
1763
|
-
if (resp.error || !resp.output) {
|
|
1764
|
-
if (throwOnError) throw new Error(resp.error || "No output");
|
|
1765
|
-
return fail(resp.error || "No output", resp.tokenUsage);
|
|
1766
|
-
}
|
|
1767
|
-
const { parsed, failure } = parseJsonGradingResponse(label, resp);
|
|
1768
|
-
if (!parsed) return failure;
|
|
1769
|
-
let pass = parsed.pass ?? true;
|
|
1770
|
-
if (typeof pass !== "boolean") pass = /^(true|yes|pass|y)$/i.test(String(pass));
|
|
1771
|
-
let score = parsed.score;
|
|
1772
|
-
if (typeof score !== "number") score = Number.isFinite(Number(score)) ? Number(score) : Number(pass);
|
|
1773
|
-
const threshold = typeof assertion?.threshold === "string" ? Number(assertion.threshold) : assertion?.threshold;
|
|
1774
|
-
if (typeof threshold === "number" && Number.isFinite(threshold)) pass = pass && score >= threshold;
|
|
1775
|
-
const reason = parsed.reason || (pass ? "Grading passed" : `Score ${score} below threshold ${threshold}`);
|
|
1776
|
-
let responseMetadata = {};
|
|
1777
|
-
if (resp.metadata && typeof resp.metadata === "object" && !Array.isArray(resp.metadata)) {
|
|
1778
|
-
const serializedMetadata = safeJsonStringify(resp.metadata);
|
|
1779
|
-
responseMetadata = serializedMetadata ? JSON.parse(serializedMetadata) : {};
|
|
1780
|
-
}
|
|
1535
|
+
function parseLegacyFactualityResponse(responseText) {
|
|
1536
|
+
const answerMatch = responseText.match(/\s*\(?([a-eA-E])\)/);
|
|
1537
|
+
if (!answerMatch) throw new Error(`Factuality checker output did not match expected format: ${responseText}`);
|
|
1538
|
+
const option = answerMatch[1].toUpperCase();
|
|
1539
|
+
const reasonMatch = responseText.match(/\)\s*(.*)/s);
|
|
1781
1540
|
return {
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
score,
|
|
1785
|
-
reason,
|
|
1786
|
-
tokensUsed: {
|
|
1787
|
-
total: resp.tokenUsage?.total || 0,
|
|
1788
|
-
prompt: resp.tokenUsage?.prompt || 0,
|
|
1789
|
-
completion: resp.tokenUsage?.completion || 0,
|
|
1790
|
-
cached: resp.tokenUsage?.cached || 0,
|
|
1791
|
-
numRequests: resp.tokenUsage?.numRequests || 0,
|
|
1792
|
-
completionDetails: parsed.tokensUsed?.completionDetails || {
|
|
1793
|
-
reasoning: 0,
|
|
1794
|
-
acceptedPrediction: 0,
|
|
1795
|
-
rejectedPrediction: 0
|
|
1796
|
-
}
|
|
1797
|
-
},
|
|
1798
|
-
metadata: {
|
|
1799
|
-
...responseMetadata,
|
|
1800
|
-
renderedGradingPrompt: prompt
|
|
1801
|
-
}
|
|
1541
|
+
option,
|
|
1542
|
+
reason: reasonMatch?.[1] ? reasonMatch[1].trim() : responseText
|
|
1802
1543
|
};
|
|
1803
1544
|
}
|
|
1804
1545
|
async function matchesLlmRubric(rubric, llmOutput, grading, vars, assertion, options, providerCallContext) {
|
|
1805
1546
|
if (!grading) throw new Error("Cannot grade output without grading config. Specify --grader option or grading config.");
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1547
|
+
const shouldPreferRemote = options?.preferRemote || grading.__promptfooPreferRemote || !grading.provider;
|
|
1548
|
+
if (!grading.rubricPrompt && shouldPreferRemote && !state.config?.redteam?.provider && state.config?.redteam && shouldGenerateRemote({ canUseCodexDefaultProvider: true })) try {
|
|
1549
|
+
return {
|
|
1550
|
+
...await doRemoteGrading({
|
|
1551
|
+
task: "llm-rubric",
|
|
1552
|
+
rubric,
|
|
1553
|
+
output: llmOutput,
|
|
1554
|
+
vars: vars || {}
|
|
1555
|
+
}),
|
|
1556
|
+
assertion
|
|
1557
|
+
};
|
|
1558
|
+
} catch (error) {
|
|
1559
|
+
return {
|
|
1560
|
+
...fail(`Could not perform remote grading: ${error}`),
|
|
1561
|
+
assertion
|
|
1562
|
+
};
|
|
1563
|
+
}
|
|
1815
1564
|
try {
|
|
1816
1565
|
return await runJsonGradingPrompt({
|
|
1817
1566
|
assertion,
|
|
@@ -1859,89 +1608,42 @@ async function matchesPiScore(renderedValue, llmInput, llmOutput, assertion) {
|
|
|
1859
1608
|
assertion
|
|
1860
1609
|
};
|
|
1861
1610
|
}
|
|
1862
|
-
function isFactualityCategory(category) {
|
|
1863
|
-
return /^[A-E]$/.test(category);
|
|
1864
|
-
}
|
|
1865
|
-
function getFactualityScoreLookup(grading) {
|
|
1866
|
-
return {
|
|
1867
|
-
A: grading.factuality?.subset ?? 1,
|
|
1868
|
-
B: grading.factuality?.superset ?? 1,
|
|
1869
|
-
C: grading.factuality?.agree ?? 1,
|
|
1870
|
-
D: grading.factuality?.disagree ?? 0,
|
|
1871
|
-
E: grading.factuality?.differButFactual ?? 1
|
|
1872
|
-
};
|
|
1873
|
-
}
|
|
1874
|
-
function buildFactualityCategoryResult(category, reason, grading, tokensUsed) {
|
|
1875
|
-
const option = category.trim().toUpperCase();
|
|
1876
|
-
if (!isFactualityCategory(option)) return fail(`Invalid category value: ${option}`, tokensUsed);
|
|
1877
|
-
const score = getFactualityScoreLookup(grading)[option];
|
|
1878
|
-
return {
|
|
1879
|
-
pass: score > 0,
|
|
1880
|
-
score,
|
|
1881
|
-
reason: reason?.trim() || `Category ${option}: ${FACTUALITY_CATEGORY_DESCRIPTIONS[option]}`,
|
|
1882
|
-
tokensUsed: normalizeTokenUsage(tokensUsed)
|
|
1883
|
-
};
|
|
1884
|
-
}
|
|
1885
|
-
function parseJsonFactualityOutput(output) {
|
|
1886
|
-
try {
|
|
1887
|
-
const jsonData = extractFirstJsonObject(output);
|
|
1888
|
-
return typeof jsonData?.category === "string" ? {
|
|
1889
|
-
category: jsonData.category,
|
|
1890
|
-
reason: jsonData.reason
|
|
1891
|
-
} : null;
|
|
1892
|
-
} catch (err) {
|
|
1893
|
-
logger.debug(`JSON parsing failed: ${err.message}`);
|
|
1894
|
-
return null;
|
|
1895
|
-
}
|
|
1896
|
-
}
|
|
1897
|
-
function parseLegacyFactualityOutput(output) {
|
|
1898
|
-
const answerMatch = output.match(/\s*\(?([a-eA-E])\)/);
|
|
1899
|
-
if (!answerMatch) return { failure: `Factuality checker output did not match expected format: ${output}` };
|
|
1900
|
-
const reasonMatch = output.match(/\)\s*(.*)/s);
|
|
1901
|
-
return {
|
|
1902
|
-
category: answerMatch[1],
|
|
1903
|
-
reason: reasonMatch?.[1]?.trim() || output
|
|
1904
|
-
};
|
|
1905
|
-
}
|
|
1906
|
-
function gradeFactualityOutput(output, grading, tokensUsed) {
|
|
1907
|
-
const jsonResult = parseJsonFactualityOutput(output);
|
|
1908
|
-
if (jsonResult) return buildFactualityCategoryResult(jsonResult.category, jsonResult.reason, grading, tokensUsed);
|
|
1909
|
-
logger.info("Falling back to legacy pattern matching for factuality check");
|
|
1910
|
-
const legacyResult = parseLegacyFactualityOutput(output);
|
|
1911
|
-
return "failure" in legacyResult ? fail(legacyResult.failure, tokensUsed) : buildFactualityCategoryResult(legacyResult.category, legacyResult.reason, grading, tokensUsed);
|
|
1912
|
-
}
|
|
1913
1611
|
async function matchesFactuality(input, expected, output, grading, vars, providerCallContext) {
|
|
1914
1612
|
if (!grading) throw new Error("Cannot grade output without grading config. Specify --grader option or grading config.");
|
|
1915
|
-
const
|
|
1916
|
-
input,
|
|
1917
|
-
ideal: expected,
|
|
1918
|
-
completion: tryParse(output),
|
|
1919
|
-
...vars || {}
|
|
1920
|
-
});
|
|
1921
|
-
const resp = await callProviderWithContext(await getAndCheckProvider("text", grading.provider, (await getDefaultProviders()).gradingProvider, "factuality check"), prompt, "factuality", {
|
|
1613
|
+
const templateVars = {
|
|
1922
1614
|
input,
|
|
1923
1615
|
ideal: expected,
|
|
1924
1616
|
completion: tryParse(output),
|
|
1925
1617
|
...vars || {}
|
|
1926
|
-
}
|
|
1618
|
+
};
|
|
1619
|
+
const prompt = await renderLlmRubricPrompt(await loadRubricPrompt(grading?.rubricPrompt, PROMPTFOO_FACTUALITY_PROMPT), templateVars);
|
|
1620
|
+
const resp = await callProviderWithContext(await getAndCheckProvider("text", grading.provider, (await getDefaultProviders()).gradingProvider, "factuality check"), prompt, "factuality", templateVars, providerCallContext);
|
|
1927
1621
|
if (resp.error || !resp.output) return fail(resp.error || "No output", resp.tokenUsage);
|
|
1928
1622
|
invariant(typeof resp.output === "string", "factuality produced malformed response");
|
|
1929
|
-
|
|
1623
|
+
try {
|
|
1624
|
+
const parsedJson = parseFactualityJsonResponse(resp.output);
|
|
1625
|
+
if (parsedJson) return buildFactualityResult(parsedJson.option, parsedJson.reason, grading, resp);
|
|
1626
|
+
} catch (err) {
|
|
1627
|
+
return fail(err.message, resp.tokenUsage);
|
|
1628
|
+
}
|
|
1629
|
+
logger.info("Falling back to legacy pattern matching for factuality check");
|
|
1630
|
+
try {
|
|
1631
|
+
const parsedLegacy = parseLegacyFactualityResponse(resp.output);
|
|
1632
|
+
return buildFactualityResult(parsedLegacy.option, parsedLegacy.reason, grading, resp);
|
|
1633
|
+
} catch (err) {
|
|
1634
|
+
return fail(err.message, resp.tokenUsage);
|
|
1635
|
+
}
|
|
1930
1636
|
}
|
|
1931
1637
|
async function matchesClosedQa(input, expected, output, grading, vars, providerCallContext) {
|
|
1932
1638
|
if (!grading) throw new Error("Cannot grade output without grading config. Specify --grader option or grading config.");
|
|
1933
|
-
const
|
|
1934
|
-
input,
|
|
1935
|
-
criteria: expected,
|
|
1936
|
-
completion: tryParse(output),
|
|
1937
|
-
...vars || {}
|
|
1938
|
-
});
|
|
1939
|
-
const resp = await callProviderWithContext(await getAndCheckProvider("text", grading.provider, (await getDefaultProviders()).gradingProvider, "model-graded-closedqa check"), prompt, "model-graded-closedqa", {
|
|
1639
|
+
const templateVars = {
|
|
1940
1640
|
input,
|
|
1941
1641
|
criteria: expected,
|
|
1942
1642
|
completion: tryParse(output),
|
|
1943
1643
|
...vars || {}
|
|
1944
|
-
}
|
|
1644
|
+
};
|
|
1645
|
+
const prompt = await renderLlmRubricPrompt(await loadRubricPrompt(grading?.rubricPrompt, OPENAI_CLOSED_QA_PROMPT), templateVars);
|
|
1646
|
+
const resp = await callProviderWithContext(await getAndCheckProvider("text", grading.provider, (await getDefaultProviders()).gradingProvider, "model-graded-closedqa check"), prompt, "model-graded-closedqa", templateVars, providerCallContext);
|
|
1945
1647
|
if (resp.error || !resp.output) return fail(resp.error || "No output", resp.tokenUsage);
|
|
1946
1648
|
invariant(typeof resp.output === "string", "model-graded-closedqa produced malformed response");
|
|
1947
1649
|
try {
|
|
@@ -1954,18 +1656,7 @@ async function matchesClosedQa(input, expected, output, grading, vars, providerC
|
|
|
1954
1656
|
pass,
|
|
1955
1657
|
score: pass ? 1 : 0,
|
|
1956
1658
|
reason,
|
|
1957
|
-
tokensUsed:
|
|
1958
|
-
total: resp.tokenUsage?.total || 0,
|
|
1959
|
-
prompt: resp.tokenUsage?.prompt || 0,
|
|
1960
|
-
completion: resp.tokenUsage?.completion || 0,
|
|
1961
|
-
cached: resp.tokenUsage?.cached || 0,
|
|
1962
|
-
numRequests: resp.tokenUsage?.numRequests || 0,
|
|
1963
|
-
completionDetails: resp.tokenUsage?.completionDetails || {
|
|
1964
|
-
reasoning: 0,
|
|
1965
|
-
acceptedPrediction: 0,
|
|
1966
|
-
rejectedPrediction: 0
|
|
1967
|
-
}
|
|
1968
|
-
}
|
|
1659
|
+
tokensUsed: normalizeMatcherTokenUsage(resp.tokenUsage)
|
|
1969
1660
|
};
|
|
1970
1661
|
} catch (err) {
|
|
1971
1662
|
return fail(`Error parsing output: ${err.message}`, resp.tokenUsage);
|
|
@@ -1975,490 +1666,51 @@ async function matchesGEval(criteria, input, output, threshold, grading, provide
|
|
|
1975
1666
|
if (!input) throw Error("No source text to estimate reply");
|
|
1976
1667
|
const maxScore = 10;
|
|
1977
1668
|
const textProvider = await getAndCheckProvider("text", grading?.provider, (await getDefaultProviders()).gradingProvider, "reply geval check");
|
|
1978
|
-
const tokensUsed =
|
|
1979
|
-
total: 0,
|
|
1980
|
-
prompt: 0,
|
|
1981
|
-
completion: 0,
|
|
1982
|
-
cached: 0,
|
|
1983
|
-
numRequests: 0,
|
|
1984
|
-
completionDetails: {
|
|
1985
|
-
reasoning: 0,
|
|
1986
|
-
acceptedPrediction: 0,
|
|
1987
|
-
rejectedPrediction: 0
|
|
1988
|
-
}
|
|
1989
|
-
};
|
|
1669
|
+
const tokensUsed = normalizeMatcherTokenUsage(void 0);
|
|
1990
1670
|
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);
|
|
1991
|
-
|
|
1671
|
+
accumulateTokenUsage(tokensUsed, respSteps.tokenUsage);
|
|
1672
|
+
if (respSteps.error) return fail(respSteps.error, tokensUsed);
|
|
1673
|
+
if (!respSteps.output) return fail("No output", tokensUsed);
|
|
1674
|
+
if (typeof respSteps.output !== "string") return fail("LLM-proposed evaluation steps response is not a string", tokensUsed);
|
|
1992
1675
|
let steps;
|
|
1993
1676
|
try {
|
|
1994
|
-
|
|
1677
|
+
const stepsMatch = respSteps.output.match(/\{"steps".+\}/g);
|
|
1678
|
+
if (!stepsMatch) return fail(`LLM-proposed evaluation steps are not in JSON format: ${respSteps.output}`, tokensUsed);
|
|
1679
|
+
steps = JSON.parse(stepsMatch[0]).steps;
|
|
1995
1680
|
if (!steps.length) return fail("LLM does not propose any evaluation step", tokensUsed);
|
|
1996
|
-
} catch {
|
|
1997
|
-
return fail(`LLM-proposed evaluation steps are not in JSON format: ${respSteps.output}`, tokensUsed);
|
|
1681
|
+
} catch (err) {
|
|
1682
|
+
return fail(`LLM-proposed evaluation steps are not in JSON format: ${err.message}\n\n${respSteps.output}`, tokensUsed);
|
|
1998
1683
|
}
|
|
1999
|
-
const
|
|
2000
|
-
|
|
2001
|
-
steps: steps.join("\n- "),
|
|
2002
|
-
maxScore: maxScore.toString(),
|
|
2003
|
-
input: tryParse(input),
|
|
2004
|
-
output: tryParse(output)
|
|
2005
|
-
}), "g-eval", {
|
|
1684
|
+
const evalPrompt = await loadRubricPrompt(typeof grading?.rubricPrompt === "object" && !Array.isArray(grading?.rubricPrompt) ? grading?.rubricPrompt?.["evaluate"] : void 0, GEVAL_PROMPT_EVALUATE);
|
|
1685
|
+
const evalVars = {
|
|
2006
1686
|
criteria,
|
|
2007
1687
|
steps: steps.join("\n- "),
|
|
2008
1688
|
maxScore: maxScore.toString(),
|
|
2009
1689
|
input: tryParse(input),
|
|
2010
1690
|
output: tryParse(output)
|
|
2011
|
-
}
|
|
2012
|
-
|
|
1691
|
+
};
|
|
1692
|
+
const resp = await callProviderWithContext(textProvider, await renderLlmRubricPrompt(evalPrompt, evalVars), "g-eval", evalVars, providerCallContext);
|
|
1693
|
+
accumulateTokenUsage(tokensUsed, resp.tokenUsage);
|
|
1694
|
+
if (resp.error) return fail(resp.error, tokensUsed);
|
|
1695
|
+
if (!resp.output) return fail("No output", tokensUsed);
|
|
1696
|
+
if (typeof resp.output !== "string") return fail("LLM-proposed evaluation result response is not a string", tokensUsed);
|
|
2013
1697
|
let result;
|
|
2014
1698
|
try {
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
1699
|
+
const resultMatch = resp.output.match(/\{.+\}/g);
|
|
1700
|
+
if (!resultMatch) return fail(`LLM-proposed evaluation result is not in JSON format: ${resp.output}`, tokensUsed);
|
|
1701
|
+
result = JSON.parse(resultMatch[0]);
|
|
1702
|
+
} catch (err) {
|
|
1703
|
+
return fail(`LLM-proposed evaluation result is not in JSON format: ${err.message}\n\n${resp.output}`, tokensUsed);
|
|
2018
1704
|
}
|
|
1705
|
+
const rawScore = typeof result.score === "number" ? result.score : Number(result.score);
|
|
1706
|
+
if (!Number.isFinite(rawScore)) return fail(`G-Eval result has invalid or missing score: ${JSON.stringify(result.score)}`, tokensUsed);
|
|
2019
1707
|
return {
|
|
2020
|
-
pass:
|
|
2021
|
-
score:
|
|
1708
|
+
pass: rawScore / maxScore >= threshold,
|
|
1709
|
+
score: rawScore / maxScore,
|
|
2022
1710
|
reason: result.reason,
|
|
2023
1711
|
tokensUsed
|
|
2024
1712
|
};
|
|
2025
1713
|
}
|
|
2026
|
-
async function matchesAnswerRelevance(input, output, threshold, grading, providerCallContext) {
|
|
2027
|
-
const embeddingProvider = await getAndCheckProvider("embedding", grading?.provider, (await getDefaultProviders()).embeddingProvider, "answer relevancy check");
|
|
2028
|
-
const textProvider = await getAndCheckProvider("text", grading?.provider, (await getDefaultProviders()).gradingProvider, "answer relevancy check");
|
|
2029
|
-
const tokensUsed = {
|
|
2030
|
-
total: 0,
|
|
2031
|
-
prompt: 0,
|
|
2032
|
-
completion: 0,
|
|
2033
|
-
cached: 0,
|
|
2034
|
-
numRequests: 0,
|
|
2035
|
-
completionDetails: {
|
|
2036
|
-
reasoning: 0,
|
|
2037
|
-
acceptedPrediction: 0,
|
|
2038
|
-
rejectedPrediction: 0
|
|
2039
|
-
}
|
|
2040
|
-
};
|
|
2041
|
-
const candidateQuestions = [];
|
|
2042
|
-
for (let i = 0; i < 3; i++) {
|
|
2043
|
-
const resp = await callProviderWithContext(textProvider, await renderLlmRubricPrompt(await loadRubricPrompt(grading?.rubricPrompt, ANSWER_RELEVANCY_GENERATE), { answer: tryParse(output) }), "answer-relevance", { answer: tryParse(output) }, providerCallContext);
|
|
2044
|
-
accumulateTokens(tokensUsed, resp.tokenUsage);
|
|
2045
|
-
if (resp.error || !resp.output) return fail(resp.error || "No output", tokensUsed);
|
|
2046
|
-
invariant(typeof resp.output === "string", "answer relevancy check produced malformed response");
|
|
2047
|
-
candidateQuestions.push(resp.output);
|
|
2048
|
-
}
|
|
2049
|
-
invariant(typeof embeddingProvider.callEmbeddingApi === "function", `Provider ${embeddingProvider.id} must implement callEmbeddingApi for similarity check`);
|
|
2050
|
-
const inputEmbeddingResp = await embeddingProvider.callEmbeddingApi(input);
|
|
2051
|
-
accumulateTokens(tokensUsed, inputEmbeddingResp.tokenUsage);
|
|
2052
|
-
if (inputEmbeddingResp.error || !inputEmbeddingResp.embedding) return fail(inputEmbeddingResp.error || "No embedding", tokensUsed);
|
|
2053
|
-
const inputEmbedding = inputEmbeddingResp.embedding;
|
|
2054
|
-
const similarities = [];
|
|
2055
|
-
const questionsWithScores = [];
|
|
2056
|
-
for (const question of candidateQuestions) {
|
|
2057
|
-
const resp = await embeddingProvider.callEmbeddingApi(question);
|
|
2058
|
-
accumulateTokens(tokensUsed, resp.tokenUsage);
|
|
2059
|
-
if (resp.error || !resp.embedding) return fail(resp.error || "No embedding", tokensUsed);
|
|
2060
|
-
const questionSimilarity = cosineSimilarity(inputEmbedding, resp.embedding);
|
|
2061
|
-
similarities.push(questionSimilarity);
|
|
2062
|
-
questionsWithScores.push({
|
|
2063
|
-
question,
|
|
2064
|
-
similarity: questionSimilarity
|
|
2065
|
-
});
|
|
2066
|
-
}
|
|
2067
|
-
const similarity = similarities.reduce((a, b) => a + b, 0) / similarities.length;
|
|
2068
|
-
const pass = similarity >= threshold - Number.EPSILON;
|
|
2069
|
-
const greaterThanReason = `Relevance ${similarity.toFixed(2)} is greater than threshold ${threshold}`;
|
|
2070
|
-
const lessThanReason = `Relevance ${similarity.toFixed(2)} is less than threshold ${threshold}`;
|
|
2071
|
-
const metadata = {
|
|
2072
|
-
generatedQuestions: questionsWithScores,
|
|
2073
|
-
averageSimilarity: similarity,
|
|
2074
|
-
threshold
|
|
2075
|
-
};
|
|
2076
|
-
if (pass) return {
|
|
2077
|
-
pass: true,
|
|
2078
|
-
score: similarity,
|
|
2079
|
-
reason: greaterThanReason,
|
|
2080
|
-
tokensUsed,
|
|
2081
|
-
metadata
|
|
2082
|
-
};
|
|
2083
|
-
return {
|
|
2084
|
-
pass: false,
|
|
2085
|
-
score: similarity,
|
|
2086
|
-
reason: lessThanReason,
|
|
2087
|
-
tokensUsed,
|
|
2088
|
-
metadata
|
|
2089
|
-
};
|
|
2090
|
-
}
|
|
2091
|
-
async function matchesContextRecall(context, groundTruth, threshold, grading, vars, providerCallContext) {
|
|
2092
|
-
const textProvider = await getAndCheckProvider("text", grading?.provider, (await getDefaultProviders()).gradingProvider, "context recall check");
|
|
2093
|
-
const contextString = serializeContext(context);
|
|
2094
|
-
const resp = await callProviderWithContext(textProvider, await renderLlmRubricPrompt(await loadRubricPrompt(grading?.rubricPrompt, CONTEXT_RECALL), {
|
|
2095
|
-
context: contextString,
|
|
2096
|
-
groundTruth,
|
|
2097
|
-
...vars || {}
|
|
2098
|
-
}), "context-recall", {
|
|
2099
|
-
context: contextString,
|
|
2100
|
-
groundTruth,
|
|
2101
|
-
...vars || {}
|
|
2102
|
-
}, providerCallContext);
|
|
2103
|
-
if (resp.error || !resp.output) return fail(resp.error || "No output", resp.tokenUsage);
|
|
2104
|
-
invariant(typeof resp.output === "string", "context-recall produced malformed response");
|
|
2105
|
-
const attributedTokenLower = CONTEXT_RECALL_ATTRIBUTED_TOKEN.toLowerCase();
|
|
2106
|
-
const notAttributedTokenLower = CONTEXT_RECALL_NOT_ATTRIBUTED_TOKEN.toLowerCase();
|
|
2107
|
-
const sentences = splitIntoSentences(resp.output).filter((line) => {
|
|
2108
|
-
const lowerLine = line.toLowerCase();
|
|
2109
|
-
return lowerLine.includes(attributedTokenLower) || lowerLine.includes(notAttributedTokenLower);
|
|
2110
|
-
});
|
|
2111
|
-
const sentenceAttributions = [];
|
|
2112
|
-
let numerator = 0;
|
|
2113
|
-
for (const sentence of sentences) {
|
|
2114
|
-
const isAttributed = sentence.toLowerCase().includes(attributedTokenLower);
|
|
2115
|
-
if (isAttributed) numerator++;
|
|
2116
|
-
const sentenceMatch = sentence.match(/^\d+\.\s*([^\.]+\.)/);
|
|
2117
|
-
const cleanSentence = sentenceMatch ? sentenceMatch[1].trim() : sentence.split(".")[0].trim();
|
|
2118
|
-
sentenceAttributions.push({
|
|
2119
|
-
sentence: cleanSentence,
|
|
2120
|
-
attributed: isAttributed
|
|
2121
|
-
});
|
|
2122
|
-
}
|
|
2123
|
-
const score = sentences.length > 0 ? numerator / sentences.length : 0;
|
|
2124
|
-
const pass = score >= threshold - Number.EPSILON;
|
|
2125
|
-
const metadata = {
|
|
2126
|
-
sentenceAttributions,
|
|
2127
|
-
totalSentences: sentences.length,
|
|
2128
|
-
attributedSentences: numerator,
|
|
2129
|
-
score
|
|
2130
|
-
};
|
|
2131
|
-
return {
|
|
2132
|
-
pass,
|
|
2133
|
-
score,
|
|
2134
|
-
reason: pass ? `Recall ${score.toFixed(2)} is >= ${threshold}` : `Recall ${score.toFixed(2)} is < ${threshold}`,
|
|
2135
|
-
tokensUsed: {
|
|
2136
|
-
total: resp.tokenUsage?.total || 0,
|
|
2137
|
-
prompt: resp.tokenUsage?.prompt || 0,
|
|
2138
|
-
completion: resp.tokenUsage?.completion || 0,
|
|
2139
|
-
cached: resp.tokenUsage?.cached || 0,
|
|
2140
|
-
numRequests: resp.tokenUsage?.numRequests || 0,
|
|
2141
|
-
completionDetails: resp.tokenUsage?.completionDetails || {
|
|
2142
|
-
reasoning: 0,
|
|
2143
|
-
acceptedPrediction: 0,
|
|
2144
|
-
rejectedPrediction: 0
|
|
2145
|
-
}
|
|
2146
|
-
},
|
|
2147
|
-
metadata
|
|
2148
|
-
};
|
|
2149
|
-
}
|
|
2150
|
-
async function matchesContextRelevance(question, context, threshold, grading, providerCallContext) {
|
|
2151
|
-
const textProvider = await getAndCheckProvider("text", grading?.provider, (await getDefaultProviders()).gradingProvider, "context relevance check");
|
|
2152
|
-
const contextString = serializeContext(context);
|
|
2153
|
-
const resp = await callProviderWithContext(textProvider, await renderLlmRubricPrompt(await loadRubricPrompt(grading?.rubricPrompt, CONTEXT_RELEVANCE), {
|
|
2154
|
-
context: contextString,
|
|
2155
|
-
query: question
|
|
2156
|
-
}), "context-relevance", {
|
|
2157
|
-
context: contextString,
|
|
2158
|
-
query: question
|
|
2159
|
-
}, providerCallContext);
|
|
2160
|
-
if (resp.error || !resp.output) return fail(resp.error || "No output", resp.tokenUsage);
|
|
2161
|
-
invariant(typeof resp.output === "string", "context-relevance produced malformed response");
|
|
2162
|
-
const contextUnits = Array.isArray(context) ? context.filter((chunk) => chunk.trim().length > 0) : splitIntoSentences(context);
|
|
2163
|
-
const totalContextUnits = contextUnits.length;
|
|
2164
|
-
const extractedSentences = splitIntoSentences(resp.output);
|
|
2165
|
-
const relevantSentences = [];
|
|
2166
|
-
const insufficientInformation = resp.output.includes(CONTEXT_RELEVANCE_BAD);
|
|
2167
|
-
let numerator = 0;
|
|
2168
|
-
if (insufficientInformation) numerator = 0;
|
|
2169
|
-
else {
|
|
2170
|
-
numerator = extractedSentences.length;
|
|
2171
|
-
relevantSentences.push(...extractedSentences);
|
|
2172
|
-
}
|
|
2173
|
-
const score = totalContextUnits > 0 ? numerator / totalContextUnits : 0;
|
|
2174
|
-
const pass = score >= threshold - Number.EPSILON;
|
|
2175
|
-
const metadata = {
|
|
2176
|
-
extractedSentences: relevantSentences,
|
|
2177
|
-
totalContextUnits,
|
|
2178
|
-
totalContextSentences: totalContextUnits,
|
|
2179
|
-
contextUnits,
|
|
2180
|
-
relevantSentenceCount: numerator,
|
|
2181
|
-
insufficientInformation,
|
|
2182
|
-
score
|
|
2183
|
-
};
|
|
2184
|
-
return {
|
|
2185
|
-
pass,
|
|
2186
|
-
score,
|
|
2187
|
-
reason: pass ? `Context relevance ${score.toFixed(2)} is >= ${threshold}` : `Context relevance ${score.toFixed(2)} is < ${threshold}`,
|
|
2188
|
-
tokensUsed: {
|
|
2189
|
-
total: resp.tokenUsage?.total || 0,
|
|
2190
|
-
prompt: resp.tokenUsage?.prompt || 0,
|
|
2191
|
-
completion: resp.tokenUsage?.completion || 0,
|
|
2192
|
-
cached: resp.tokenUsage?.cached || 0,
|
|
2193
|
-
numRequests: resp.tokenUsage?.numRequests || 0,
|
|
2194
|
-
completionDetails: resp.tokenUsage?.completionDetails || {
|
|
2195
|
-
reasoning: 0,
|
|
2196
|
-
acceptedPrediction: 0,
|
|
2197
|
-
rejectedPrediction: 0
|
|
2198
|
-
}
|
|
2199
|
-
},
|
|
2200
|
-
metadata
|
|
2201
|
-
};
|
|
2202
|
-
}
|
|
2203
|
-
async function matchesContextFaithfulness(query, output, context, threshold, grading, vars, providerCallContext) {
|
|
2204
|
-
const textProvider = await getAndCheckProvider("text", grading?.provider, (await getDefaultProviders()).gradingProvider, "faithfulness check");
|
|
2205
|
-
const tokensUsed = {
|
|
2206
|
-
total: 0,
|
|
2207
|
-
prompt: 0,
|
|
2208
|
-
completion: 0,
|
|
2209
|
-
cached: 0,
|
|
2210
|
-
numRequests: 0,
|
|
2211
|
-
completionDetails: {
|
|
2212
|
-
reasoning: 0,
|
|
2213
|
-
acceptedPrediction: 0,
|
|
2214
|
-
rejectedPrediction: 0
|
|
2215
|
-
}
|
|
2216
|
-
};
|
|
2217
|
-
if (grading?.rubricPrompt) invariant(Array.isArray(grading.rubricPrompt), "rubricPrompt must be an array");
|
|
2218
|
-
const rawLongformPrompt = typeof grading?.rubricPrompt?.[0] === "string" ? grading?.rubricPrompt?.[0] : grading?.rubricPrompt?.[0]?.content;
|
|
2219
|
-
const rawNliPrompt = typeof grading?.rubricPrompt?.[1] === "string" ? grading?.rubricPrompt?.[1] : grading?.rubricPrompt?.[1]?.content;
|
|
2220
|
-
const longformPrompt = await loadRubricPrompt(rawLongformPrompt, CONTEXT_FAITHFULNESS_LONGFORM);
|
|
2221
|
-
const nliPrompt = await loadRubricPrompt(rawNliPrompt, CONTEXT_FAITHFULNESS_NLI_STATEMENTS);
|
|
2222
|
-
let promptText = await renderLlmRubricPrompt(longformPrompt, {
|
|
2223
|
-
question: query,
|
|
2224
|
-
answer: tryParse(output),
|
|
2225
|
-
...vars || {}
|
|
2226
|
-
});
|
|
2227
|
-
let resp = await callProviderWithContext(textProvider, promptText, "context-faithfulness-longform", {
|
|
2228
|
-
question: query,
|
|
2229
|
-
answer: tryParse(output),
|
|
2230
|
-
...vars || {}
|
|
2231
|
-
}, providerCallContext);
|
|
2232
|
-
accumulateTokens(tokensUsed, resp.tokenUsage);
|
|
2233
|
-
if (resp.error || !resp.output) return fail(resp.error || "No output", tokensUsed);
|
|
2234
|
-
invariant(typeof resp.output === "string", "context-faithfulness produced malformed response");
|
|
2235
|
-
const contextString = serializeContext(context);
|
|
2236
|
-
const statements = splitIntoSentences(resp.output);
|
|
2237
|
-
promptText = await renderLlmRubricPrompt(nliPrompt, {
|
|
2238
|
-
context: contextString,
|
|
2239
|
-
statements,
|
|
2240
|
-
...vars || {}
|
|
2241
|
-
});
|
|
2242
|
-
resp = await callProviderWithContext(textProvider, promptText, "context-faithfulness-nli", {
|
|
2243
|
-
context: contextString,
|
|
2244
|
-
statements,
|
|
2245
|
-
...vars || {}
|
|
2246
|
-
}, providerCallContext);
|
|
2247
|
-
accumulateTokens(tokensUsed, resp.tokenUsage);
|
|
2248
|
-
if (resp.error || !resp.output) return fail(resp.error || "No output", tokensUsed);
|
|
2249
|
-
invariant(typeof resp.output === "string", "context-faithfulness produced malformed response");
|
|
2250
|
-
let finalAnswer = "Final verdict for each statement in order:";
|
|
2251
|
-
finalAnswer = finalAnswer.toLowerCase();
|
|
2252
|
-
let verdicts = resp.output.toLowerCase().trim();
|
|
2253
|
-
let score = 0;
|
|
2254
|
-
if (statements.length > 0) if (verdicts.includes(finalAnswer)) {
|
|
2255
|
-
verdicts = verdicts.slice(verdicts.indexOf(finalAnswer) + finalAnswer.length);
|
|
2256
|
-
const parsedVerdicts = verdicts.split(".").filter((answer) => answer.trim() !== "");
|
|
2257
|
-
if (parsedVerdicts.length > 0) score = 1 - parsedVerdicts.filter((answer) => !answer.includes("yes")).length / statements.length;
|
|
2258
|
-
} else {
|
|
2259
|
-
const noVerdictCount = verdicts.split("verdict: no").length - 1;
|
|
2260
|
-
if (noVerdictCount + (verdicts.split("verdict: yes").length - 1) > 0) score = 1 - noVerdictCount / statements.length;
|
|
2261
|
-
}
|
|
2262
|
-
score = Math.min(1, Math.max(0, score));
|
|
2263
|
-
const pass = score >= threshold - Number.EPSILON;
|
|
2264
|
-
return {
|
|
2265
|
-
pass,
|
|
2266
|
-
score,
|
|
2267
|
-
reason: pass ? `Faithfulness ${score.toFixed(2)} is >= ${threshold}` : `Faithfulness ${score.toFixed(2)} is < ${threshold}`,
|
|
2268
|
-
tokensUsed
|
|
2269
|
-
};
|
|
2270
|
-
}
|
|
2271
|
-
async function matchesSelectBest(criteria, outputs, grading, vars, providerCallContext) {
|
|
2272
|
-
invariant(outputs.length >= 2, "select-best assertion must have at least two outputs to compare between");
|
|
2273
|
-
const resp = await callProviderWithContext(await getAndCheckProvider("text", grading?.provider, (await getDefaultProviders()).gradingProvider, "select-best check"), await renderLlmRubricPrompt(await loadRubricPrompt(grading?.rubricPrompt, SELECT_BEST_PROMPT), {
|
|
2274
|
-
criteria,
|
|
2275
|
-
outputs: outputs.map((o) => tryParse(o)),
|
|
2276
|
-
...vars || {}
|
|
2277
|
-
}), "select-best", {
|
|
2278
|
-
criteria,
|
|
2279
|
-
outputs: outputs.map((o) => tryParse(o)),
|
|
2280
|
-
...vars || {}
|
|
2281
|
-
}, providerCallContext);
|
|
2282
|
-
if (resp.error || !resp.output) return new Array(outputs.length).fill(fail(resp.error || "No output", resp.tokenUsage));
|
|
2283
|
-
invariant(typeof resp.output === "string", "select-best produced malformed response");
|
|
2284
|
-
const firstDigitMatch = resp.output.trim().match(/\d/);
|
|
2285
|
-
const verdict = firstDigitMatch ? Number.parseInt(firstDigitMatch[0], 10) : NaN;
|
|
2286
|
-
if (Number.isNaN(verdict) || verdict < 0 || verdict >= outputs.length) return new Array(outputs.length).fill(fail(`Invalid select-best verdict: ${verdict}`));
|
|
2287
|
-
const tokensUsed = {
|
|
2288
|
-
total: resp.tokenUsage?.total || 0,
|
|
2289
|
-
prompt: resp.tokenUsage?.prompt || 0,
|
|
2290
|
-
completion: resp.tokenUsage?.completion || 0,
|
|
2291
|
-
cached: resp.tokenUsage?.cached || 0,
|
|
2292
|
-
numRequests: resp.tokenUsage?.numRequests || 0,
|
|
2293
|
-
completionDetails: resp.tokenUsage?.completionDetails || {
|
|
2294
|
-
reasoning: 0,
|
|
2295
|
-
acceptedPrediction: 0,
|
|
2296
|
-
rejectedPrediction: 0
|
|
2297
|
-
}
|
|
2298
|
-
};
|
|
2299
|
-
return outputs.map((_output, index) => {
|
|
2300
|
-
if (index === verdict) return {
|
|
2301
|
-
pass: true,
|
|
2302
|
-
score: 1,
|
|
2303
|
-
reason: `Output selected as the best: ${criteria}`,
|
|
2304
|
-
tokensUsed
|
|
2305
|
-
};
|
|
2306
|
-
else return {
|
|
2307
|
-
pass: false,
|
|
2308
|
-
score: 0,
|
|
2309
|
-
reason: `Output not selected: ${criteria}`,
|
|
2310
|
-
tokensUsed
|
|
2311
|
-
};
|
|
2312
|
-
});
|
|
2313
|
-
}
|
|
2314
|
-
async function selectMaxScore(outputs, resultsWithGradingResults, assertion) {
|
|
2315
|
-
invariant(outputs.length >= 2, "max-score assertion must have at least two outputs to compare between");
|
|
2316
|
-
const value = assertion.value || {};
|
|
2317
|
-
const options = {
|
|
2318
|
-
method: typeof value === "object" && "method" in value ? value.method : "average",
|
|
2319
|
-
weights: typeof value === "object" && "weights" in value ? value.weights : {},
|
|
2320
|
-
threshold: typeof value === "object" && "threshold" in value ? value.threshold : void 0
|
|
2321
|
-
};
|
|
2322
|
-
const scores = resultsWithGradingResults.map((result, index) => {
|
|
2323
|
-
const relevantResults = (result.gradingResult?.componentResults || []).filter((r) => r.assertion && r.assertion.type !== "max-score" && r.assertion.type !== "select-best");
|
|
2324
|
-
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");
|
|
2325
|
-
let totalWeightedScore = 0;
|
|
2326
|
-
let totalWeight = 0;
|
|
2327
|
-
relevantResults.forEach((componentResult) => {
|
|
2328
|
-
const assertionType = componentResult.assertion?.type || "unknown";
|
|
2329
|
-
const weight = options.weights[assertionType] === void 0 ? 1 : options.weights[assertionType];
|
|
2330
|
-
const score = componentResult.score || 0;
|
|
2331
|
-
totalWeightedScore += score * weight;
|
|
2332
|
-
totalWeight += weight;
|
|
2333
|
-
});
|
|
2334
|
-
let aggregateScore;
|
|
2335
|
-
if (options.method === "sum") aggregateScore = totalWeightedScore;
|
|
2336
|
-
else aggregateScore = totalWeight > 0 ? totalWeightedScore / totalWeight : 0;
|
|
2337
|
-
return {
|
|
2338
|
-
index,
|
|
2339
|
-
score: aggregateScore,
|
|
2340
|
-
componentCount: relevantResults.length,
|
|
2341
|
-
totalWeight
|
|
2342
|
-
};
|
|
2343
|
-
});
|
|
2344
|
-
let maxScore = -Infinity;
|
|
2345
|
-
let winnerIndex = 0;
|
|
2346
|
-
for (let i = 0; i < scores.length; i++) if (scores[i].score > maxScore) {
|
|
2347
|
-
maxScore = scores[i].score;
|
|
2348
|
-
winnerIndex = i;
|
|
2349
|
-
}
|
|
2350
|
-
const meetsThreshold = options.threshold === void 0 || maxScore >= options.threshold;
|
|
2351
|
-
return scores.map(({ index, score, componentCount, totalWeight }) => {
|
|
2352
|
-
const isWinner = index === winnerIndex && meetsThreshold;
|
|
2353
|
-
return {
|
|
2354
|
-
pass: isWinner,
|
|
2355
|
-
score: isWinner ? 1 : 0,
|
|
2356
|
-
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)})`,
|
|
2357
|
-
namedScores: {
|
|
2358
|
-
maxScore: score,
|
|
2359
|
-
assertionCount: componentCount,
|
|
2360
|
-
totalWeight
|
|
2361
|
-
}
|
|
2362
|
-
};
|
|
2363
|
-
});
|
|
2364
|
-
}
|
|
2365
|
-
async function matchesSearchRubric(rubric, llmOutput, grading, vars, assertion, _provider, providerCallContext) {
|
|
2366
|
-
if (!grading) throw new Error("Cannot grade output without grading config. Specify --grader option or grading config.");
|
|
2367
|
-
const defaultProviders = await getDefaultProviders();
|
|
2368
|
-
const defaultSearchProviders = [
|
|
2369
|
-
defaultProviders.webSearchProvider,
|
|
2370
|
-
defaultProviders.llmRubricProvider,
|
|
2371
|
-
defaultProviders.gradingProvider
|
|
2372
|
-
];
|
|
2373
|
-
let searchProvider = (grading.provider ? await getGradingProvider("text", grading.provider, null) : null) || defaultSearchProviders.find((provider) => Boolean(provider));
|
|
2374
|
-
if (!hasWebSearchCapability(searchProvider)) {
|
|
2375
|
-
const webSearchDefault = defaultSearchProviders.find((provider) => hasWebSearchCapability(provider));
|
|
2376
|
-
if (webSearchDefault) searchProvider = webSearchDefault;
|
|
2377
|
-
}
|
|
2378
|
-
if (!hasWebSearchCapability(searchProvider)) {
|
|
2379
|
-
const webSearchProvider = await loadWebSearchProvider(true);
|
|
2380
|
-
if (webSearchProvider) searchProvider = webSearchProvider;
|
|
2381
|
-
}
|
|
2382
|
-
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");
|
|
2383
|
-
const prompt = await renderLlmRubricPrompt(await loadRubricPrompt(grading?.rubricPrompt, DEFAULT_WEB_SEARCH_PROMPT), {
|
|
2384
|
-
output: tryParse(llmOutput),
|
|
2385
|
-
rubric,
|
|
2386
|
-
...vars || {}
|
|
2387
|
-
});
|
|
2388
|
-
const resp = await callProviderWithContext(searchProvider, prompt, "search-rubric", {
|
|
2389
|
-
output: tryParse(llmOutput),
|
|
2390
|
-
rubric,
|
|
2391
|
-
...vars || {}
|
|
2392
|
-
}, providerCallContext);
|
|
2393
|
-
if (resp.error || !resp.output) return {
|
|
2394
|
-
pass: false,
|
|
2395
|
-
score: 0,
|
|
2396
|
-
reason: `Search rubric evaluation failed: ${resp.error || "No output"}`,
|
|
2397
|
-
tokensUsed: resp.tokenUsage,
|
|
2398
|
-
assertion
|
|
2399
|
-
};
|
|
2400
|
-
try {
|
|
2401
|
-
const result = extractFirstJsonObject(String(resp.output));
|
|
2402
|
-
let pass = result.pass ?? false;
|
|
2403
|
-
const score = typeof result.score === "number" ? result.score : pass ? 1 : 0;
|
|
2404
|
-
if (assertion?.threshold !== void 0) pass = pass && score >= assertion.threshold;
|
|
2405
|
-
return {
|
|
2406
|
-
pass,
|
|
2407
|
-
score,
|
|
2408
|
-
reason: result.reason || "No reason provided",
|
|
2409
|
-
tokensUsed: resp.tokenUsage,
|
|
2410
|
-
assertion,
|
|
2411
|
-
metadata: {
|
|
2412
|
-
searchResults: result.searchResults || [],
|
|
2413
|
-
searchProvider: searchProvider.id()
|
|
2414
|
-
}
|
|
2415
|
-
};
|
|
2416
|
-
} catch {
|
|
2417
|
-
const outputLower = String(resp.output).toLowerCase();
|
|
2418
|
-
const pass = outputLower.includes("\"pass\":true") || outputLower.includes("\"pass\": true");
|
|
2419
|
-
return {
|
|
2420
|
-
pass,
|
|
2421
|
-
score: pass ? 1 : 0,
|
|
2422
|
-
reason: resp.output,
|
|
2423
|
-
tokensUsed: resp.tokenUsage,
|
|
2424
|
-
assertion
|
|
2425
|
-
};
|
|
2426
|
-
}
|
|
2427
|
-
}
|
|
2428
|
-
async function matchesModeration({ userPrompt, assistantResponse, categories = [] }, grading) {
|
|
2429
|
-
if (!assistantResponse) return {
|
|
2430
|
-
pass: true,
|
|
2431
|
-
score: 1,
|
|
2432
|
-
reason: "No output to moderate"
|
|
2433
|
-
};
|
|
2434
|
-
const defaultProviders = await getDefaultProviders();
|
|
2435
|
-
const defaultModerationProvider = !getEnvString("OPENAI_API_KEY") && (getEnvString("REPLICATE_API_KEY") || getEnvString("REPLICATE_API_TOKEN")) ? await loadApiProvider(LLAMA_GUARD_REPLICATE_PROVIDER) : defaultProviders.moderationProvider;
|
|
2436
|
-
const moderationProvider = await getAndCheckProvider("moderation", grading?.provider, defaultModerationProvider, "moderation check");
|
|
2437
|
-
invariant(moderationProvider, "Moderation provider must be defined");
|
|
2438
|
-
const resp = await moderationProvider.callModerationApi(userPrompt, assistantResponse);
|
|
2439
|
-
if (resp.error) return {
|
|
2440
|
-
pass: false,
|
|
2441
|
-
score: 0,
|
|
2442
|
-
reason: `Moderation API error: ${resp.error}`
|
|
2443
|
-
};
|
|
2444
|
-
const { flags } = resp;
|
|
2445
|
-
if (!flags || flags.length === 0) return {
|
|
2446
|
-
pass: true,
|
|
2447
|
-
score: 1,
|
|
2448
|
-
reason: "No moderation flags detected"
|
|
2449
|
-
};
|
|
2450
|
-
const filteredFlags = categories.length === 0 ? flags : flags.filter((flag) => categories.includes(flag.code));
|
|
2451
|
-
if (filteredFlags.length > 0) return {
|
|
2452
|
-
pass: false,
|
|
2453
|
-
score: 0,
|
|
2454
|
-
reason: `Moderation flags detected: ${filteredFlags.map((flag) => flag.description).join(", ")}`
|
|
2455
|
-
};
|
|
2456
|
-
return {
|
|
2457
|
-
pass: true,
|
|
2458
|
-
score: 1,
|
|
2459
|
-
reason: "No relevant moderation flags detected"
|
|
2460
|
-
};
|
|
2461
|
-
}
|
|
2462
1714
|
//#endregion
|
|
2463
1715
|
//#region src/integrations/huggingfaceDatasets.ts
|
|
2464
1716
|
/**
|
|
@@ -2984,7 +2236,7 @@ var RedteamPluginBase = class RedteamPluginBase {
|
|
|
2984
2236
|
const rejectedPromptLengths = [];
|
|
2985
2237
|
let rejectedPromptLimit;
|
|
2986
2238
|
for (const prompt of parsedPrompts) {
|
|
2987
|
-
const violation = getGeneratedPromptOverLimit("__prompt" in prompt ?
|
|
2239
|
+
const violation = getGeneratedPromptOverLimit("__prompt" in prompt ? prompt.__prompt : JSON.stringify(prompt), this.config.maxCharsPerMessage);
|
|
2988
2240
|
if (violation) {
|
|
2989
2241
|
rejectedPromptLengths.push(violation.length);
|
|
2990
2242
|
rejectedPromptLimit = violation.limit;
|
|
@@ -3148,10 +2400,17 @@ var RedteamGraderBase = class {
|
|
|
3148
2400
|
},
|
|
3149
2401
|
rubric: finalRubric
|
|
3150
2402
|
};
|
|
3151
|
-
const
|
|
2403
|
+
const defaultTest = typeof state.config?.defaultTest === "object" ? state.config.defaultTest : void 0;
|
|
2404
|
+
const hasConfiguredGradingProvider = Boolean(state.config?.redteam?.provider || defaultTest?.options?.provider);
|
|
2405
|
+
const grading = {
|
|
3152
2406
|
...test.options,
|
|
3153
2407
|
provider: await redteamProviderManager.getGradingProvider({ jsonOnly: true })
|
|
3154
|
-
}
|
|
2408
|
+
};
|
|
2409
|
+
if (!hasConfiguredGradingProvider) {
|
|
2410
|
+
Object.defineProperty(grading, "__promptfooPreferRemote", { value: true });
|
|
2411
|
+
logger.debug("[Redteam] No configured grading provider detected, preferring remote grading");
|
|
2412
|
+
}
|
|
2413
|
+
const grade = await matchesLlmRubric(finalRubric, llmOutput, grading);
|
|
3155
2414
|
logger.debug(`Redteam grading result for ${this.id}: - ${JSON.stringify(grade)}`);
|
|
3156
2415
|
let suggestions;
|
|
3157
2416
|
if (!grade.pass) suggestions = this.getSuggestions({
|
|
@@ -15970,6 +15229,6 @@ function getGraderById(id) {
|
|
|
15970
15229
|
return grader;
|
|
15971
15230
|
}
|
|
15972
15231
|
//#endregion
|
|
15973
|
-
export {
|
|
15232
|
+
export { CONTEXT_FAITHFULNESS_LONGFORM as $, DivergentRepetitionPlugin as A, matchesFactuality as B, getPiiLeakTestsForCategory as C, getCustomPolicies as Ct, HarmbenchPlugin as D, DEFAULT_ANTHROPIC_MODEL as Dt, ImitationPlugin as E, getDefaultProviders as Et, AegisPlugin as F, doRemoteGrading as G, matchesLlmRubric as H, RedteamGraderBase as I, readProviderPromptMap as J, processPrompts as K, RedteamPluginBase as L, CrossSessionLeakPlugin as M, ContractPlugin as N, HallucinationPlugin as O, BeavertailsPlugin as P, ANSWER_RELEVANCY_GENERATE as Q, fetchHuggingFaceDataset as R, PlinyPlugin as S, withProviderCallExecutionContext as St, IntentPlugin as T, sampleArray as Tt, matchesPiScore as U, matchesGEval as V, matchesTrajectoryGoalSuccess as W, SELECT_BEST_PROMPT as X, DEFAULT_WEB_SEARCH_PROMPT as Y, SUGGEST_PROMPTS_SYSTEM_MESSAGE as Z, PoliticsPlugin as _, loadFromJavaScriptFile as _t, UnverifiableClaimsPlugin as a, CONTEXT_RELEVANCE_BAD as at, isValidPolicyObject as b, getAndCheckProvider as bt, ToolDiscoveryPlugin as c, cosineSimilarity as ct, TeenSafetyDangerousContentPlugin as d, fail as dt, CONTEXT_FAITHFULNESS_NLI_STATEMENTS as et, TeenSafetyAgeRestrictedGoodsAndServicesPlugin as f, normalizeMatcherTokenUsage as ft, PromptExtractionPlugin as g, getFinalTest as gt, RbacPlugin as h, coerceString as ht, VLGuardPlugin as i, CONTEXT_RELEVANCE as it, DebugAccessPlugin as j, ExcessiveAgencyPlugin as k, TeenSafetyHarmfulBodyIdealsPlugin as l, dotProduct as lt, ShellInjectionPlugin as m, tryParse as mt, getGraderById as n, CONTEXT_RECALL_ATTRIBUTED_TOKEN as nt, UnsafeBenchPlugin as o, loadRubricPrompt as ot, SqlInjectionPlugin as p, splitIntoSentences as pt, readPrompts as q, VLSUPlugin as r, CONTEXT_RECALL_NOT_ATTRIBUTED_TOKEN as rt, ToxicChatPlugin as s, renderLlmRubricPrompt as st, GRADERS as t, CONTEXT_RECALL as tt, TeenSafetyDangerousRoleplayPlugin as u, euclideanDistance as ut, PolicyPlugin as v, processFileReference as vt, OverreliancePlugin as w, retryWithDeduplication as wt, makeInlinePolicyIdSync as x, getGradingProvider as xt, determinePolicyTypeFromId as y, callProviderWithContext as yt, matchesClosedQa as z };
|
|
15974
15233
|
|
|
15975
|
-
//# sourceMappingURL=graders-
|
|
15234
|
+
//# sourceMappingURL=graders-CwrbifOo.js.map
|