@botpress/evals 1.19.0-beta.14 → 1.19.0-beta.16
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/client.d.ts +9 -9
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +74 -20
- package/dist/client.js.map +4 -4
- package/dist/definition.d.ts +2 -3
- package/dist/definition.d.ts.map +1 -1
- package/dist/definition.js.map +2 -2
- package/dist/graders/index.js +74 -21
- package/dist/graders/index.js.map +2 -2
- package/dist/graders/llm.d.ts +12 -12
- package/dist/graders/llm.d.ts.map +1 -1
- package/dist/graders/llm.js +75 -30
- package/dist/graders/llm.js.map +2 -2
- package/dist/graders/response.js +65 -16
- package/dist/graders/response.js.map +2 -2
- package/dist/index.d.ts +1 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -10
- package/dist/index.js.map +3 -3
- package/dist/loader.js +39 -1
- package/dist/loader.js.map +3 -3
- package/dist/runner.d.ts +1 -5
- package/dist/runner.d.ts.map +1 -1
- package/dist/runner.js +217 -141
- package/dist/runner.js.map +4 -4
- package/dist/{spans/sse-collector.d.ts → sse-collector.d.ts} +4 -6
- package/dist/sse-collector.d.ts.map +1 -0
- package/dist/{spans/sse-collector.js → sse-collector.js} +49 -17
- package/dist/sse-collector.js.map +7 -0
- package/dist/trace.d.ts.map +1 -0
- package/dist/transformer.d.ts +2 -2
- package/dist/transformer.d.ts.map +1 -1
- package/dist/transformer.js +1 -1
- package/dist/transformer.js.map +2 -2
- package/dist/types.d.ts +33 -38
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +2 -2
- package/package.json +6 -66
- package/dist/manifest.d.ts +0 -13
- package/dist/manifest.d.ts.map +0 -1
- package/dist/spans/index.d.ts +0 -5
- package/dist/spans/index.d.ts.map +0 -1
- package/dist/spans/index.js +0 -642
- package/dist/spans/index.js.map +0 -7
- package/dist/spans/local-span-source.d.ts +0 -16
- package/dist/spans/local-span-source.d.ts.map +0 -1
- package/dist/spans/local-span-source.js +0 -478
- package/dist/spans/local-span-source.js.map +0 -7
- package/dist/spans/span-source.d.ts +0 -20
- package/dist/spans/span-source.d.ts.map +0 -1
- package/dist/spans/span-source.js +0 -1
- package/dist/spans/span-source.js.map +0 -7
- package/dist/spans/sse-collector.d.ts.map +0 -1
- package/dist/spans/sse-collector.js.map +0 -7
- package/dist/spans/trace.d.ts.map +0 -1
- package/dist/spans/vortex-span-source.d.ts +0 -34
- package/dist/spans/vortex-span-source.d.ts.map +0 -1
- package/dist/spans/vortex-span-source.js +0 -166
- package/dist/spans/vortex-span-source.js.map +0 -7
- package/dist/stores/eval-definition-loader.d.ts +0 -4
- package/dist/stores/eval-definition-loader.d.ts.map +0 -1
- package/dist/stores/eval-definition-loader.js +0 -104
- package/dist/stores/eval-definition-loader.js.map +0 -7
- package/dist/stores/eval-store.d.ts +0 -61
- package/dist/stores/eval-store.d.ts.map +0 -1
- package/dist/stores/eval-store.js +0 -1
- package/dist/stores/eval-store.js.map +0 -7
- package/dist/stores/index.d.ts +0 -8
- package/dist/stores/index.d.ts.map +0 -1
- package/dist/stores/index.js +0 -1118
- package/dist/stores/index.js.map +0 -7
- package/dist/stores/local-eval-store.d.ts +0 -66
- package/dist/stores/local-eval-store.d.ts.map +0 -1
- package/dist/stores/local-eval-store.js +0 -557
- package/dist/stores/local-eval-store.js.map +0 -7
- package/dist/stores/vortex-eval-store-entry.d.ts +0 -6
- package/dist/stores/vortex-eval-store-entry.d.ts.map +0 -1
- package/dist/stores/vortex-eval-store-entry.js +0 -664
- package/dist/stores/vortex-eval-store-entry.js.map +0 -7
- package/dist/stores/vortex-eval-store.d.ts +0 -78
- package/dist/stores/vortex-eval-store.d.ts.map +0 -1
- package/dist/stores/vortex-eval-store.js +0 -562
- package/dist/stores/vortex-eval-store.js.map +0 -7
- /package/dist/{spans/trace.d.ts → trace.d.ts} +0 -0
- /package/dist/{spans/trace.js → trace.js} +0 -0
- /package/dist/{spans/trace.js.map → trace.js.map} +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/graders/match.ts", "../../src/graders/llm.ts", "../../src/types.ts", "../../src/graders/response.ts", "../../src/graders/tools.ts", "../../src/graders/state.ts", "../../src/graders/workflow.ts", "../../src/graders/timing.ts", "../../src/graders/outcome.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Shared match utilities for assertion grading.\n * Used by tool, state, and table graders.\n */\n\nimport type { MatchOperator } from '../types'\n\n/**\n * Evaluate a single match operator against a value.\n */\nexport function matchValue(operator: MatchOperator, actual: unknown): boolean {\n // Shorthand: string means exact match\n if (typeof operator === 'string') {\n return String(actual) === operator\n }\n\n if ('equals' in operator) {\n return actual === operator.equals\n }\n\n if ('contains' in operator) {\n return String(actual).toLowerCase().includes(operator.contains.toLowerCase())\n }\n\n if ('not_contains' in operator) {\n return !String(actual).toLowerCase().includes(operator.not_contains.toLowerCase())\n }\n\n if ('matches' in operator) {\n return new RegExp(operator.matches, 'i').test(String(actual))\n }\n\n if ('in' in operator) {\n return operator.in.includes(actual)\n }\n\n if ('exists' in operator) {\n return operator.exists ? actual !== undefined && actual !== null : actual === undefined || actual === null\n }\n\n if ('gte' in operator) {\n return Number(actual) >= operator.gte\n }\n\n if ('lte' in operator) {\n return Number(actual) <= operator.lte\n }\n\n return false\n}\n\nexport function operatorToString(operator: MatchOperator): string {\n if (typeof operator === 'string') return `equals \"${operator}\"`\n if ('equals' in operator) return `equals ${JSON.stringify(operator.equals)}`\n if ('contains' in operator) return `contains \"${operator.contains}\"`\n if ('not_contains' in operator) return `not_contains \"${operator.not_contains}\"`\n if ('matches' in operator) return `matches /${operator.matches}/`\n if ('in' in operator) return `in [${operator.in.map((v) => JSON.stringify(v)).join(', ')}]`\n if ('exists' in operator) return operator.exists ? 'exists' : 'does not exist'\n if ('gte' in operator) return `>= ${operator.gte}`\n if ('lte' in operator) return `<= ${operator.lte}`\n return JSON.stringify(operator)\n}\n", "/**\n * LLM judge grader using @botpress/zai.\n * `zai.check` owns the judge prompt, output parsing, and retries on invalid model output.\n */\n\nimport type { Client } from '@botpress/client'\nimport { Cognitive } from '@botpress/cognitive'\nimport { Zai } from '@botpress/zai'\nimport type { EvalLogger, GraderResult } from '../types'\nimport { defaultLogger } from '../types'\n\nconst MODEL_ALIASES = ['fast', 'best']\n\nlet _zai: Zai | null = null\nlet _availableModels: string[] = []\nlet _judgeModel: string = 'fast'\n// When true (default), a judge that can't run is a hard FAIL, so an unavailable judge can't be\n// mistaken for success. Callers may opt into fail-open (a skipped pass) via `failClosed: false`,\n// e.g. local runs without judge credentials. Either way the result is marked `skipped: true`.\nlet _failClosed: boolean = true\nlet _log: EvalLogger = defaultLogger\n\n/** @internal Test-only: clears module judge state so tests stay hermetic in the shared bun test process. */\nexport function _resetLLMJudgeForTests(): void {\n _zai = null\n _availableModels = []\n _judgeModel = 'fast'\n _log = defaultLogger\n _failClosed = true\n}\n\n/** @internal Test-only: injects a fake Zai client so judge behavior is testable offline. */\nexport function _setLLMJudgeForTests(zai: unknown, options?: { failClosed?: boolean; model?: string }): void {\n _zai = zai as Zai\n _availableModels = ['fast']\n _judgeModel = options?.model ?? 'fast'\n _failClosed = options?.failClosed ?? true\n}\n\nfunction _isModelValid(model: string): boolean {\n if (MODEL_ALIASES.includes(model)) return true\n if (_availableModels.length === 0) return false\n\n return _availableModels.includes(model)\n}\n\n/** Initialize the LLM judge with an authenticated Botpress client. */\nexport async function initLLMJudge(\n client: Client,\n options?: { model?: string; logger?: EvalLogger; failClosed?: boolean }\n) {\n const log = options?.logger ?? defaultLogger\n _log = log\n _failClosed = options?.failClosed ?? true\n\n const cognitive = new Cognitive({ client, __experimental_beta: true })\n\n try {\n _availableModels = Array.from((await cognitive.fetchRemoteModels()).keys())\n } catch (err) {\n log.warn(`Failed to fetch available models: ${(err as Error).message}. LLM judge will be unavailable.`)\n _availableModels = []\n }\n\n _judgeModel = options?.model ?? 'fast'\n\n if (_availableModels.length === 0) {\n log.warn('No available Cognitive models: cannot validate judge model.')\n } else if (!_isModelValid(_judgeModel)) {\n log.warn(`Configured LLM judge model \"${_judgeModel}\" is invalid. Run \"adk models\" to list available models.`)\n }\n\n _zai = new Zai({ client: cognitive, modelId: _judgeModel as ConstructorParameters<typeof Zai>[0]['modelId'] })\n}\n\nexport async function gradeLLMJudge(\n botResponse: string,\n criteria: string,\n context: {\n userMessage: string\n /** @deprecated No-op: the judge is boolean (zai.check); there is no score threshold. */\n passThreshold?: number\n }\n): Promise<GraderResult> {\n const assertion = `llm_judge: \"${criteria}\"`\n\n try {\n if (!_zai) {\n _log.warn(`LLM judge unavailable for \"${criteria}\": no credentials configured (initLLMJudge not called)`)\n return {\n assertion,\n pass: !_failClosed,\n skipped: true,\n expected: criteria,\n actual: 'FAILED \u2014 LLM judge unavailable: no credentials configured',\n }\n }\n\n if (!_isModelValid(_judgeModel)) {\n return {\n assertion,\n pass: false,\n expected: criteria,\n actual: 'FAILED \u2014 invalid LLM judge model',\n }\n }\n\n const { output } = await _zai.check({ userMessage: context.userMessage, botResponse }, criteria).result()\n\n return {\n assertion,\n pass: output.value,\n expected: criteria,\n actual: `${output.value ? 'Pass' : 'Fail'} \u2014 ${output.explanation}`,\n }\n } catch (err) {\n _log.warn(`LLM judge failed for \"${criteria}\": ${(err as Error).message}`)\n return {\n assertion,\n pass: !_failClosed,\n skipped: true,\n expected: criteria,\n actual: `FAILED \u2014 LLM judge unavailable: ${(err as Error).message}`,\n }\n }\n}\n", "/**\n * Eval type definitions.\n *\n * User-facing types live in @botpress/evals so eval authors can update eval\n * tooling without tying the authoring API to the agent runtime package.\n */\n\nimport type { EvalDefinition as _EvalDefinition } from './definition'\n\nexport {\n Eval,\n type EvalDefinition,\n type EvalSetup,\n type ConversationTurn,\n type TurnAssertions,\n type OutcomeAssertions,\n type ResponseAssertion,\n type ToolAssertion,\n type StateAssertion,\n type WorkflowAssertion,\n type TimingAssertion,\n type MatchOperator,\n type NumericOperator,\n} from './definition'\n\nexport type { Span, SpanStatus } from './spans/trace'\nexport type { WaitOptions, WorkflowWaitOptions } from './spans/span-source'\nimport type { SpanSource } from './spans/span-source'\nexport type { SpanSource }\n\n/**\n * The @botpress/chat Client *class* (constructor) \u2014 not an instance. Callers\n * inject it (the CLI passes its bundled chat client) and the runner calls the\n * static `.connect()`. Typed via `typeof import(...)` so this types-only module\n * doesn't pull in a value import.\n */\nexport type ChatClient = typeof import('@botpress/chat').Client\n\n// --- Grader result (universal currency for all graders) ---\n\nexport interface GraderResult {\n assertion: string\n pass: boolean\n expected: string\n actual: string\n /**\n * True when the assertion could not actually be evaluated (e.g. the llm_judge had no credentials,\n * returned an empty response, or errored). Distinguishes a genuine pass from a \"didn't run\" pass.\n * Callers that demand a trustworthy verdict (e.g. the benchmark) should treat `skipped` as a failure.\n */\n skipped?: boolean\n}\n\n// --- Tool call extracted from traces ---\n\nexport interface ToolCall {\n name: string\n input: Record<string, unknown>\n output: string\n status: string\n}\n\n// --- Turn report ---\n\nexport interface TurnReport {\n turnIndex: number\n userMessage: string\n botResponse: string\n assertions: GraderResult[]\n pass: boolean\n /** Time spent waiting for the bot to respond (ms) */\n botDuration: number\n /** Time spent fetching traces + running graders (ms) */\n evalDuration: number\n}\n\n// --- Single eval report ---\n\nexport interface EvalReport {\n name: string\n description?: string\n type?: 'capability' | 'regression'\n tags?: string[]\n turns: TurnReport[]\n outcomeAssertions: GraderResult[]\n pass: boolean\n duration: number\n error?: string\n /** Stable EvalErrorCode when `error` came from a typed EvalRunnerError \u2014 lets consumers distinguish setup/config failures from bot failures. */\n errorCode?: string\n}\n\n// --- Progress event for real-time UI updates ---\n\nexport type EvalProgressEvent =\n | { type: 'suite_start'; totalEvals: number }\n | { type: 'eval_start'; evalName: string; index: number; totalTurns: number }\n | {\n type: 'turn_start'\n evalName: string\n evalIndex: number\n turnIndex: number\n totalTurns: number\n userMessage: string\n }\n | {\n type: 'turn_complete'\n evalName: string\n evalIndex: number\n turnIndex: number\n totalTurns: number\n turnReport: TurnReport\n }\n | { type: 'eval_complete'; evalName: string; index: number; report: EvalReport }\n | { type: 'suite_complete'; report: EvalRunReport; error?: string }\n\n// --- Eval run report (full suite) ---\n\nexport interface EvalRunReport {\n id: string\n timestamp: string\n evals: EvalReport[]\n passed: number\n failed: number\n total: number\n duration: number\n filter?: {\n names?: string[]\n tags?: string[]\n type?: 'capability' | 'regression'\n }\n /**\n * True when the suite was aborted mid-run (e.g. user clicked Stop). The\n * persisted report is partial \u2014 `evals` reflects only the completed evals,\n * and `total` matches that count, not the original suite size.\n */\n aborted?: boolean\n}\n\n// --- Bot connection info ---\n\nexport interface BotConnection {\n client: import('@botpress/client').Client\n botId: string\n}\n\n// --- Logger interface ---\n\nexport interface EvalLogger {\n info: (message: string) => void\n warn: (message: string) => void\n error: (message: string) => void\n}\n\n/**\n * Fallback when no logger is injected (programmatic use outside the CLI).\n * console rather than a no-op so warnings stay visible \u2014 a silent default\n * would hide judge failures and skipped pre-flights, the exact swallow\n * anti-pattern docs/ERROR-HANDLING.md bans. The CLI always injects its own\n * structured logger via EvalRunnerConfig.logger.\n */\nexport const defaultLogger: EvalLogger = console\n\n// --- Eval runner configuration ---\n\nexport interface EvalRunnerConfig {\n /** Authenticated Botpress client. Used for state seeding, workflow triggers, webhook discovery, and LLM judge. */\n client: import('@botpress/client').Client\n botId: string\n /** Path to the agent directory. Used to discover eval files from `<agentPath>/evals/`. Not needed when `definitions` is provided. */\n agentPath?: string\n /** Pre-loaded eval definitions. When provided, `agentPath` is not used for eval discovery. */\n definitions?: _EvalDefinition[]\n /** URL of the dev server providing traces and config. Defaults to the discovered DevConsole URL. */\n devServerUrl?: string\n /** Headers for dev-server requests, e.g. X-Agent-Path when routed through the singleton proxy. */\n devServerHeaders?: Record<string, string>\n /**\n * Optional host-provided chat client. The CLI passes its bundled chat client\n * here so the eval engine does not depend on @botpress/adk.\n */\n chatClient?: ChatClient\n onProgress?: (event: EvalProgressEvent) => void | Promise<void>\n /** Logger for warnings and errors. Defaults to console. */\n logger?: EvalLogger\n /**\n * Called for unexpected (internal-bug) eval failures that runEval folds\n * into report.error \u2014 they never propagate to the CLI's command boundary,\n * so without this hook they'd be invisible to error tracking. The CLI binds\n * this to telemetry.captureException; evals itself stays telemetry-free.\n */\n onException?: (error: unknown, properties?: Record<string, unknown>) => void\n /**\n * Optional abort signal \u2014 when fired, the suite stops starting new evals.\n * The currently running eval continues to completion (LLM calls in flight\n * cannot always be cancelled), but no further evals are started.\n */\n signal?: AbortSignal\n /** Bot-level eval options from agent.config.ts. Cascades: eval > agent config > default. */\n evalOptions?: {\n idleTimeout?: number\n /** LLM judge pass threshold (integer, 1-5). Values outside this range are clamped. Cascades: eval > agent config > default (3). */\n judgePassThreshold?: number\n /** Model to use for llm_judge assertions (e.g. 'openai:gpt-4o'). Defaults to 'fast'. */\n judgeModel?: string\n }\n /** Factory for creating span sources. Each eval gets its own instance. Defaults to LocalSpanSource (SSE from dev server). */\n createSpanSource?: () => SpanSource\n /** Externally-provided run ID. When set, the runner uses this instead of generating its own. */\n runId?: string\n /** Pre-resolved chat integration webhook ID. Skips the getBot() discovery call when provided. */\n chatWebhookId?: string\n /** Base URL for the chat service (e.g. https://chat.botpress.dev). Defaults to https://chat.botpress.cloud. */\n chatBaseUrl?: string\n}\n\n// --- Eval suite filter ---\n\nexport interface EvalFilter {\n names?: string[]\n tags?: string[]\n type?: 'capability' | 'regression'\n}\n\n// --- Transformer types (trace-driven eval engine) ---\n\nexport interface StateMutation {\n type: string // 'bot', 'user', 'conversation'\n changedKeys: string[]\n previous: unknown\n current: unknown\n swappedToFile: boolean // data['swapped_to_file'] === true\n}\n\nexport interface WorkflowSpan {\n name: string\n status: 'running' | 'ok' | 'error'\n statusFinal?: string // 'completed', 'continue', 'failed'\n}\n\nexport interface TurnData {\n messages: string[]\n toolCalls: ToolCall[]\n stateMutations: StateMutation[]\n workflowSpans: WorkflowSpan[]\n handlerDuration: number\n handlerStatus: 'ok' | 'error'\n}\n", "/**\n * Response assertion graders.\n * Checks bot response text against expected assertions.\n */\n\nimport type { ResponseAssertion, GraderResult } from '../types'\nimport { gradeLLMJudge } from './llm'\n\nexport async function gradeResponse(\n botResponse: string,\n assertions: ResponseAssertion[],\n context: { userMessage: string; judgePassThreshold?: number }\n): Promise<GraderResult[]> {\n const results: GraderResult[] = []\n\n for (const assertion of assertions) {\n if ('contains' in assertion) {\n const pass = botResponse.toLowerCase().includes(assertion.contains.toLowerCase())\n results.push({\n assertion: `contains \"${assertion.contains}\"`,\n pass,\n expected: `Response contains \"${assertion.contains}\"`,\n actual: pass ? `Found in response` : `Not found in response`,\n })\n continue\n }\n\n if ('not_contains' in assertion) {\n const pass = !botResponse.toLowerCase().includes(assertion.not_contains.toLowerCase())\n results.push({\n assertion: `not_contains \"${assertion.not_contains}\"`,\n pass,\n expected: `Response does not contain \"${assertion.not_contains}\"`,\n actual: pass ? `Not found in response` : `Found in response`,\n })\n continue\n }\n\n if ('matches' in assertion) {\n const regex = new RegExp(assertion.matches, 'i')\n const pass = regex.test(botResponse)\n results.push({\n assertion: `matches ${assertion.matches}`,\n pass,\n expected: `Response matches /${assertion.matches}/`,\n actual: pass ? `Matched` : `No match`,\n })\n continue\n }\n\n if ('llm_judge' in assertion) {\n const result = await gradeLLMJudge(botResponse, assertion.llm_judge, {\n userMessage: context.userMessage,\n ...(context.judgePassThreshold !== undefined ? { passThreshold: context.judgePassThreshold } : {}),\n })\n results.push(result)\n continue\n }\n\n // TODO: uncomment this once we support it\n // if ('similar_to' in assertion) {\n // results.push({\n // assertion: `similar_to: \"${assertion.similar_to}\"`,\n // pass: true,\n // expected: assertion.similar_to,\n // actual: 'SKIPPED \u2014 similar_to not yet implemented',\n // })\n // continue\n // }\n\n results.push({\n assertion: 'unknown',\n pass: false,\n expected: 'known assertion type',\n actual: `Unknown assertion: ${JSON.stringify(assertion)}`,\n })\n }\n\n return results\n}\n", "/**\n * Tool assertion graders.\n * Checks tool calls from traces against expected assertions.\n */\n\nimport type { ToolAssertion, ToolCall, GraderResult } from '../types'\nimport { matchValue, operatorToString } from './match'\n\nexport function gradeTools(toolCalls: ToolCall[], assertions: ToolAssertion[]): GraderResult[] {\n return assertions.map((assertion) => {\n // --- called ---\n if ('called' in assertion && !('not_called' in assertion) && !('call_order' in assertion)) {\n const matches = toolCalls.filter((tc) => tc.name === assertion.called)\n const wasCalled = matches.length > 0\n\n if (!wasCalled) {\n return {\n assertion: `tool called: ${assertion.called}`,\n pass: false,\n expected: `${assertion.called} was called`,\n actual: `Not called. Tools called: [${toolCalls.map((tc) => tc.name).join(', ') || 'none'}]`,\n }\n }\n\n // Check params if specified\n if (assertion.params) {\n const paramResults: { key: string; pass: boolean; detail: string }[] = []\n\n for (const [key, operator] of Object.entries(assertion.params)) {\n // Check across all matching calls \u2014 pass if any call matches\n const anyMatch = matches.some((tc) => matchValue(operator, tc.input[key]))\n paramResults.push({\n key,\n pass: anyMatch,\n detail: anyMatch\n ? `matched`\n : `expected ${key} ${operatorToString(operator)}, got ${JSON.stringify(matches.map((tc) => tc.input[key]))}`,\n })\n }\n\n const allParamsPass = paramResults.every((p) => p.pass)\n const failedParams = paramResults.filter((p) => !p.pass)\n\n return {\n assertion: `tool called: ${assertion.called} with params`,\n pass: allParamsPass,\n expected: `${assertion.called} called with ${Object.entries(assertion.params)\n .map(([k, v]) => `${k} ${operatorToString(v)}`)\n .join(', ')}`,\n actual: allParamsPass ? `Matched` : failedParams.map((p) => p.detail).join('; '),\n }\n }\n\n return {\n assertion: `tool called: ${assertion.called}`,\n pass: true,\n expected: `${assertion.called} was called`,\n actual: `Called ${matches.length} time(s)`,\n }\n }\n\n // --- not_called ---\n if ('not_called' in assertion) {\n const wasCalled = toolCalls.some((tc) => tc.name === assertion.not_called)\n return {\n assertion: `tool not_called: ${assertion.not_called}`,\n pass: !wasCalled,\n expected: `${assertion.not_called} was NOT called`,\n actual: wasCalled ? `Was called` : `Not called`,\n }\n }\n\n // --- call_order ---\n if ('call_order' in assertion) {\n const calledNames = toolCalls.map((tc) => tc.name)\n const expectedOrder = assertion.call_order as string[]\n\n // Check that the expected sequence appears in order (not necessarily contiguous)\n let cursor = 0\n for (const name of calledNames) {\n if (cursor < expectedOrder.length && name === expectedOrder[cursor]) {\n cursor++\n }\n }\n const inOrder = cursor === expectedOrder.length\n\n return {\n assertion: `call_order: [${expectedOrder.join(' \u2192 ')}]`,\n pass: inOrder,\n expected: `Tools called in order: [${expectedOrder.join(' \u2192 ')}]`,\n actual: `Actual order: [${calledNames.join(' \u2192 ') || 'none'}]`,\n }\n }\n\n return {\n assertion: 'unknown tool assertion',\n pass: false,\n expected: 'known assertion type',\n actual: `Unknown: ${JSON.stringify(assertion)}`,\n }\n })\n}\n", "/**\n * State assertion graders.\n * Pure functions that grade state assertions against StateMutation[] from the transformer.\n * No API calls, no retries, no BpClient.\n */\n\nimport type { StateMutation, StateAssertion, GraderResult } from '../types'\n\n/**\n * Parse a state path like \"conversation.lastCity\" into its components.\n * bot.* -> type: \"bot\", field: \"*\"\n * user.* -> type: \"user\", field: \"*\"\n * conversation.* -> type: \"conversation\", field: \"*\"\n */\nfunction parseStatePath(path: string): { type: string; field: string } {\n const dot = path.indexOf('.')\n if (dot === -1) {\n throw new Error(`Invalid state path \"${path}\" \u2014 expected \"type.field\" format`)\n }\n\n const type = path.slice(0, dot)\n const field = path.slice(dot + 1)\n\n if (type !== 'bot' && type !== 'user' && type !== 'conversation') {\n throw new Error(`Unknown state type \"${type}\" in path \"${path}\" \u2014 expected bot, user, or conversation`)\n }\n\n return { type, field }\n}\n\n/**\n * Grade state assertions using StateMutation[] from the transformer.\n *\n * - `equals`: find the LAST mutation matching the state type, extract field from `current`, deep-compare\n * - `changed: true`: check if the field appears in ANY mutation's `changedKeys` for that state type\n * - `changed: false`: check that the field appears in NO mutation's `changedKeys`\n * - Swapped state: when `swappedToFile` is true, current/previous are undefined \u2014 report a clear message\n */\nexport function gradeState(mutations: StateMutation[], assertions: StateAssertion[]): GraderResult[] {\n const results: GraderResult[] = []\n\n for (const assertion of assertions) {\n const parsed = parseStatePath(assertion.path)\n const matchingMutations = mutations.filter((m) => m.type === parsed.type)\n\n if (assertion.equals !== undefined) {\n if (matchingMutations.length === 0) {\n results.push({\n assertion: `state: ${assertion.path} equals`,\n pass: false,\n expected: JSON.stringify(assertion.equals),\n actual:\n `No state.save span found for \"${parsed.type}\" \u2014 the bot did not mutate this state during the turn. ` +\n 'If this state was seeded via setup.state, assert on the tool/action that reads it, or use a conversation turn that triggers a state write.',\n })\n continue\n }\n\n const lastMutation = matchingMutations[matchingMutations.length - 1]!\n\n if (lastMutation.swappedToFile) {\n results.push({\n assertion: `state: ${assertion.path} equals`,\n pass: false,\n expected: JSON.stringify(assertion.equals),\n actual: 'State was too large for trace-based assertion (swapped to file)',\n })\n continue\n }\n\n const currentState = lastMutation.current as Record<string, unknown> | undefined\n const actualValue = currentState ? currentState[parsed.field] : undefined\n const pass = deepEqual(actualValue, assertion.equals)\n\n results.push({\n assertion: `state: ${assertion.path} equals`,\n pass,\n expected: JSON.stringify(assertion.equals),\n actual: JSON.stringify(actualValue),\n })\n }\n\n if (assertion.changed !== undefined) {\n if (matchingMutations.length === 0) {\n results.push({\n assertion: `state: ${assertion.path} ${assertion.changed ? 'changed' : 'unchanged'}`,\n pass: !assertion.changed,\n expected: assertion.changed\n ? `Field \"${parsed.field}\" changed in a \"${parsed.type}\" state mutation`\n : `Field \"${parsed.field}\" unchanged`,\n actual: 'No state mutation found for type \"' + parsed.type + '\"',\n })\n continue\n }\n\n // Check for swapped state in any matching mutation\n const hasSwapped = matchingMutations.some((m) => m.swappedToFile)\n if (hasSwapped) {\n results.push({\n assertion: `state: ${assertion.path} ${assertion.changed ? 'changed' : 'unchanged'}`,\n pass: false,\n expected: assertion.changed\n ? `Field \"${parsed.field}\" changed in a \"${parsed.type}\" state mutation`\n : `Field \"${parsed.field}\" unchanged`,\n actual: 'State was too large for trace-based assertion (swapped to file)',\n })\n continue\n }\n\n const fieldChanged = matchingMutations.some((m) => m.changedKeys.includes(parsed.field))\n const pass = assertion.changed ? fieldChanged : !fieldChanged\n\n results.push({\n assertion: `state: ${assertion.path} ${assertion.changed ? 'changed' : 'unchanged'}`,\n pass,\n expected: assertion.changed\n ? `Field \"${parsed.field}\" changed in a \"${parsed.type}\" state mutation`\n : `Field \"${parsed.field}\" unchanged`,\n actual: fieldChanged ? `Field \"${parsed.field}\" was changed` : `Field \"${parsed.field}\" was not changed`,\n })\n }\n }\n\n return results\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true\n if (a === null || b === null) return false\n if (typeof a !== typeof b) return false\n\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false\n return a.every((v, i) => deepEqual(v, b[i]))\n }\n\n if (Array.isArray(a) !== Array.isArray(b)) return false\n\n if (typeof a === 'object' && typeof b === 'object') {\n const keysA = Object.keys(a as object)\n const keysB = Object.keys(b as object)\n if (keysA.length !== keysB.length) return false\n return keysA.every((k) => deepEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]))\n }\n\n return false\n}\n", "/**\n * Workflow assertion graders.\n * Checks workflow execution via transformer-produced WorkflowSpan data.\n */\n\nimport type { WorkflowAssertion, WorkflowSpan, GraderResult } from '../types'\n\nexport function gradeWorkflows(workflows: WorkflowSpan[], assertions: WorkflowAssertion[]): GraderResult[] {\n const results: GraderResult[] = []\n\n for (const assertion of assertions) {\n const matching = workflows.filter((wf) => wf.name === assertion.name)\n\n // entered \u2014 was the workflow triggered at all?\n if (assertion.entered !== undefined) {\n const wasEntered = matching.length > 0\n const pass = assertion.entered ? wasEntered : !wasEntered\n\n results.push({\n assertion: `workflow: ${assertion.name} ${assertion.entered ? 'entered' : 'not entered'}`,\n pass,\n expected: assertion.entered\n ? `Workflow \"${assertion.name}\" was entered`\n : `Workflow \"${assertion.name}\" was not entered`,\n actual: wasEntered ? `Found ${matching.length} workflow span(s)` : `No workflow spans found`,\n })\n }\n\n // completed \u2014 did the workflow complete?\n if (assertion.completed !== undefined) {\n const didComplete = matching.some(\n (wf) => wf.statusFinal === 'completed' || wf.status === 'ok' || wf.status === 'error'\n )\n const pass = assertion.completed ? didComplete : !didComplete\n\n results.push({\n assertion: `workflow: ${assertion.name} ${assertion.completed ? 'completed' : 'not completed'}`,\n pass,\n expected: assertion.completed\n ? `Workflow \"${assertion.name}\" completed`\n : `Workflow \"${assertion.name}\" did not complete`,\n actual: didComplete ? `Completed` : `Not completed`,\n })\n }\n }\n\n return results\n}\n", "/**\n * Timing assertion graders.\n * Checks bot response duration against expected thresholds.\n */\n\nimport type { TimingAssertion, GraderResult } from '../types'\nimport { matchValue, operatorToString } from './match'\n\nexport function gradeTiming(botDuration: number, assertions: TimingAssertion[]): GraderResult[] {\n const results: GraderResult[] = []\n\n for (const assertion of assertions) {\n const pass = matchValue(assertion.response_time, botDuration)\n const expected = operatorToString(assertion.response_time)\n\n results.push({\n assertion: `response_time ${expected}`,\n pass,\n expected: `Response time ${expected}`,\n actual: `${botDuration}ms`,\n })\n }\n\n return results\n}\n", "/**\n * Outcome assertion orchestrator.\n * Runs state and workflow graders after all conversation turns complete.\n */\n\nimport type { EvalDefinition, GraderResult, StateMutation, WorkflowSpan } from '../types'\nimport { gradeState } from './state'\nimport { gradeWorkflows } from './workflow'\n\n/**\n * Grade all outcome assertions after the conversation completes.\n * Takes transformer output (StateMutation[], WorkflowSpan[]) \u2014 no raw spans, no API calls.\n */\nexport function gradeOutcome(\n mutations: StateMutation[],\n evalDef: EvalDefinition,\n workflowSpans: WorkflowSpan[]\n): GraderResult[] {\n const outcome = evalDef.outcome\n if (!outcome) return []\n\n const results: GraderResult[] = []\n\n if (outcome.state && outcome.state.length > 0) {\n const stateResults = gradeState(mutations, outcome.state)\n results.push(...stateResults)\n }\n\n if (outcome.workflow && outcome.workflow.length > 0) {\n const workflowResults = gradeWorkflows(workflowSpans, outcome.workflow)\n results.push(...workflowResults)\n }\n\n return results\n}\n"],
|
|
5
|
-
"mappings": ";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c;AAAA,MACtC,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO;AACT;;;ACvCO,SAAS,YAAY,aAAqB,YAA+C;AAC9F,QAAM,UAA0B,CAAC;AAEjC,aAAW,aAAa,YAAY;AAClC,UAAM,OAAO,WAAW,UAAU,eAAe,WAAW;AAC5D,UAAM,WAAW,iBAAiB,UAAU,aAAa;AAEzD,YAAQ,KAAK;AAAA,MACX,WAAW,iBAAiB,QAAQ;AAAA,MACpC;AAAA,MACA,UAAU,iBAAiB,QAAQ;AAAA,MACnC,QAAQ,GAAG,WAAW;AAAA,IACxB,CAAC;AAAA,EACH;AAEA,SAAO;AACT;;;ACXO,SAAS,aACd,WACA,SACA,eACgB;AAChB,QAAM,UAAU,QAAQ;AACxB,MAAI,CAAC,QAAS,QAAO,CAAC;AAEtB,QAAM,UAA0B,CAAC;AAEjC,MAAI,QAAQ,SAAS,QAAQ,MAAM,SAAS,GAAG;AAC7C,UAAM,eAAe,WAAW,WAAW,QAAQ,KAAK;AACxD,YAAQ,KAAK,GAAG,YAAY;AAAA,EAC9B;AAEA,MAAI,QAAQ,YAAY,QAAQ,SAAS,SAAS,GAAG;AACnD,UAAM,kBAAkB,eAAe,eAAe,QAAQ,QAAQ;AACtE,YAAQ,KAAK,GAAG,eAAe;AAAA,EACjC;AAEA,SAAO;AACT;",
|
|
4
|
+
"sourcesContent": ["/**\n * Shared match utilities for assertion grading.\n * Used by tool, state, and table graders.\n */\n\nimport type { MatchOperator } from '../types'\n\n/**\n * Evaluate a single match operator against a value.\n */\nexport function matchValue(operator: MatchOperator, actual: unknown): boolean {\n // Shorthand: string means exact match\n if (typeof operator === 'string') {\n return String(actual) === operator\n }\n\n if ('equals' in operator) {\n return actual === operator.equals\n }\n\n if ('contains' in operator) {\n return String(actual).toLowerCase().includes(operator.contains.toLowerCase())\n }\n\n if ('not_contains' in operator) {\n return !String(actual).toLowerCase().includes(operator.not_contains.toLowerCase())\n }\n\n if ('matches' in operator) {\n return new RegExp(operator.matches, 'i').test(String(actual))\n }\n\n if ('in' in operator) {\n return operator.in.includes(actual)\n }\n\n if ('exists' in operator) {\n return operator.exists ? actual !== undefined && actual !== null : actual === undefined || actual === null\n }\n\n if ('gte' in operator) {\n return Number(actual) >= operator.gte\n }\n\n if ('lte' in operator) {\n return Number(actual) <= operator.lte\n }\n\n return false\n}\n\nexport function operatorToString(operator: MatchOperator): string {\n if (typeof operator === 'string') return `equals \"${operator}\"`\n if ('equals' in operator) return `equals ${JSON.stringify(operator.equals)}`\n if ('contains' in operator) return `contains \"${operator.contains}\"`\n if ('not_contains' in operator) return `not_contains \"${operator.not_contains}\"`\n if ('matches' in operator) return `matches /${operator.matches}/`\n if ('in' in operator) return `in [${operator.in.map((v) => JSON.stringify(v)).join(', ')}]`\n if ('exists' in operator) return operator.exists ? 'exists' : 'does not exist'\n if ('gte' in operator) return `>= ${operator.gte}`\n if ('lte' in operator) return `<= ${operator.lte}`\n return JSON.stringify(operator)\n}\n", "/**\n * LLM judge grader using @botpress/cognitive.\n * Replaces the OpenAI-based implementation from the standalone project.\n */\n\nimport { Client } from '@botpress/client'\nimport { Cognitive } from '@botpress/cognitive'\nimport type { EvalLogger, GraderResult } from '../types'\nimport { defaultLogger } from '../types'\n\nconst DEFAULT_PASS_THRESHOLD = 3\n\nfunction buildJudgeSystemPrompt(passThreshold: number): string {\n return `You are an evaluation judge for a chatbot. You will be given:\n- The user's message\n- The bot's response\n- Grading criteria\n\nYour job is to determine if the bot's response meets the criteria.\n\nRespond with a JSON object:\n{\n \"pass\": true/false,\n \"score\": 1-5,\n \"reason\": \"brief explanation\"\n}\n\nScoring guide:\n- 5: Fully meets criteria, excellent response\n- 4: Mostly meets criteria, minor issues\n- 3: Partially meets criteria, notable gaps\n- 2: Barely meets criteria, significant issues\n- 1: Does not meet criteria\n\nA score of ${passThreshold} or above is a pass.`\n}\n\nconst MODEL_ALIASES = ['fast', 'best']\n\nlet _cognitive: Cognitive | null = null\nlet _availableModels: string[] = []\nlet _judgeModel: string = 'fast'\nlet _log: EvalLogger = defaultLogger\n\n/** @internal Test-only: clears module judge state so tests stay hermetic in the shared bun test process. */\nexport function _resetLLMJudgeForTests(): void {\n _cognitive = null\n _availableModels = []\n _judgeModel = 'fast'\n _log = defaultLogger\n}\n\nfunction _isModelValid(model: string): boolean {\n if (MODEL_ALIASES.includes(model)) return true\n if (_availableModels.length === 0) return false\n\n return _availableModels.includes(model)\n}\n\n/**\n * Initialize the LLM judge with explicit credentials.\n * Call this before running evals so the judge doesn't need env vars.\n */\nexport async function initLLMJudge(\n credentials: { token: string; apiUrl: string; botId: string; workspaceId?: string },\n options?: { model?: string; logger?: EvalLogger }\n) {\n const log = options?.logger ?? defaultLogger\n _log = log\n\n const client = new Client({\n token: credentials.token,\n apiUrl: credentials.apiUrl,\n botId: credentials.botId,\n ...(credentials.workspaceId !== undefined ? { workspaceId: credentials.workspaceId } : {}),\n })\n _cognitive = new Cognitive({ client, __experimental_beta: true })\n\n try {\n _availableModels = Array.from((await _cognitive.fetchRemoteModels()).keys())\n } catch (err) {\n log.warn(`Failed to fetch available models: ${(err as Error).message}. LLM judge will be unavailable.`)\n _availableModels = []\n }\n\n _judgeModel = options?.model ?? 'fast'\n\n if (_availableModels.length === 0) {\n log.warn('No available Cognitive models: cannot validate judge model.')\n } else if (!_isModelValid(_judgeModel)) {\n log.warn(`Configured LLM judge model \"${_judgeModel}\" is invalid. Run \"adk models\" to list available models.`)\n }\n}\n\nexport async function gradeLLMJudge(\n botResponse: string,\n criteria: string,\n context: { userMessage: string; passThreshold?: number }\n): Promise<GraderResult> {\n const threshold = Math.max(1, Math.min(5, context.passThreshold ?? DEFAULT_PASS_THRESHOLD))\n\n try {\n // A judge that can't run must NOT silently pass the assertion \u2014 a flaky\n // LLM call or missing credentials would turn real assertions green.\n // Unavailability is a visible failure with a clear reason.\n if (!_cognitive) {\n _log.warn(`LLM judge unavailable for \"${criteria}\": no credentials configured (initLLMJudge not called)`)\n return {\n assertion: `llm_judge: \"${criteria}\"`,\n pass: false,\n expected: criteria,\n actual: 'FAILED \u2014 LLM judge unavailable: no credentials configured',\n }\n }\n\n if (!_isModelValid(_judgeModel)) {\n return {\n assertion: `llm_judge: \"${criteria}\"`,\n pass: false,\n expected: criteria,\n actual: 'FAILED \u2014 invalid LLM judge model',\n }\n }\n\n type CognitiveModel = Exclude<Parameters<Cognitive['generateContent']>[0]['model'], undefined>\n\n const { output } = await _cognitive.generateContent({\n model: _judgeModel as CognitiveModel,\n temperature: 0,\n responseFormat: 'json_object',\n systemPrompt: buildJudgeSystemPrompt(threshold),\n messages: [\n {\n role: 'user',\n content: `User message: ${context.userMessage}\\n\\nBot response: ${botResponse}\\n\\nCriteria: ${criteria}`,\n },\n ],\n })\n\n const rawContent = output?.choices?.[0]?.content\n const content = typeof rawContent === 'string' ? rawContent : null\n if (!content) {\n _log.warn(`LLM judge returned an empty response for \"${criteria}\"`)\n return {\n assertion: `llm_judge: \"${criteria}\"`,\n pass: false,\n expected: criteria,\n actual: 'FAILED \u2014 LLM judge returned empty response',\n }\n }\n\n const verdict = JSON.parse(content) as {\n pass: boolean\n score: number\n reason: string\n }\n\n return {\n assertion: `llm_judge: \"${criteria}\"`,\n pass: verdict.score >= threshold,\n expected: criteria,\n actual: `Score ${verdict.score}/5 (threshold: ${threshold}) \u2014 ${verdict.reason}`,\n }\n } catch (err) {\n _log.warn(`LLM judge failed for \"${criteria}\": ${(err as Error).message}`)\n return {\n assertion: `llm_judge: \"${criteria}\"`,\n pass: false,\n expected: criteria,\n actual: `FAILED \u2014 LLM judge unavailable: ${(err as Error).message}`,\n }\n }\n}\n", "/**\n * Eval type definitions.\n *\n * User-facing types live in @botpress/evals so eval authors can update eval\n * tooling without tying the authoring API to the agent runtime package.\n */\n\nexport {\n Eval,\n type EvalDefinition,\n type EvalSetup,\n type ConversationTurn,\n type TurnAssertions,\n type OutcomeAssertions,\n type ResponseAssertion,\n type ToolAssertion,\n type StateAssertion,\n type WorkflowAssertion,\n type TimingAssertion,\n type MatchOperator,\n type NumericOperator,\n} from './definition'\n\nexport type { Span, SpanStatus } from './trace'\n\nexport interface ChatClientConnection {\n user: { id: string }\n createConversation: (props: Record<string, unknown>) => Promise<{ conversation: { id: string } }>\n // Broad parameter types keep this compatible with @botpress/chat's narrower\n // generated payload unions while avoiding a dependency on those definitions.\n createMessage: (props: any) => Promise<unknown>\n createEvent: (props: any) => Promise<unknown>\n}\n\nexport interface ChatClient {\n connect: (props: { webhookId: string }) => Promise<ChatClientConnection>\n}\n\n// --- Grader result (universal currency for all graders) ---\n\nexport interface GraderResult {\n assertion: string\n pass: boolean\n expected: string\n actual: string\n}\n\n// --- Tool call extracted from traces ---\n\nexport interface ToolCall {\n name: string\n input: Record<string, unknown>\n output: string\n status: string\n}\n\n// --- Turn report ---\n\nexport interface TurnReport {\n turnNumber: number\n userMessage: string\n botResponse: string\n assertions: GraderResult[]\n pass: boolean\n /** Time spent waiting for the bot to respond (ms) */\n botDuration: number\n /** Time spent fetching traces + running graders (ms) */\n evalDuration: number\n}\n\n// --- Single eval report ---\n\nexport interface EvalReport {\n name: string\n description?: string\n type?: 'capability' | 'regression'\n tags?: string[]\n turns: TurnReport[]\n outcomeAssertions: GraderResult[]\n pass: boolean\n duration: number\n error?: string\n /** Stable EvalErrorCode when `error` came from a typed EvalRunnerError \u2014 lets consumers distinguish setup/config failures from bot failures. */\n errorCode?: string\n}\n\n// --- Progress event for real-time UI updates ---\n\nexport type EvalProgressEvent =\n | { type: 'suite_start'; totalEvals: number }\n | { type: 'eval_start'; evalName: string; index: number; totalTurns: number }\n | {\n type: 'turn_start'\n evalName: string\n evalIndex: number\n turnNumber: number\n totalTurns: number\n userMessage: string\n }\n | {\n type: 'turn_complete'\n evalName: string\n evalIndex: number\n turnNumber: number\n totalTurns: number\n turnReport: TurnReport\n }\n | { type: 'eval_complete'; evalName: string; index: number; report: EvalReport }\n | { type: 'suite_complete'; report: EvalRunReport; error?: string }\n\n// --- Eval run report (full suite) ---\n\nexport interface EvalRunReport {\n id: string\n timestamp: string\n evals: EvalReport[]\n passed: number\n failed: number\n total: number\n duration: number\n filter?: {\n names?: string[]\n tags?: string[]\n type?: 'capability' | 'regression'\n }\n /**\n * True when the suite was aborted mid-run (e.g. user clicked Stop). The\n * persisted report is partial \u2014 `evals` reflects only the completed evals,\n * and `total` matches that count, not the original suite size.\n */\n aborted?: boolean\n}\n\n// --- Bot connection info ---\n\nexport interface BotConnection {\n webhookId: string\n botId: string\n token: string\n apiUrl: string\n}\n\n// --- Logger interface ---\n\nexport interface EvalLogger {\n info: (message: string) => void\n warn: (message: string) => void\n error: (message: string) => void\n}\n\n/**\n * Fallback when no logger is injected (programmatic use outside the CLI).\n * console rather than a no-op so warnings stay visible \u2014 a silent default\n * would hide judge failures and skipped pre-flights, the exact swallow\n * anti-pattern docs/ERROR-HANDLING.md bans. The CLI always injects its own\n * structured logger via EvalRunnerConfig.logger.\n */\nexport const defaultLogger: EvalLogger = console\n\n// --- Eval runner configuration ---\n\nexport interface EvalRunnerConfig {\n credentials: {\n token: string\n apiUrl: string\n botId: string\n workspaceId?: string\n webhookId?: string\n }\n agentPath: string\n /** URL of the dev server providing traces and config. Defaults to the discovered DevConsole URL. */\n devServerUrl?: string\n /** Headers for dev-server requests, e.g. X-Agent-Path when routed through the singleton proxy. */\n devServerHeaders?: Record<string, string>\n /**\n * Optional host-provided chat client. The CLI passes its bundled chat client\n * here so the eval engine does not depend on @botpress/adk.\n */\n chatClient?: ChatClient\n onProgress?: (event: EvalProgressEvent) => void\n /** Logger for warnings and errors. Defaults to console. */\n logger?: EvalLogger\n /**\n * Called for unexpected (internal-bug) eval failures that runEval folds\n * into report.error \u2014 they never propagate to the CLI's command boundary,\n * so without this hook they'd be invisible to error tracking. The CLI binds\n * this to telemetry.captureException; evals itself stays telemetry-free.\n */\n onException?: (error: unknown, properties?: Record<string, unknown>) => void\n /**\n * Optional abort signal \u2014 when fired, the suite stops starting new evals.\n * The currently running eval continues to completion (LLM calls in flight\n * cannot always be cancelled), but no further evals are started.\n */\n signal?: AbortSignal\n /** Bot-level eval options from agent.config.ts. Cascades: eval > agent config > default. */\n evalOptions?: {\n idleTimeout?: number\n /** LLM judge pass threshold (integer, 1-5). Values outside this range are clamped. Cascades: eval > agent config > default (3). */\n judgePassThreshold?: number\n /** Model to use for llm_judge assertions (e.g. 'openai:gpt-4o'). Defaults to 'fast'. */\n judgeModel?: string\n }\n}\n\n// --- Eval suite filter ---\n\nexport interface EvalFilter {\n names?: string[]\n tags?: string[]\n type?: 'capability' | 'regression'\n}\n\n// --- Transformer types (trace-driven eval engine) ---\n\nexport interface StateMutation {\n type: string // 'bot', 'user', 'conversation'\n changedKeys: string[]\n previous: unknown\n current: unknown\n swappedToFile: boolean // data['swapped_to_file'] === true\n}\n\nexport interface WorkflowSpan {\n name: string\n status: 'running' | 'ok' | 'error'\n statusFinal?: string // 'completed', 'continue', 'failed'\n}\n\nexport interface TurnData {\n messages: string[]\n toolCalls: ToolCall[]\n stateMutations: StateMutation[]\n workflowSpans: WorkflowSpan[]\n handlerDuration: number\n handlerStatus: 'ok' | 'error'\n}\n", "/**\n * Response assertion graders.\n * Checks bot response text against expected assertions.\n */\n\nimport type { ResponseAssertion, GraderResult } from '../types'\nimport { gradeLLMJudge } from './llm'\n\nexport async function gradeResponse(\n botResponse: string,\n assertions: ResponseAssertion[],\n context: { userMessage: string; judgePassThreshold?: number }\n): Promise<GraderResult[]> {\n const results: GraderResult[] = []\n\n for (const assertion of assertions) {\n if ('contains' in assertion) {\n const pass = botResponse.toLowerCase().includes(assertion.contains.toLowerCase())\n results.push({\n assertion: `contains \"${assertion.contains}\"`,\n pass,\n expected: `Response contains \"${assertion.contains}\"`,\n actual: pass ? `Found in response` : `Not found in response`,\n })\n continue\n }\n\n if ('not_contains' in assertion) {\n const pass = !botResponse.toLowerCase().includes(assertion.not_contains.toLowerCase())\n results.push({\n assertion: `not_contains \"${assertion.not_contains}\"`,\n pass,\n expected: `Response does not contain \"${assertion.not_contains}\"`,\n actual: pass ? `Not found in response` : `Found in response`,\n })\n continue\n }\n\n if ('matches' in assertion) {\n const regex = new RegExp(assertion.matches, 'i')\n const pass = regex.test(botResponse)\n results.push({\n assertion: `matches ${assertion.matches}`,\n pass,\n expected: `Response matches /${assertion.matches}/`,\n actual: pass ? `Matched` : `No match`,\n })\n continue\n }\n\n if ('llm_judge' in assertion) {\n const result = await gradeLLMJudge(botResponse, assertion.llm_judge, {\n userMessage: context.userMessage,\n ...(context.judgePassThreshold !== undefined ? { passThreshold: context.judgePassThreshold } : {}),\n })\n results.push(result)\n continue\n }\n\n // TODO: uncomment this once we support it\n // if ('similar_to' in assertion) {\n // results.push({\n // assertion: `similar_to: \"${assertion.similar_to}\"`,\n // pass: true,\n // expected: assertion.similar_to,\n // actual: 'SKIPPED \u2014 similar_to not yet implemented',\n // })\n // continue\n // }\n\n results.push({\n assertion: 'unknown',\n pass: false,\n expected: 'known assertion type',\n actual: `Unknown assertion: ${JSON.stringify(assertion)}`,\n })\n }\n\n return results\n}\n", "/**\n * Tool assertion graders.\n * Checks tool calls from traces against expected assertions.\n */\n\nimport type { ToolAssertion, ToolCall, GraderResult } from '../types'\nimport { matchValue, operatorToString } from './match'\n\nexport function gradeTools(toolCalls: ToolCall[], assertions: ToolAssertion[]): GraderResult[] {\n return assertions.map((assertion) => {\n // --- called ---\n if ('called' in assertion && !('not_called' in assertion) && !('call_order' in assertion)) {\n const matches = toolCalls.filter((tc) => tc.name === assertion.called)\n const wasCalled = matches.length > 0\n\n if (!wasCalled) {\n return {\n assertion: `tool called: ${assertion.called}`,\n pass: false,\n expected: `${assertion.called} was called`,\n actual: `Not called. Tools called: [${toolCalls.map((tc) => tc.name).join(', ') || 'none'}]`,\n }\n }\n\n // Check params if specified\n if (assertion.params) {\n const paramResults: { key: string; pass: boolean; detail: string }[] = []\n\n for (const [key, operator] of Object.entries(assertion.params)) {\n // Check across all matching calls \u2014 pass if any call matches\n const anyMatch = matches.some((tc) => matchValue(operator, tc.input[key]))\n paramResults.push({\n key,\n pass: anyMatch,\n detail: anyMatch\n ? `matched`\n : `expected ${key} ${operatorToString(operator)}, got ${JSON.stringify(matches.map((tc) => tc.input[key]))}`,\n })\n }\n\n const allParamsPass = paramResults.every((p) => p.pass)\n const failedParams = paramResults.filter((p) => !p.pass)\n\n return {\n assertion: `tool called: ${assertion.called} with params`,\n pass: allParamsPass,\n expected: `${assertion.called} called with ${Object.entries(assertion.params)\n .map(([k, v]) => `${k} ${operatorToString(v)}`)\n .join(', ')}`,\n actual: allParamsPass ? `Matched` : failedParams.map((p) => p.detail).join('; '),\n }\n }\n\n return {\n assertion: `tool called: ${assertion.called}`,\n pass: true,\n expected: `${assertion.called} was called`,\n actual: `Called ${matches.length} time(s)`,\n }\n }\n\n // --- not_called ---\n if ('not_called' in assertion) {\n const wasCalled = toolCalls.some((tc) => tc.name === assertion.not_called)\n return {\n assertion: `tool not_called: ${assertion.not_called}`,\n pass: !wasCalled,\n expected: `${assertion.not_called} was NOT called`,\n actual: wasCalled ? `Was called` : `Not called`,\n }\n }\n\n // --- call_order ---\n if ('call_order' in assertion) {\n const calledNames = toolCalls.map((tc) => tc.name)\n const expectedOrder = assertion.call_order as string[]\n\n // Check that the expected sequence appears in order (not necessarily contiguous)\n let cursor = 0\n for (const name of calledNames) {\n if (cursor < expectedOrder.length && name === expectedOrder[cursor]) {\n cursor++\n }\n }\n const inOrder = cursor === expectedOrder.length\n\n return {\n assertion: `call_order: [${expectedOrder.join(' \u2192 ')}]`,\n pass: inOrder,\n expected: `Tools called in order: [${expectedOrder.join(' \u2192 ')}]`,\n actual: `Actual order: [${calledNames.join(' \u2192 ') || 'none'}]`,\n }\n }\n\n return {\n assertion: 'unknown tool assertion',\n pass: false,\n expected: 'known assertion type',\n actual: `Unknown: ${JSON.stringify(assertion)}`,\n }\n })\n}\n", "/**\n * State assertion graders.\n * Pure functions that grade state assertions against StateMutation[] from the transformer.\n * No API calls, no retries, no BpClient.\n */\n\nimport type { StateMutation, StateAssertion, GraderResult } from '../types'\n\n/**\n * Parse a state path like \"conversation.lastCity\" into its components.\n * bot.* -> type: \"bot\", field: \"*\"\n * user.* -> type: \"user\", field: \"*\"\n * conversation.* -> type: \"conversation\", field: \"*\"\n */\nfunction parseStatePath(path: string): { type: string; field: string } {\n const dot = path.indexOf('.')\n if (dot === -1) {\n throw new Error(`Invalid state path \"${path}\" \u2014 expected \"type.field\" format`)\n }\n\n const type = path.slice(0, dot)\n const field = path.slice(dot + 1)\n\n if (type !== 'bot' && type !== 'user' && type !== 'conversation') {\n throw new Error(`Unknown state type \"${type}\" in path \"${path}\" \u2014 expected bot, user, or conversation`)\n }\n\n return { type, field }\n}\n\n/**\n * Grade state assertions using StateMutation[] from the transformer.\n *\n * - `equals`: find the LAST mutation matching the state type, extract field from `current`, deep-compare\n * - `changed: true`: check if the field appears in ANY mutation's `changedKeys` for that state type\n * - `changed: false`: check that the field appears in NO mutation's `changedKeys`\n * - Swapped state: when `swappedToFile` is true, current/previous are undefined \u2014 report a clear message\n */\nexport function gradeState(mutations: StateMutation[], assertions: StateAssertion[]): GraderResult[] {\n const results: GraderResult[] = []\n\n for (const assertion of assertions) {\n const parsed = parseStatePath(assertion.path)\n const matchingMutations = mutations.filter((m) => m.type === parsed.type)\n\n if (assertion.equals !== undefined) {\n if (matchingMutations.length === 0) {\n results.push({\n assertion: `state: ${assertion.path} equals`,\n pass: false,\n expected: JSON.stringify(assertion.equals),\n actual:\n `No state.save span found for \"${parsed.type}\" \u2014 the bot did not mutate this state during the turn. ` +\n 'If this state was seeded via setup.state, assert on the tool/action that reads it, or use a conversation turn that triggers a state write.',\n })\n continue\n }\n\n const lastMutation = matchingMutations[matchingMutations.length - 1]!\n\n if (lastMutation.swappedToFile) {\n results.push({\n assertion: `state: ${assertion.path} equals`,\n pass: false,\n expected: JSON.stringify(assertion.equals),\n actual: 'State was too large for trace-based assertion (swapped to file)',\n })\n continue\n }\n\n const currentState = lastMutation.current as Record<string, unknown> | undefined\n const actualValue = currentState ? currentState[parsed.field] : undefined\n const pass = deepEqual(actualValue, assertion.equals)\n\n results.push({\n assertion: `state: ${assertion.path} equals`,\n pass,\n expected: JSON.stringify(assertion.equals),\n actual: JSON.stringify(actualValue),\n })\n }\n\n if (assertion.changed !== undefined) {\n if (matchingMutations.length === 0) {\n results.push({\n assertion: `state: ${assertion.path} ${assertion.changed ? 'changed' : 'unchanged'}`,\n pass: !assertion.changed,\n expected: assertion.changed\n ? `Field \"${parsed.field}\" changed in a \"${parsed.type}\" state mutation`\n : `Field \"${parsed.field}\" unchanged`,\n actual: 'No state mutation found for type \"' + parsed.type + '\"',\n })\n continue\n }\n\n // Check for swapped state in any matching mutation\n const hasSwapped = matchingMutations.some((m) => m.swappedToFile)\n if (hasSwapped) {\n results.push({\n assertion: `state: ${assertion.path} ${assertion.changed ? 'changed' : 'unchanged'}`,\n pass: false,\n expected: assertion.changed\n ? `Field \"${parsed.field}\" changed in a \"${parsed.type}\" state mutation`\n : `Field \"${parsed.field}\" unchanged`,\n actual: 'State was too large for trace-based assertion (swapped to file)',\n })\n continue\n }\n\n const fieldChanged = matchingMutations.some((m) => m.changedKeys.includes(parsed.field))\n const pass = assertion.changed ? fieldChanged : !fieldChanged\n\n results.push({\n assertion: `state: ${assertion.path} ${assertion.changed ? 'changed' : 'unchanged'}`,\n pass,\n expected: assertion.changed\n ? `Field \"${parsed.field}\" changed in a \"${parsed.type}\" state mutation`\n : `Field \"${parsed.field}\" unchanged`,\n actual: fieldChanged ? `Field \"${parsed.field}\" was changed` : `Field \"${parsed.field}\" was not changed`,\n })\n }\n }\n\n return results\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true\n if (a === null || b === null) return false\n if (typeof a !== typeof b) return false\n\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false\n return a.every((v, i) => deepEqual(v, b[i]))\n }\n\n if (Array.isArray(a) !== Array.isArray(b)) return false\n\n if (typeof a === 'object' && typeof b === 'object') {\n const keysA = Object.keys(a as object)\n const keysB = Object.keys(b as object)\n if (keysA.length !== keysB.length) return false\n return keysA.every((k) => deepEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]))\n }\n\n return false\n}\n", "/**\n * Workflow assertion graders.\n * Checks workflow execution via transformer-produced WorkflowSpan data.\n */\n\nimport type { WorkflowAssertion, WorkflowSpan, GraderResult } from '../types'\n\nexport function gradeWorkflows(workflows: WorkflowSpan[], assertions: WorkflowAssertion[]): GraderResult[] {\n const results: GraderResult[] = []\n\n for (const assertion of assertions) {\n const matching = workflows.filter((wf) => wf.name === assertion.name)\n\n // entered \u2014 was the workflow triggered at all?\n if (assertion.entered !== undefined) {\n const wasEntered = matching.length > 0\n const pass = assertion.entered ? wasEntered : !wasEntered\n\n results.push({\n assertion: `workflow: ${assertion.name} ${assertion.entered ? 'entered' : 'not entered'}`,\n pass,\n expected: assertion.entered\n ? `Workflow \"${assertion.name}\" was entered`\n : `Workflow \"${assertion.name}\" was not entered`,\n actual: wasEntered ? `Found ${matching.length} workflow span(s)` : `No workflow spans found`,\n })\n }\n\n // completed \u2014 did the workflow complete?\n if (assertion.completed !== undefined) {\n const didComplete = matching.some(\n (wf) => wf.statusFinal === 'completed' || wf.status === 'ok' || wf.status === 'error'\n )\n const pass = assertion.completed ? didComplete : !didComplete\n\n results.push({\n assertion: `workflow: ${assertion.name} ${assertion.completed ? 'completed' : 'not completed'}`,\n pass,\n expected: assertion.completed\n ? `Workflow \"${assertion.name}\" completed`\n : `Workflow \"${assertion.name}\" did not complete`,\n actual: didComplete ? `Completed` : `Not completed`,\n })\n }\n }\n\n return results\n}\n", "/**\n * Timing assertion graders.\n * Checks bot response duration against expected thresholds.\n */\n\nimport type { TimingAssertion, GraderResult } from '../types'\nimport { matchValue, operatorToString } from './match'\n\nexport function gradeTiming(botDuration: number, assertions: TimingAssertion[]): GraderResult[] {\n const results: GraderResult[] = []\n\n for (const assertion of assertions) {\n const pass = matchValue(assertion.response_time, botDuration)\n const expected = operatorToString(assertion.response_time)\n\n results.push({\n assertion: `response_time ${expected}`,\n pass,\n expected: `Response time ${expected}`,\n actual: `${botDuration}ms`,\n })\n }\n\n return results\n}\n", "/**\n * Outcome assertion orchestrator.\n * Runs state and workflow graders after all conversation turns complete.\n */\n\nimport type { EvalDefinition, GraderResult, StateMutation, WorkflowSpan } from '../types'\nimport { gradeState } from './state'\nimport { gradeWorkflows } from './workflow'\n\n/**\n * Grade all outcome assertions after the conversation completes.\n * Takes transformer output (StateMutation[], WorkflowSpan[]) \u2014 no raw spans, no API calls.\n */\nexport function gradeOutcome(\n mutations: StateMutation[],\n evalDef: EvalDefinition,\n workflowSpans: WorkflowSpan[]\n): GraderResult[] {\n const outcome = evalDef.outcome\n if (!outcome) return []\n\n const results: GraderResult[] = []\n\n if (outcome.state && outcome.state.length > 0) {\n const stateResults = gradeState(mutations, outcome.state)\n results.push(...stateResults)\n }\n\n if (outcome.workflow && outcome.workflow.length > 0) {\n const workflowResults = gradeWorkflows(workflowSpans, outcome.workflow)\n results.push(...workflowResults)\n }\n\n return results\n}\n"],
|
|
5
|
+
"mappings": ";AAUO,SAAS,WAAW,UAAyB,QAA0B;AAE5E,MAAI,OAAO,aAAa,UAAU;AAChC,WAAO,OAAO,MAAM,MAAM;AAAA,EAC5B;AAEA,MAAI,YAAY,UAAU;AACxB,WAAO,WAAW,SAAS;AAAA,EAC7B;AAEA,MAAI,cAAc,UAAU;AAC1B,WAAO,OAAO,MAAM,EAAE,YAAY,EAAE,SAAS,SAAS,SAAS,YAAY,CAAC;AAAA,EAC9E;AAEA,MAAI,kBAAkB,UAAU;AAC9B,WAAO,CAAC,OAAO,MAAM,EAAE,YAAY,EAAE,SAAS,SAAS,aAAa,YAAY,CAAC;AAAA,EACnF;AAEA,MAAI,aAAa,UAAU;AACzB,WAAO,IAAI,OAAO,SAAS,SAAS,GAAG,EAAE,KAAK,OAAO,MAAM,CAAC;AAAA,EAC9D;AAEA,MAAI,QAAQ,UAAU;AACpB,WAAO,SAAS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.ts
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* LLM judge grader using @botpress/
|
|
3
|
-
*
|
|
2
|
+
* LLM judge grader using @botpress/cognitive.
|
|
3
|
+
* Replaces the OpenAI-based implementation from the standalone project.
|
|
4
4
|
*/
|
|
5
|
-
import type { Client } from '@botpress/client';
|
|
6
5
|
import type { EvalLogger, GraderResult } from '../types';
|
|
7
6
|
/** @internal Test-only: clears module judge state so tests stay hermetic in the shared bun test process. */
|
|
8
7
|
export declare function _resetLLMJudgeForTests(): void;
|
|
9
|
-
/**
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
8
|
+
/**
|
|
9
|
+
* Initialize the LLM judge with explicit credentials.
|
|
10
|
+
* Call this before running evals so the judge doesn't need env vars.
|
|
11
|
+
*/
|
|
12
|
+
export declare function initLLMJudge(credentials: {
|
|
13
|
+
token: string;
|
|
14
|
+
apiUrl: string;
|
|
15
|
+
botId: string;
|
|
16
|
+
workspaceId?: string;
|
|
17
|
+
}, options?: {
|
|
16
18
|
model?: string;
|
|
17
19
|
logger?: EvalLogger;
|
|
18
|
-
failClosed?: boolean;
|
|
19
20
|
}): Promise<void>;
|
|
20
21
|
export declare function gradeLLMJudge(botResponse: string, criteria: string, context: {
|
|
21
22
|
userMessage: string;
|
|
22
|
-
/** @deprecated No-op: the judge is boolean (zai.check); there is no score threshold. */
|
|
23
23
|
passThreshold?: number;
|
|
24
24
|
}): Promise<GraderResult>;
|
|
25
25
|
//# sourceMappingURL=llm.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"llm.d.ts","sourceRoot":"","sources":["../../src/graders/llm.ts"],"names":[],"mappings":"AAAA;;;GAGG;
|
|
1
|
+
{"version":3,"file":"llm.d.ts","sourceRoot":"","sources":["../../src/graders/llm.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,UAAU,CAAA;AAqCxD,4GAA4G;AAC5G,wBAAgB,sBAAsB,IAAI,IAAI,CAK7C;AASD;;;GAGG;AACH,wBAAsB,YAAY,CAChC,WAAW,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAE,EACnF,OAAO,CAAC,EAAE;IAAE,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,UAAU,CAAA;CAAE,iBA2BlD;AAED,wBAAsB,aAAa,CACjC,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,aAAa,CAAC,EAAE,MAAM,CAAA;CAAE,GACvD,OAAO,CAAC,YAAY,CAAC,CA0EvB"}
|
package/dist/graders/llm.js
CHANGED
|
@@ -1,42 +1,64 @@
|
|
|
1
1
|
// src/graders/llm.ts
|
|
2
|
+
import { Client } from "@botpress/client";
|
|
2
3
|
import { Cognitive } from "@botpress/cognitive";
|
|
3
|
-
import { Zai } from "@botpress/zai";
|
|
4
4
|
|
|
5
5
|
// src/types.ts
|
|
6
6
|
var defaultLogger = console;
|
|
7
7
|
|
|
8
8
|
// src/graders/llm.ts
|
|
9
|
+
var DEFAULT_PASS_THRESHOLD = 3;
|
|
10
|
+
function buildJudgeSystemPrompt(passThreshold) {
|
|
11
|
+
return `You are an evaluation judge for a chatbot. You will be given:
|
|
12
|
+
- The user's message
|
|
13
|
+
- The bot's response
|
|
14
|
+
- Grading criteria
|
|
15
|
+
|
|
16
|
+
Your job is to determine if the bot's response meets the criteria.
|
|
17
|
+
|
|
18
|
+
Respond with a JSON object:
|
|
19
|
+
{
|
|
20
|
+
"pass": true/false,
|
|
21
|
+
"score": 1-5,
|
|
22
|
+
"reason": "brief explanation"
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
Scoring guide:
|
|
26
|
+
- 5: Fully meets criteria, excellent response
|
|
27
|
+
- 4: Mostly meets criteria, minor issues
|
|
28
|
+
- 3: Partially meets criteria, notable gaps
|
|
29
|
+
- 2: Barely meets criteria, significant issues
|
|
30
|
+
- 1: Does not meet criteria
|
|
31
|
+
|
|
32
|
+
A score of ${passThreshold} or above is a pass.`;
|
|
33
|
+
}
|
|
9
34
|
var MODEL_ALIASES = ["fast", "best"];
|
|
10
|
-
var
|
|
35
|
+
var _cognitive = null;
|
|
11
36
|
var _availableModels = [];
|
|
12
37
|
var _judgeModel = "fast";
|
|
13
|
-
var _failClosed = true;
|
|
14
38
|
var _log = defaultLogger;
|
|
15
39
|
function _resetLLMJudgeForTests() {
|
|
16
|
-
|
|
40
|
+
_cognitive = null;
|
|
17
41
|
_availableModels = [];
|
|
18
42
|
_judgeModel = "fast";
|
|
19
43
|
_log = defaultLogger;
|
|
20
|
-
_failClosed = true;
|
|
21
|
-
}
|
|
22
|
-
function _setLLMJudgeForTests(zai, options) {
|
|
23
|
-
_zai = zai;
|
|
24
|
-
_availableModels = ["fast"];
|
|
25
|
-
_judgeModel = options?.model ?? "fast";
|
|
26
|
-
_failClosed = options?.failClosed ?? true;
|
|
27
44
|
}
|
|
28
45
|
function _isModelValid(model) {
|
|
29
46
|
if (MODEL_ALIASES.includes(model)) return true;
|
|
30
47
|
if (_availableModels.length === 0) return false;
|
|
31
48
|
return _availableModels.includes(model);
|
|
32
49
|
}
|
|
33
|
-
async function initLLMJudge(
|
|
50
|
+
async function initLLMJudge(credentials, options) {
|
|
34
51
|
const log = options?.logger ?? defaultLogger;
|
|
35
52
|
_log = log;
|
|
36
|
-
|
|
37
|
-
|
|
53
|
+
const client = new Client({
|
|
54
|
+
token: credentials.token,
|
|
55
|
+
apiUrl: credentials.apiUrl,
|
|
56
|
+
botId: credentials.botId,
|
|
57
|
+
...credentials.workspaceId !== void 0 ? { workspaceId: credentials.workspaceId } : {}
|
|
58
|
+
});
|
|
59
|
+
_cognitive = new Cognitive({ client, __experimental_beta: true });
|
|
38
60
|
try {
|
|
39
|
-
_availableModels = Array.from((await
|
|
61
|
+
_availableModels = Array.from((await _cognitive.fetchRemoteModels()).keys());
|
|
40
62
|
} catch (err) {
|
|
41
63
|
log.warn(`Failed to fetch available models: ${err.message}. LLM judge will be unavailable.`);
|
|
42
64
|
_availableModels = [];
|
|
@@ -47,42 +69,66 @@ async function initLLMJudge(client, options) {
|
|
|
47
69
|
} else if (!_isModelValid(_judgeModel)) {
|
|
48
70
|
log.warn(`Configured LLM judge model "${_judgeModel}" is invalid. Run "adk models" to list available models.`);
|
|
49
71
|
}
|
|
50
|
-
_zai = new Zai({ client: cognitive, modelId: _judgeModel });
|
|
51
72
|
}
|
|
52
73
|
async function gradeLLMJudge(botResponse, criteria, context) {
|
|
53
|
-
const
|
|
74
|
+
const threshold = Math.max(1, Math.min(5, context.passThreshold ?? DEFAULT_PASS_THRESHOLD));
|
|
54
75
|
try {
|
|
55
|
-
if (!
|
|
76
|
+
if (!_cognitive) {
|
|
56
77
|
_log.warn(`LLM judge unavailable for "${criteria}": no credentials configured (initLLMJudge not called)`);
|
|
57
78
|
return {
|
|
58
|
-
assertion
|
|
59
|
-
pass:
|
|
60
|
-
skipped: true,
|
|
79
|
+
assertion: `llm_judge: "${criteria}"`,
|
|
80
|
+
pass: false,
|
|
61
81
|
expected: criteria,
|
|
62
82
|
actual: "FAILED \u2014 LLM judge unavailable: no credentials configured"
|
|
63
83
|
};
|
|
64
84
|
}
|
|
65
85
|
if (!_isModelValid(_judgeModel)) {
|
|
66
86
|
return {
|
|
67
|
-
assertion
|
|
87
|
+
assertion: `llm_judge: "${criteria}"`,
|
|
68
88
|
pass: false,
|
|
69
89
|
expected: criteria,
|
|
70
90
|
actual: "FAILED \u2014 invalid LLM judge model"
|
|
71
91
|
};
|
|
72
92
|
}
|
|
73
|
-
const { output } = await
|
|
93
|
+
const { output } = await _cognitive.generateContent({
|
|
94
|
+
model: _judgeModel,
|
|
95
|
+
temperature: 0,
|
|
96
|
+
responseFormat: "json_object",
|
|
97
|
+
systemPrompt: buildJudgeSystemPrompt(threshold),
|
|
98
|
+
messages: [
|
|
99
|
+
{
|
|
100
|
+
role: "user",
|
|
101
|
+
content: `User message: ${context.userMessage}
|
|
102
|
+
|
|
103
|
+
Bot response: ${botResponse}
|
|
104
|
+
|
|
105
|
+
Criteria: ${criteria}`
|
|
106
|
+
}
|
|
107
|
+
]
|
|
108
|
+
});
|
|
109
|
+
const rawContent = output?.choices?.[0]?.content;
|
|
110
|
+
const content = typeof rawContent === "string" ? rawContent : null;
|
|
111
|
+
if (!content) {
|
|
112
|
+
_log.warn(`LLM judge returned an empty response for "${criteria}"`);
|
|
113
|
+
return {
|
|
114
|
+
assertion: `llm_judge: "${criteria}"`,
|
|
115
|
+
pass: false,
|
|
116
|
+
expected: criteria,
|
|
117
|
+
actual: "FAILED \u2014 LLM judge returned empty response"
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
const verdict = JSON.parse(content);
|
|
74
121
|
return {
|
|
75
|
-
assertion
|
|
76
|
-
pass:
|
|
122
|
+
assertion: `llm_judge: "${criteria}"`,
|
|
123
|
+
pass: verdict.score >= threshold,
|
|
77
124
|
expected: criteria,
|
|
78
|
-
actual:
|
|
125
|
+
actual: `Score ${verdict.score}/5 (threshold: ${threshold}) \u2014 ${verdict.reason}`
|
|
79
126
|
};
|
|
80
127
|
} catch (err) {
|
|
81
128
|
_log.warn(`LLM judge failed for "${criteria}": ${err.message}`);
|
|
82
129
|
return {
|
|
83
|
-
assertion
|
|
84
|
-
pass:
|
|
85
|
-
skipped: true,
|
|
130
|
+
assertion: `llm_judge: "${criteria}"`,
|
|
131
|
+
pass: false,
|
|
86
132
|
expected: criteria,
|
|
87
133
|
actual: `FAILED \u2014 LLM judge unavailable: ${err.message}`
|
|
88
134
|
};
|
|
@@ -90,7 +136,6 @@ async function gradeLLMJudge(botResponse, criteria, context) {
|
|
|
90
136
|
}
|
|
91
137
|
export {
|
|
92
138
|
_resetLLMJudgeForTests,
|
|
93
|
-
_setLLMJudgeForTests,
|
|
94
139
|
gradeLLMJudge,
|
|
95
140
|
initLLMJudge
|
|
96
141
|
};
|
package/dist/graders/llm.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/graders/llm.ts", "../../src/types.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * LLM judge grader using @botpress/zai.\n * `zai.check` owns the judge prompt, output parsing, and retries on invalid model output.\n */\n\nimport type { Client } from '@botpress/client'\nimport { Cognitive } from '@botpress/cognitive'\nimport { Zai } from '@botpress/zai'\nimport type { EvalLogger, GraderResult } from '../types'\nimport { defaultLogger } from '../types'\n\nconst MODEL_ALIASES = ['fast', 'best']\n\nlet _zai: Zai | null = null\nlet _availableModels: string[] = []\nlet _judgeModel: string = 'fast'\n// When true (default), a judge that can't run is a hard FAIL, so an unavailable judge can't be\n// mistaken for success. Callers may opt into fail-open (a skipped pass) via `failClosed: false`,\n// e.g. local runs without judge credentials. Either way the result is marked `skipped: true`.\nlet _failClosed: boolean = true\nlet _log: EvalLogger = defaultLogger\n\n/** @internal Test-only: clears module judge state so tests stay hermetic in the shared bun test process. */\nexport function _resetLLMJudgeForTests(): void {\n _zai = null\n _availableModels = []\n _judgeModel = 'fast'\n _log = defaultLogger\n _failClosed = true\n}\n\n/** @internal Test-only: injects a fake Zai client so judge behavior is testable offline. */\nexport function _setLLMJudgeForTests(zai: unknown, options?: { failClosed?: boolean; model?: string }): void {\n _zai = zai as Zai\n _availableModels = ['fast']\n _judgeModel = options?.model ?? 'fast'\n _failClosed = options?.failClosed ?? true\n}\n\nfunction _isModelValid(model: string): boolean {\n if (MODEL_ALIASES.includes(model)) return true\n if (_availableModels.length === 0) return false\n\n return _availableModels.includes(model)\n}\n\n/** Initialize the LLM judge with an authenticated Botpress client. */\nexport async function initLLMJudge(\n client: Client,\n options?: { model?: string; logger?: EvalLogger; failClosed?: boolean }\n) {\n const log = options?.logger ?? defaultLogger\n _log = log\n _failClosed = options?.failClosed ?? true\n\n const cognitive = new Cognitive({ client, __experimental_beta: true })\n\n try {\n _availableModels = Array.from((await cognitive.fetchRemoteModels()).keys())\n } catch (err) {\n log.warn(`Failed to fetch available models: ${(err as Error).message}. LLM judge will be unavailable.`)\n _availableModels = []\n }\n\n _judgeModel = options?.model ?? 'fast'\n\n if (_availableModels.length === 0) {\n log.warn('No available Cognitive models: cannot validate judge model.')\n } else if (!_isModelValid(_judgeModel)) {\n log.warn(`Configured LLM judge model \"${_judgeModel}\" is invalid. Run \"adk models\" to list available models.`)\n }\n\n _zai = new Zai({ client: cognitive, modelId: _judgeModel as ConstructorParameters<typeof Zai>[0]['modelId'] })\n}\n\nexport async function gradeLLMJudge(\n botResponse: string,\n criteria: string,\n context: {\n userMessage: string\n /** @deprecated No-op: the judge is boolean (zai.check); there is no score threshold. */\n passThreshold?: number\n }\n): Promise<GraderResult> {\n const assertion = `llm_judge: \"${criteria}\"`\n\n try {\n if (!_zai) {\n _log.warn(`LLM judge unavailable for \"${criteria}\": no credentials configured (initLLMJudge not called)`)\n return {\n assertion,\n pass: !_failClosed,\n skipped: true,\n expected: criteria,\n actual: 'FAILED \u2014 LLM judge unavailable: no credentials configured',\n }\n }\n\n if (!_isModelValid(_judgeModel)) {\n return {\n assertion,\n pass: false,\n expected: criteria,\n actual: 'FAILED \u2014 invalid LLM judge model',\n }\n }\n\n const { output } = await _zai.check({ userMessage: context.userMessage, botResponse }, criteria).result()\n\n return {\n assertion,\n pass: output.value,\n expected: criteria,\n actual: `${output.value ? 'Pass' : 'Fail'} \u2014 ${output.explanation}`,\n }\n } catch (err) {\n _log.warn(`LLM judge failed for \"${criteria}\": ${(err as Error).message}`)\n return {\n assertion,\n pass: !_failClosed,\n skipped: true,\n expected: criteria,\n actual: `FAILED \u2014 LLM judge unavailable: ${(err as Error).message}`,\n }\n }\n}\n", "/**\n * Eval type definitions.\n *\n * User-facing types live in @botpress/evals so eval authors can update eval\n * tooling without tying the authoring API to the agent runtime package.\n */\n\nimport type { EvalDefinition as _EvalDefinition } from './definition'\n\nexport {\n Eval,\n type EvalDefinition,\n type EvalSetup,\n type ConversationTurn,\n type TurnAssertions,\n type OutcomeAssertions,\n type ResponseAssertion,\n type ToolAssertion,\n type StateAssertion,\n type WorkflowAssertion,\n type TimingAssertion,\n type MatchOperator,\n type NumericOperator,\n} from './definition'\n\nexport type { Span, SpanStatus } from './spans/trace'\nexport type { WaitOptions, WorkflowWaitOptions } from './spans/span-source'\nimport type { SpanSource } from './spans/span-source'\nexport type { SpanSource }\n\n/**\n * The @botpress/chat Client *class* (constructor) \u2014 not an instance. Callers\n * inject it (the CLI passes its bundled chat client) and the runner calls the\n * static `.connect()`. Typed via `typeof import(...)` so this types-only module\n * doesn't pull in a value import.\n */\nexport type ChatClient = typeof import('@botpress/chat').Client\n\n// --- Grader result (universal currency for all graders) ---\n\nexport interface GraderResult {\n assertion: string\n pass: boolean\n expected: string\n actual: string\n /**\n * True when the assertion could not actually be evaluated (e.g. the llm_judge had no credentials,\n * returned an empty response, or errored). Distinguishes a genuine pass from a \"didn't run\" pass.\n * Callers that demand a trustworthy verdict (e.g. the benchmark) should treat `skipped` as a failure.\n */\n skipped?: boolean\n}\n\n// --- Tool call extracted from traces ---\n\nexport interface ToolCall {\n name: string\n input: Record<string, unknown>\n output: string\n status: string\n}\n\n// --- Turn report ---\n\nexport interface TurnReport {\n turnIndex: number\n userMessage: string\n botResponse: string\n assertions: GraderResult[]\n pass: boolean\n /** Time spent waiting for the bot to respond (ms) */\n botDuration: number\n /** Time spent fetching traces + running graders (ms) */\n evalDuration: number\n}\n\n// --- Single eval report ---\n\nexport interface EvalReport {\n name: string\n description?: string\n type?: 'capability' | 'regression'\n tags?: string[]\n turns: TurnReport[]\n outcomeAssertions: GraderResult[]\n pass: boolean\n duration: number\n error?: string\n /** Stable EvalErrorCode when `error` came from a typed EvalRunnerError \u2014 lets consumers distinguish setup/config failures from bot failures. */\n errorCode?: string\n}\n\n// --- Progress event for real-time UI updates ---\n\nexport type EvalProgressEvent =\n | { type: 'suite_start'; totalEvals: number }\n | { type: 'eval_start'; evalName: string; index: number; totalTurns: number }\n | {\n type: 'turn_start'\n evalName: string\n evalIndex: number\n turnIndex: number\n totalTurns: number\n userMessage: string\n }\n | {\n type: 'turn_complete'\n evalName: string\n evalIndex: number\n turnIndex: number\n totalTurns: number\n turnReport: TurnReport\n }\n | { type: 'eval_complete'; evalName: string; index: number; report: EvalReport }\n | { type: 'suite_complete'; report: EvalRunReport; error?: string }\n\n// --- Eval run report (full suite) ---\n\nexport interface EvalRunReport {\n id: string\n timestamp: string\n evals: EvalReport[]\n passed: number\n failed: number\n total: number\n duration: number\n filter?: {\n names?: string[]\n tags?: string[]\n type?: 'capability' | 'regression'\n }\n /**\n * True when the suite was aborted mid-run (e.g. user clicked Stop). The\n * persisted report is partial \u2014 `evals` reflects only the completed evals,\n * and `total` matches that count, not the original suite size.\n */\n aborted?: boolean\n}\n\n// --- Bot connection info ---\n\nexport interface BotConnection {\n client: import('@botpress/client').Client\n botId: string\n}\n\n// --- Logger interface ---\n\nexport interface EvalLogger {\n info: (message: string) => void\n warn: (message: string) => void\n error: (message: string) => void\n}\n\n/**\n * Fallback when no logger is injected (programmatic use outside the CLI).\n * console rather than a no-op so warnings stay visible \u2014 a silent default\n * would hide judge failures and skipped pre-flights, the exact swallow\n * anti-pattern docs/ERROR-HANDLING.md bans. The CLI always injects its own\n * structured logger via EvalRunnerConfig.logger.\n */\nexport const defaultLogger: EvalLogger = console\n\n// --- Eval runner configuration ---\n\nexport interface EvalRunnerConfig {\n /** Authenticated Botpress client. Used for state seeding, workflow triggers, webhook discovery, and LLM judge. */\n client: import('@botpress/client').Client\n botId: string\n /** Path to the agent directory. Used to discover eval files from `<agentPath>/evals/`. Not needed when `definitions` is provided. */\n agentPath?: string\n /** Pre-loaded eval definitions. When provided, `agentPath` is not used for eval discovery. */\n definitions?: _EvalDefinition[]\n /** URL of the dev server providing traces and config. Defaults to the discovered DevConsole URL. */\n devServerUrl?: string\n /** Headers for dev-server requests, e.g. X-Agent-Path when routed through the singleton proxy. */\n devServerHeaders?: Record<string, string>\n /**\n * Optional host-provided chat client. The CLI passes its bundled chat client\n * here so the eval engine does not depend on @botpress/adk.\n */\n chatClient?: ChatClient\n onProgress?: (event: EvalProgressEvent) => void | Promise<void>\n /** Logger for warnings and errors. Defaults to console. */\n logger?: EvalLogger\n /**\n * Called for unexpected (internal-bug) eval failures that runEval folds\n * into report.error \u2014 they never propagate to the CLI's command boundary,\n * so without this hook they'd be invisible to error tracking. The CLI binds\n * this to telemetry.captureException; evals itself stays telemetry-free.\n */\n onException?: (error: unknown, properties?: Record<string, unknown>) => void\n /**\n * Optional abort signal \u2014 when fired, the suite stops starting new evals.\n * The currently running eval continues to completion (LLM calls in flight\n * cannot always be cancelled), but no further evals are started.\n */\n signal?: AbortSignal\n /** Bot-level eval options from agent.config.ts. Cascades: eval > agent config > default. */\n evalOptions?: {\n idleTimeout?: number\n /** LLM judge pass threshold (integer, 1-5). Values outside this range are clamped. Cascades: eval > agent config > default (3). */\n judgePassThreshold?: number\n /** Model to use for llm_judge assertions (e.g. 'openai:gpt-4o'). Defaults to 'fast'. */\n judgeModel?: string\n }\n /** Factory for creating span sources. Each eval gets its own instance. Defaults to LocalSpanSource (SSE from dev server). */\n createSpanSource?: () => SpanSource\n /** Externally-provided run ID. When set, the runner uses this instead of generating its own. */\n runId?: string\n /** Pre-resolved chat integration webhook ID. Skips the getBot() discovery call when provided. */\n chatWebhookId?: string\n /** Base URL for the chat service (e.g. https://chat.botpress.dev). Defaults to https://chat.botpress.cloud. */\n chatBaseUrl?: string\n}\n\n// --- Eval suite filter ---\n\nexport interface EvalFilter {\n names?: string[]\n tags?: string[]\n type?: 'capability' | 'regression'\n}\n\n// --- Transformer types (trace-driven eval engine) ---\n\nexport interface StateMutation {\n type: string // 'bot', 'user', 'conversation'\n changedKeys: string[]\n previous: unknown\n current: unknown\n swappedToFile: boolean // data['swapped_to_file'] === true\n}\n\nexport interface WorkflowSpan {\n name: string\n status: 'running' | 'ok' | 'error'\n statusFinal?: string // 'completed', 'continue', 'failed'\n}\n\nexport interface TurnData {\n messages: string[]\n toolCalls: ToolCall[]\n stateMutations: StateMutation[]\n workflowSpans: WorkflowSpan[]\n handlerDuration: number\n handlerStatus: 'ok' | 'error'\n}\n"],
|
|
5
|
-
"mappings": ";
|
|
4
|
+
"sourcesContent": ["/**\n * LLM judge grader using @botpress/cognitive.\n * Replaces the OpenAI-based implementation from the standalone project.\n */\n\nimport { Client } from '@botpress/client'\nimport { Cognitive } from '@botpress/cognitive'\nimport type { EvalLogger, GraderResult } from '../types'\nimport { defaultLogger } from '../types'\n\nconst DEFAULT_PASS_THRESHOLD = 3\n\nfunction buildJudgeSystemPrompt(passThreshold: number): string {\n return `You are an evaluation judge for a chatbot. You will be given:\n- The user's message\n- The bot's response\n- Grading criteria\n\nYour job is to determine if the bot's response meets the criteria.\n\nRespond with a JSON object:\n{\n \"pass\": true/false,\n \"score\": 1-5,\n \"reason\": \"brief explanation\"\n}\n\nScoring guide:\n- 5: Fully meets criteria, excellent response\n- 4: Mostly meets criteria, minor issues\n- 3: Partially meets criteria, notable gaps\n- 2: Barely meets criteria, significant issues\n- 1: Does not meet criteria\n\nA score of ${passThreshold} or above is a pass.`\n}\n\nconst MODEL_ALIASES = ['fast', 'best']\n\nlet _cognitive: Cognitive | null = null\nlet _availableModels: string[] = []\nlet _judgeModel: string = 'fast'\nlet _log: EvalLogger = defaultLogger\n\n/** @internal Test-only: clears module judge state so tests stay hermetic in the shared bun test process. */\nexport function _resetLLMJudgeForTests(): void {\n _cognitive = null\n _availableModels = []\n _judgeModel = 'fast'\n _log = defaultLogger\n}\n\nfunction _isModelValid(model: string): boolean {\n if (MODEL_ALIASES.includes(model)) return true\n if (_availableModels.length === 0) return false\n\n return _availableModels.includes(model)\n}\n\n/**\n * Initialize the LLM judge with explicit credentials.\n * Call this before running evals so the judge doesn't need env vars.\n */\nexport async function initLLMJudge(\n credentials: { token: string; apiUrl: string; botId: string; workspaceId?: string },\n options?: { model?: string; logger?: EvalLogger }\n) {\n const log = options?.logger ?? defaultLogger\n _log = log\n\n const client = new Client({\n token: credentials.token,\n apiUrl: credentials.apiUrl,\n botId: credentials.botId,\n ...(credentials.workspaceId !== undefined ? { workspaceId: credentials.workspaceId } : {}),\n })\n _cognitive = new Cognitive({ client, __experimental_beta: true })\n\n try {\n _availableModels = Array.from((await _cognitive.fetchRemoteModels()).keys())\n } catch (err) {\n log.warn(`Failed to fetch available models: ${(err as Error).message}. LLM judge will be unavailable.`)\n _availableModels = []\n }\n\n _judgeModel = options?.model ?? 'fast'\n\n if (_availableModels.length === 0) {\n log.warn('No available Cognitive models: cannot validate judge model.')\n } else if (!_isModelValid(_judgeModel)) {\n log.warn(`Configured LLM judge model \"${_judgeModel}\" is invalid. Run \"adk models\" to list available models.`)\n }\n}\n\nexport async function gradeLLMJudge(\n botResponse: string,\n criteria: string,\n context: { userMessage: string; passThreshold?: number }\n): Promise<GraderResult> {\n const threshold = Math.max(1, Math.min(5, context.passThreshold ?? DEFAULT_PASS_THRESHOLD))\n\n try {\n // A judge that can't run must NOT silently pass the assertion \u2014 a flaky\n // LLM call or missing credentials would turn real assertions green.\n // Unavailability is a visible failure with a clear reason.\n if (!_cognitive) {\n _log.warn(`LLM judge unavailable for \"${criteria}\": no credentials configured (initLLMJudge not called)`)\n return {\n assertion: `llm_judge: \"${criteria}\"`,\n pass: false,\n expected: criteria,\n actual: 'FAILED \u2014 LLM judge unavailable: no credentials configured',\n }\n }\n\n if (!_isModelValid(_judgeModel)) {\n return {\n assertion: `llm_judge: \"${criteria}\"`,\n pass: false,\n expected: criteria,\n actual: 'FAILED \u2014 invalid LLM judge model',\n }\n }\n\n type CognitiveModel = Exclude<Parameters<Cognitive['generateContent']>[0]['model'], undefined>\n\n const { output } = await _cognitive.generateContent({\n model: _judgeModel as CognitiveModel,\n temperature: 0,\n responseFormat: 'json_object',\n systemPrompt: buildJudgeSystemPrompt(threshold),\n messages: [\n {\n role: 'user',\n content: `User message: ${context.userMessage}\\n\\nBot response: ${botResponse}\\n\\nCriteria: ${criteria}`,\n },\n ],\n })\n\n const rawContent = output?.choices?.[0]?.content\n const content = typeof rawContent === 'string' ? rawContent : null\n if (!content) {\n _log.warn(`LLM judge returned an empty response for \"${criteria}\"`)\n return {\n assertion: `llm_judge: \"${criteria}\"`,\n pass: false,\n expected: criteria,\n actual: 'FAILED \u2014 LLM judge returned empty response',\n }\n }\n\n const verdict = JSON.parse(content) as {\n pass: boolean\n score: number\n reason: string\n }\n\n return {\n assertion: `llm_judge: \"${criteria}\"`,\n pass: verdict.score >= threshold,\n expected: criteria,\n actual: `Score ${verdict.score}/5 (threshold: ${threshold}) \u2014 ${verdict.reason}`,\n }\n } catch (err) {\n _log.warn(`LLM judge failed for \"${criteria}\": ${(err as Error).message}`)\n return {\n assertion: `llm_judge: \"${criteria}\"`,\n pass: false,\n expected: criteria,\n actual: `FAILED \u2014 LLM judge unavailable: ${(err as Error).message}`,\n }\n }\n}\n", "/**\n * Eval type definitions.\n *\n * User-facing types live in @botpress/evals so eval authors can update eval\n * tooling without tying the authoring API to the agent runtime package.\n */\n\nexport {\n Eval,\n type EvalDefinition,\n type EvalSetup,\n type ConversationTurn,\n type TurnAssertions,\n type OutcomeAssertions,\n type ResponseAssertion,\n type ToolAssertion,\n type StateAssertion,\n type WorkflowAssertion,\n type TimingAssertion,\n type MatchOperator,\n type NumericOperator,\n} from './definition'\n\nexport type { Span, SpanStatus } from './trace'\n\nexport interface ChatClientConnection {\n user: { id: string }\n createConversation: (props: Record<string, unknown>) => Promise<{ conversation: { id: string } }>\n // Broad parameter types keep this compatible with @botpress/chat's narrower\n // generated payload unions while avoiding a dependency on those definitions.\n createMessage: (props: any) => Promise<unknown>\n createEvent: (props: any) => Promise<unknown>\n}\n\nexport interface ChatClient {\n connect: (props: { webhookId: string }) => Promise<ChatClientConnection>\n}\n\n// --- Grader result (universal currency for all graders) ---\n\nexport interface GraderResult {\n assertion: string\n pass: boolean\n expected: string\n actual: string\n}\n\n// --- Tool call extracted from traces ---\n\nexport interface ToolCall {\n name: string\n input: Record<string, unknown>\n output: string\n status: string\n}\n\n// --- Turn report ---\n\nexport interface TurnReport {\n turnNumber: number\n userMessage: string\n botResponse: string\n assertions: GraderResult[]\n pass: boolean\n /** Time spent waiting for the bot to respond (ms) */\n botDuration: number\n /** Time spent fetching traces + running graders (ms) */\n evalDuration: number\n}\n\n// --- Single eval report ---\n\nexport interface EvalReport {\n name: string\n description?: string\n type?: 'capability' | 'regression'\n tags?: string[]\n turns: TurnReport[]\n outcomeAssertions: GraderResult[]\n pass: boolean\n duration: number\n error?: string\n /** Stable EvalErrorCode when `error` came from a typed EvalRunnerError \u2014 lets consumers distinguish setup/config failures from bot failures. */\n errorCode?: string\n}\n\n// --- Progress event for real-time UI updates ---\n\nexport type EvalProgressEvent =\n | { type: 'suite_start'; totalEvals: number }\n | { type: 'eval_start'; evalName: string; index: number; totalTurns: number }\n | {\n type: 'turn_start'\n evalName: string\n evalIndex: number\n turnNumber: number\n totalTurns: number\n userMessage: string\n }\n | {\n type: 'turn_complete'\n evalName: string\n evalIndex: number\n turnNumber: number\n totalTurns: number\n turnReport: TurnReport\n }\n | { type: 'eval_complete'; evalName: string; index: number; report: EvalReport }\n | { type: 'suite_complete'; report: EvalRunReport; error?: string }\n\n// --- Eval run report (full suite) ---\n\nexport interface EvalRunReport {\n id: string\n timestamp: string\n evals: EvalReport[]\n passed: number\n failed: number\n total: number\n duration: number\n filter?: {\n names?: string[]\n tags?: string[]\n type?: 'capability' | 'regression'\n }\n /**\n * True when the suite was aborted mid-run (e.g. user clicked Stop). The\n * persisted report is partial \u2014 `evals` reflects only the completed evals,\n * and `total` matches that count, not the original suite size.\n */\n aborted?: boolean\n}\n\n// --- Bot connection info ---\n\nexport interface BotConnection {\n webhookId: string\n botId: string\n token: string\n apiUrl: string\n}\n\n// --- Logger interface ---\n\nexport interface EvalLogger {\n info: (message: string) => void\n warn: (message: string) => void\n error: (message: string) => void\n}\n\n/**\n * Fallback when no logger is injected (programmatic use outside the CLI).\n * console rather than a no-op so warnings stay visible \u2014 a silent default\n * would hide judge failures and skipped pre-flights, the exact swallow\n * anti-pattern docs/ERROR-HANDLING.md bans. The CLI always injects its own\n * structured logger via EvalRunnerConfig.logger.\n */\nexport const defaultLogger: EvalLogger = console\n\n// --- Eval runner configuration ---\n\nexport interface EvalRunnerConfig {\n credentials: {\n token: string\n apiUrl: string\n botId: string\n workspaceId?: string\n webhookId?: string\n }\n agentPath: string\n /** URL of the dev server providing traces and config. Defaults to the discovered DevConsole URL. */\n devServerUrl?: string\n /** Headers for dev-server requests, e.g. X-Agent-Path when routed through the singleton proxy. */\n devServerHeaders?: Record<string, string>\n /**\n * Optional host-provided chat client. The CLI passes its bundled chat client\n * here so the eval engine does not depend on @botpress/adk.\n */\n chatClient?: ChatClient\n onProgress?: (event: EvalProgressEvent) => void\n /** Logger for warnings and errors. Defaults to console. */\n logger?: EvalLogger\n /**\n * Called for unexpected (internal-bug) eval failures that runEval folds\n * into report.error \u2014 they never propagate to the CLI's command boundary,\n * so without this hook they'd be invisible to error tracking. The CLI binds\n * this to telemetry.captureException; evals itself stays telemetry-free.\n */\n onException?: (error: unknown, properties?: Record<string, unknown>) => void\n /**\n * Optional abort signal \u2014 when fired, the suite stops starting new evals.\n * The currently running eval continues to completion (LLM calls in flight\n * cannot always be cancelled), but no further evals are started.\n */\n signal?: AbortSignal\n /** Bot-level eval options from agent.config.ts. Cascades: eval > agent config > default. */\n evalOptions?: {\n idleTimeout?: number\n /** LLM judge pass threshold (integer, 1-5). Values outside this range are clamped. Cascades: eval > agent config > default (3). */\n judgePassThreshold?: number\n /** Model to use for llm_judge assertions (e.g. 'openai:gpt-4o'). Defaults to 'fast'. */\n judgeModel?: string\n }\n}\n\n// --- Eval suite filter ---\n\nexport interface EvalFilter {\n names?: string[]\n tags?: string[]\n type?: 'capability' | 'regression'\n}\n\n// --- Transformer types (trace-driven eval engine) ---\n\nexport interface StateMutation {\n type: string // 'bot', 'user', 'conversation'\n changedKeys: string[]\n previous: unknown\n current: unknown\n swappedToFile: boolean // data['swapped_to_file'] === true\n}\n\nexport interface WorkflowSpan {\n name: string\n status: 'running' | 'ok' | 'error'\n statusFinal?: string // 'completed', 'continue', 'failed'\n}\n\nexport interface TurnData {\n messages: string[]\n toolCalls: ToolCall[]\n stateMutations: StateMutation[]\n workflowSpans: WorkflowSpan[]\n handlerDuration: number\n handlerStatus: 'ok' | 'error'\n}\n"],
|
|
5
|
+
"mappings": ";AAKA,SAAS,cAAc;AACvB,SAAS,iBAAiB;;;ACuJnB,IAAM,gBAA4B;;;ADnJzC,IAAM,yBAAyB;AAE/B,SAAS,uBAAuB,eAA+B;AAC7D,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,aAqBI,aAAa;AAC1B;AAEA,IAAM,gBAAgB,CAAC,QAAQ,MAAM;AAErC,IAAI,aAA+B;AACnC,IAAI,mBAA6B,CAAC;AAClC,IAAI,cAAsB;AAC1B,IAAI,OAAmB;AAGhB,SAAS,yBAA+B;AAC7C,eAAa;AACb,qBAAmB,CAAC;AACpB,gBAAc;AACd,SAAO;AACT;AAEA,SAAS,cAAc,OAAwB;AAC7C,MAAI,cAAc,SAAS,KAAK,EAAG,QAAO;AAC1C,MAAI,iBAAiB,WAAW,EAAG,QAAO;AAE1C,SAAO,iBAAiB,SAAS,KAAK;AACxC;AAMA,eAAsB,aACpB,aACA,SACA;AACA,QAAM,MAAM,SAAS,UAAU;AAC/B,SAAO;AAEP,QAAM,SAAS,IAAI,OAAO;AAAA,IACxB,OAAO,YAAY;AAAA,IACnB,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,QAAQ,WAAW;AAAA;AAAA,gBAAqB,WAAW;AAAA;AAAA,YAAiB,QAAQ;AAAA,QACxG;AAAA,MACF;AAAA,IACF,CAAC;AAED,UAAM,aAAa,QAAQ,UAAU,CAAC,GAAG;AACzC,UAAM,UAAU,OAAO,eAAe,WAAW,aAAa;AAC9D,QAAI,CAAC,SAAS;AACZ,WAAK,KAAK,6CAA6C,QAAQ,GAAG;AAClE,aAAO;AAAA,QACL,WAAW,eAAe,QAAQ;AAAA,QAClC,MAAM;AAAA,QACN,UAAU;AAAA,QACV,QAAQ;AAAA,MACV;AAAA,IACF;AAEA,UAAM,UAAU,KAAK,MAAM,OAAO;AAMlC,WAAO;AAAA,MACL,WAAW,eAAe,QAAQ;AAAA,MAClC,MAAM,QAAQ,SAAS;AAAA,MACvB,UAAU;AAAA,MACV,QAAQ,SAAS,QAAQ,KAAK,kBAAkB,SAAS,YAAO,QAAQ,MAAM;AAAA,IAChF;AAAA,EACF,SAAS,KAAK;AACZ,SAAK,KAAK,yBAAyB,QAAQ,MAAO,IAAc,OAAO,EAAE;AACzE,WAAO;AAAA,MACL,WAAW,eAAe,QAAQ;AAAA,MAClC,MAAM;AAAA,MACN,UAAU;AAAA,MACV,QAAQ,wCAAoC,IAAc,OAAO;AAAA,IACnE;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/graders/response.js
CHANGED
|
@@ -1,16 +1,40 @@
|
|
|
1
1
|
// src/graders/llm.ts
|
|
2
|
+
import { Client } from "@botpress/client";
|
|
2
3
|
import { Cognitive } from "@botpress/cognitive";
|
|
3
|
-
import { Zai } from "@botpress/zai";
|
|
4
4
|
|
|
5
5
|
// src/types.ts
|
|
6
6
|
var defaultLogger = console;
|
|
7
7
|
|
|
8
8
|
// src/graders/llm.ts
|
|
9
|
+
var DEFAULT_PASS_THRESHOLD = 3;
|
|
10
|
+
function buildJudgeSystemPrompt(passThreshold) {
|
|
11
|
+
return `You are an evaluation judge for a chatbot. You will be given:
|
|
12
|
+
- The user's message
|
|
13
|
+
- The bot's response
|
|
14
|
+
- Grading criteria
|
|
15
|
+
|
|
16
|
+
Your job is to determine if the bot's response meets the criteria.
|
|
17
|
+
|
|
18
|
+
Respond with a JSON object:
|
|
19
|
+
{
|
|
20
|
+
"pass": true/false,
|
|
21
|
+
"score": 1-5,
|
|
22
|
+
"reason": "brief explanation"
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
Scoring guide:
|
|
26
|
+
- 5: Fully meets criteria, excellent response
|
|
27
|
+
- 4: Mostly meets criteria, minor issues
|
|
28
|
+
- 3: Partially meets criteria, notable gaps
|
|
29
|
+
- 2: Barely meets criteria, significant issues
|
|
30
|
+
- 1: Does not meet criteria
|
|
31
|
+
|
|
32
|
+
A score of ${passThreshold} or above is a pass.`;
|
|
33
|
+
}
|
|
9
34
|
var MODEL_ALIASES = ["fast", "best"];
|
|
10
|
-
var
|
|
35
|
+
var _cognitive = null;
|
|
11
36
|
var _availableModels = [];
|
|
12
37
|
var _judgeModel = "fast";
|
|
13
|
-
var _failClosed = true;
|
|
14
38
|
var _log = defaultLogger;
|
|
15
39
|
function _isModelValid(model) {
|
|
16
40
|
if (MODEL_ALIASES.includes(model)) return true;
|
|
@@ -18,39 +42,64 @@ function _isModelValid(model) {
|
|
|
18
42
|
return _availableModels.includes(model);
|
|
19
43
|
}
|
|
20
44
|
async function gradeLLMJudge(botResponse, criteria, context) {
|
|
21
|
-
const
|
|
45
|
+
const threshold = Math.max(1, Math.min(5, context.passThreshold ?? DEFAULT_PASS_THRESHOLD));
|
|
22
46
|
try {
|
|
23
|
-
if (!
|
|
47
|
+
if (!_cognitive) {
|
|
24
48
|
_log.warn(`LLM judge unavailable for "${criteria}": no credentials configured (initLLMJudge not called)`);
|
|
25
49
|
return {
|
|
26
|
-
assertion
|
|
27
|
-
pass:
|
|
28
|
-
skipped: true,
|
|
50
|
+
assertion: `llm_judge: "${criteria}"`,
|
|
51
|
+
pass: false,
|
|
29
52
|
expected: criteria,
|
|
30
53
|
actual: "FAILED \u2014 LLM judge unavailable: no credentials configured"
|
|
31
54
|
};
|
|
32
55
|
}
|
|
33
56
|
if (!_isModelValid(_judgeModel)) {
|
|
34
57
|
return {
|
|
35
|
-
assertion
|
|
58
|
+
assertion: `llm_judge: "${criteria}"`,
|
|
36
59
|
pass: false,
|
|
37
60
|
expected: criteria,
|
|
38
61
|
actual: "FAILED \u2014 invalid LLM judge model"
|
|
39
62
|
};
|
|
40
63
|
}
|
|
41
|
-
const { output } = await
|
|
64
|
+
const { output } = await _cognitive.generateContent({
|
|
65
|
+
model: _judgeModel,
|
|
66
|
+
temperature: 0,
|
|
67
|
+
responseFormat: "json_object",
|
|
68
|
+
systemPrompt: buildJudgeSystemPrompt(threshold),
|
|
69
|
+
messages: [
|
|
70
|
+
{
|
|
71
|
+
role: "user",
|
|
72
|
+
content: `User message: ${context.userMessage}
|
|
73
|
+
|
|
74
|
+
Bot response: ${botResponse}
|
|
75
|
+
|
|
76
|
+
Criteria: ${criteria}`
|
|
77
|
+
}
|
|
78
|
+
]
|
|
79
|
+
});
|
|
80
|
+
const rawContent = output?.choices?.[0]?.content;
|
|
81
|
+
const content = typeof rawContent === "string" ? rawContent : null;
|
|
82
|
+
if (!content) {
|
|
83
|
+
_log.warn(`LLM judge returned an empty response for "${criteria}"`);
|
|
84
|
+
return {
|
|
85
|
+
assertion: `llm_judge: "${criteria}"`,
|
|
86
|
+
pass: false,
|
|
87
|
+
expected: criteria,
|
|
88
|
+
actual: "FAILED \u2014 LLM judge returned empty response"
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
const verdict = JSON.parse(content);
|
|
42
92
|
return {
|
|
43
|
-
assertion
|
|
44
|
-
pass:
|
|
93
|
+
assertion: `llm_judge: "${criteria}"`,
|
|
94
|
+
pass: verdict.score >= threshold,
|
|
45
95
|
expected: criteria,
|
|
46
|
-
actual:
|
|
96
|
+
actual: `Score ${verdict.score}/5 (threshold: ${threshold}) \u2014 ${verdict.reason}`
|
|
47
97
|
};
|
|
48
98
|
} catch (err) {
|
|
49
99
|
_log.warn(`LLM judge failed for "${criteria}": ${err.message}`);
|
|
50
100
|
return {
|
|
51
|
-
assertion
|
|
52
|
-
pass:
|
|
53
|
-
skipped: true,
|
|
101
|
+
assertion: `llm_judge: "${criteria}"`,
|
|
102
|
+
pass: false,
|
|
54
103
|
expected: criteria,
|
|
55
104
|
actual: `FAILED \u2014 LLM judge unavailable: ${err.message}`
|
|
56
105
|
};
|