@memberjunction/testing-engine 6.2.0-edge.0 → 6.2.0-edge.2
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/README.md +4 -1
- package/dist/decision-eval/corpus.d.ts +94 -0
- package/dist/decision-eval/corpus.d.ts.map +1 -0
- package/dist/decision-eval/corpus.js +144 -0
- package/dist/decision-eval/corpus.js.map +1 -0
- package/dist/decision-eval/discovery-baseline.d.ts +62 -0
- package/dist/decision-eval/discovery-baseline.d.ts.map +1 -0
- package/dist/decision-eval/discovery-baseline.js +90 -0
- package/dist/decision-eval/discovery-baseline.js.map +1 -0
- package/dist/decision-eval/discovery-corpus.d.ts +75 -0
- package/dist/decision-eval/discovery-corpus.d.ts.map +1 -0
- package/dist/decision-eval/discovery-corpus.js +110 -0
- package/dist/decision-eval/discovery-corpus.js.map +1 -0
- package/dist/decision-eval/discovery-mapping.d.ts +18 -0
- package/dist/decision-eval/discovery-mapping.d.ts.map +1 -0
- package/dist/decision-eval/discovery-mapping.js +21 -0
- package/dist/decision-eval/discovery-mapping.js.map +1 -0
- package/dist/decision-eval/discovery-metrics.d.ts +339 -0
- package/dist/decision-eval/discovery-metrics.d.ts.map +1 -0
- package/dist/decision-eval/discovery-metrics.js +401 -0
- package/dist/decision-eval/discovery-metrics.js.map +1 -0
- package/dist/decision-eval/discovery-scorecard.d.ts +96 -0
- package/dist/decision-eval/discovery-scorecard.d.ts.map +1 -0
- package/dist/decision-eval/discovery-scorecard.js +351 -0
- package/dist/decision-eval/discovery-scorecard.js.map +1 -0
- package/dist/decision-eval/discovery-suite.d.ts +201 -0
- package/dist/decision-eval/discovery-suite.d.ts.map +1 -0
- package/dist/decision-eval/discovery-suite.js +180 -0
- package/dist/decision-eval/discovery-suite.js.map +1 -0
- package/dist/decision-eval/discovery-types.d.ts +896 -0
- package/dist/decision-eval/discovery-types.d.ts.map +1 -0
- package/dist/decision-eval/discovery-types.js +211 -0
- package/dist/decision-eval/discovery-types.js.map +1 -0
- package/dist/decision-eval/index.d.ts +18 -0
- package/dist/decision-eval/index.d.ts.map +1 -0
- package/dist/decision-eval/index.js +18 -0
- package/dist/decision-eval/index.js.map +1 -0
- package/dist/decision-eval/metrics.d.ts +330 -0
- package/dist/decision-eval/metrics.d.ts.map +1 -0
- package/dist/decision-eval/metrics.js +574 -0
- package/dist/decision-eval/metrics.js.map +1 -0
- package/dist/decision-eval/output-paths.d.ts +119 -0
- package/dist/decision-eval/output-paths.d.ts.map +1 -0
- package/dist/decision-eval/output-paths.js +258 -0
- package/dist/decision-eval/output-paths.js.map +1 -0
- package/dist/decision-eval/point-mapping.d.ts +50 -0
- package/dist/decision-eval/point-mapping.d.ts.map +1 -0
- package/dist/decision-eval/point-mapping.js +83 -0
- package/dist/decision-eval/point-mapping.js.map +1 -0
- package/dist/decision-eval/scorecard.d.ts +190 -0
- package/dist/decision-eval/scorecard.d.ts.map +1 -0
- package/dist/decision-eval/scorecard.js +384 -0
- package/dist/decision-eval/scorecard.js.map +1 -0
- package/dist/decision-eval/suite.d.ts +244 -0
- package/dist/decision-eval/suite.d.ts.map +1 -0
- package/dist/decision-eval/suite.js +238 -0
- package/dist/decision-eval/suite.js.map +1 -0
- package/dist/decision-eval/types.d.ts +993 -0
- package/dist/decision-eval/types.d.ts.map +1 -0
- package/dist/decision-eval/types.js +227 -0
- package/dist/decision-eval/types.js.map +1 -0
- package/dist/drivers/AgentEvalDriver.d.ts +30 -1
- package/dist/drivers/AgentEvalDriver.d.ts.map +1 -1
- package/dist/drivers/AgentEvalDriver.js +145 -16
- package/dist/drivers/AgentEvalDriver.js.map +1 -1
- package/dist/drivers/DecisionEvalDriver.d.ts +297 -0
- package/dist/drivers/DecisionEvalDriver.d.ts.map +1 -0
- package/dist/drivers/DecisionEvalDriver.js +716 -0
- package/dist/drivers/DecisionEvalDriver.js.map +1 -0
- package/dist/drivers/PinnedDecisionRunner.d.ts +24 -0
- package/dist/drivers/PinnedDecisionRunner.d.ts.map +1 -0
- package/dist/drivers/PinnedDecisionRunner.js +24 -0
- package/dist/drivers/PinnedDecisionRunner.js.map +1 -0
- package/dist/drivers/PromptEvalDriver.d.ts.map +1 -1
- package/dist/drivers/PromptEvalDriver.js +11 -4
- package/dist/drivers/PromptEvalDriver.js.map +1 -1
- package/dist/drivers/RubricCalibrationTestDriver.d.ts +34 -0
- package/dist/drivers/RubricCalibrationTestDriver.d.ts.map +1 -0
- package/dist/drivers/RubricCalibrationTestDriver.js +193 -0
- package/dist/drivers/RubricCalibrationTestDriver.js.map +1 -0
- package/dist/drivers/calibration.d.ts +85 -0
- package/dist/drivers/calibration.d.ts.map +1 -0
- package/dist/drivers/calibration.js +191 -0
- package/dist/drivers/calibration.js.map +1 -0
- package/dist/drivers/index.d.ts +2 -0
- package/dist/drivers/index.d.ts.map +1 -1
- package/dist/drivers/index.js +2 -0
- package/dist/drivers/index.js.map +1 -1
- package/dist/engine/TestEngine.d.ts.map +1 -1
- package/dist/engine/TestEngine.js +21 -11
- package/dist/engine/TestEngine.js.map +1 -1
- package/dist/eval/corpus.d.ts +8 -0
- package/dist/eval/corpus.d.ts.map +1 -1
- package/dist/eval/corpus.js +26 -10
- package/dist/eval/corpus.js.map +1 -1
- package/dist/eval/decision.d.ts +8 -0
- package/dist/eval/decision.d.ts.map +1 -1
- package/dist/eval/decision.js +23 -7
- package/dist/eval/decision.js.map +1 -1
- package/dist/eval/expectation.d.ts +2 -0
- package/dist/eval/expectation.d.ts.map +1 -1
- package/dist/eval/expectation.js +9 -5
- package/dist/eval/expectation.js.map +1 -1
- package/dist/eval/history.d.ts +2 -0
- package/dist/eval/history.d.ts.map +1 -1
- package/dist/eval/history.js +5 -1
- package/dist/eval/history.js.map +1 -1
- package/dist/eval/matchers.d.ts +7 -0
- package/dist/eval/matchers.d.ts.map +1 -1
- package/dist/eval/matchers.js +11 -3
- package/dist/eval/matchers.js.map +1 -1
- package/dist/eval/subAgentTrace.d.ts +8 -6
- package/dist/eval/subAgentTrace.d.ts.map +1 -1
- package/dist/eval/subAgentTrace.js +15 -11
- package/dist/eval/subAgentTrace.js.map +1 -1
- package/dist/eval/wellFormed.d.ts +2 -0
- package/dist/eval/wellFormed.d.ts.map +1 -1
- package/dist/eval/wellFormed.js +5 -1
- package/dist/eval/wellFormed.js.map +1 -1
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -0
- package/dist/index.js.map +1 -1
- package/dist/oracles/AgentDecisionOracle.js +7 -7
- package/dist/oracles/DecisionJudgeOracle.d.ts +97 -0
- package/dist/oracles/DecisionJudgeOracle.d.ts.map +1 -0
- package/dist/oracles/DecisionJudgeOracle.js +230 -0
- package/dist/oracles/DecisionJudgeOracle.js.map +1 -0
- package/dist/oracles/DecisionLabelMatchOracle.d.ts +38 -0
- package/dist/oracles/DecisionLabelMatchOracle.d.ts.map +1 -0
- package/dist/oracles/DecisionLabelMatchOracle.js +96 -0
- package/dist/oracles/DecisionLabelMatchOracle.js.map +1 -0
- package/dist/oracles/DiscoveryLabelMatchOracle.d.ts +39 -0
- package/dist/oracles/DiscoveryLabelMatchOracle.d.ts.map +1 -0
- package/dist/oracles/DiscoveryLabelMatchOracle.js +88 -0
- package/dist/oracles/DiscoveryLabelMatchOracle.js.map +1 -0
- package/dist/oracles/LLMJudgeOracle.d.ts +2 -47
- package/dist/oracles/LLMJudgeOracle.d.ts.map +1 -1
- package/dist/oracles/LLMJudgeOracle.js +80 -149
- package/dist/oracles/LLMJudgeOracle.js.map +1 -1
- package/dist/oracles/RubricOracle.d.ts +51 -0
- package/dist/oracles/RubricOracle.d.ts.map +1 -0
- package/dist/oracles/RubricOracle.js +66 -0
- package/dist/oracles/RubricOracle.js.map +1 -0
- package/dist/oracles/TraceSubAgentValidatorOracle.js +3 -3
- package/dist/oracles/index.d.ts +5 -0
- package/dist/oracles/index.d.ts.map +1 -1
- package/dist/oracles/index.js +5 -0
- package/dist/oracles/index.js.map +1 -1
- package/dist/oracles/inline-rubric.d.ts +25 -0
- package/dist/oracles/inline-rubric.d.ts.map +1 -0
- package/dist/oracles/inline-rubric.js +82 -0
- package/dist/oracles/inline-rubric.js.map +1 -0
- package/dist/oracles/judge-trace.d.ts +76 -0
- package/dist/oracles/judge-trace.d.ts.map +1 -0
- package/dist/oracles/judge-trace.js +125 -0
- package/dist/oracles/judge-trace.js.map +1 -0
- package/dist/oracles/promote-criteria.d.ts +57 -0
- package/dist/oracles/promote-criteria.d.ts.map +1 -0
- package/dist/oracles/promote-criteria.js +104 -0
- package/dist/oracles/promote-criteria.js.map +1 -0
- package/dist/oracles/rubric-resolution.d.ts +69 -0
- package/dist/oracles/rubric-resolution.d.ts.map +1 -0
- package/dist/oracles/rubric-resolution.js +110 -0
- package/dist/oracles/rubric-resolution.js.map +1 -0
- package/dist/types.d.ts +4 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/cost-calculator.d.ts +34 -0
- package/dist/utils/cost-calculator.d.ts.map +1 -1
- package/dist/utils/cost-calculator.js +40 -8
- package/dist/utils/cost-calculator.js.map +1 -1
- package/dist/utils/execution-context.d.ts +6 -0
- package/dist/utils/execution-context.d.ts.map +1 -1
- package/dist/utils/execution-context.js +15 -3
- package/dist/utils/execution-context.js.map +1 -1
- package/dist/utils/result-formatter.d.ts +38 -0
- package/dist/utils/result-formatter.d.ts.map +1 -1
- package/dist/utils/result-formatter.js +74 -24
- package/dist/utils/result-formatter.js.map +1 -1
- package/dist/utils/scoring.d.ts +20 -0
- package/dist/utils/scoring.d.ts.map +1 -1
- package/dist/utils/scoring.js +35 -7
- package/dist/utils/scoring.js.map +1 -1
- package/dist/utils/variable-resolver.d.ts +20 -1
- package/dist/utils/variable-resolver.d.ts.map +1 -1
- package/dist/utils/variable-resolver.js +58 -20
- package/dist/utils/variable-resolver.js.map +1 -1
- package/package.json +12 -10
|
@@ -0,0 +1,716 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Decision-eval driver: one typed decision, built exactly as production builds it,
|
|
3
|
+
* scored against a label.
|
|
4
|
+
* @module @memberjunction/testing-engine
|
|
5
|
+
*/
|
|
6
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
7
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
9
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
10
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
11
|
+
};
|
|
12
|
+
import { RegisterClass, UUIDsEqual } from '@memberjunction/global';
|
|
13
|
+
import { AIEngine } from '@memberjunction/aiengine';
|
|
14
|
+
import { AIDecisionParams, AIDecisionRunner } from '@memberjunction/ai-prompts';
|
|
15
|
+
import { BuildDecisionDiscoveryOptionSet, BuildDecisionDiscoveryQuestions, CanSearchEntities, DECISION_DISCOVERY_MIN_CONFIDENCE, DECISION_DISCOVERY_MIN_OPTIONS, DECISION_DISCOVERY_TIMEOUT_MS, DecisionDiscoveryAgentSearch, DecisionDiscoveryCatalog, DecisionDiscoveryFromResult, DecisionDiscoveryRunnableAgents, DecisionPromptOptionCap, JudgeDecisionDiscovery, MentionsAgent } from '@memberjunction/ai-agents';
|
|
16
|
+
import { BuildRoutingQuestions, BuildRoutingState, BuildRoutingStateStructured, CanAskRoutingDecision, DECISION_ROUTING_MIN_CONFIDENCE, DECISION_ROUTING_TIMEOUT_MS, FindDecisionCalibration, InterpretRoutingAnswers, ROUTING_CONTINUES_CALIBRATION, ROUTING_CONTINUES_QUESTION, ROUTING_ROUTE_QUESTION } from '@memberjunction/ai-core-plus';
|
|
17
|
+
import { BaseTestDriver } from './BaseTestDriver.js';
|
|
18
|
+
import { PinnedDecisionRunner } from './PinnedDecisionRunner.js';
|
|
19
|
+
import { OraclesWithNamedRubric } from '../oracles/rubric-resolution.js';
|
|
20
|
+
import { MapPointToRoutingInput } from '../decision-eval/point-mapping.js';
|
|
21
|
+
import { DiscoveryDecisionState } from '../decision-eval/discovery-mapping.js';
|
|
22
|
+
import { FIND_CANDIDATE_AGENTS_TOP_K, RankSemanticSearchBaseline } from '../decision-eval/discovery-baseline.js';
|
|
23
|
+
import { DiscoveryEvalConfigSchema, DiscoveryEvalExpectedSchema, DiscoveryEvalInputSchema } from '../decision-eval/discovery-types.js';
|
|
24
|
+
import { DEFAULT_DECISION_PROMPT_NAME, DecisionEvalConfigSchema, DecisionEvalExpectedSchema, DecisionEvalInputSchema, DecisionEvalKindSchema, DescribeZodError } from '../decision-eval/types.js';
|
|
25
|
+
/** The conversation manager the routing decision offers as "someone else", and the agent that runs discovery. */
|
|
26
|
+
export const CONVERSATION_MANAGER_NAME = 'Sage';
|
|
27
|
+
/**
|
|
28
|
+
* Why a requested temperature or seed does not reach the model: say it plainly rather than fake it.
|
|
29
|
+
*/
|
|
30
|
+
const SAMPLING_NOT_APPLIED = 'The decision path has no sampling parameters: AIDecisionRunner passes only the model, '
|
|
31
|
+
+ 'state, questions and cancellation to the driver (DecisionParams), and LLMDecision builds its chat prompt\'s '
|
|
32
|
+
+ 'parameters without a temperature or seed. The request is recorded, not applied.';
|
|
33
|
+
/**
|
|
34
|
+
* Runs ONE typed decision on a corpus point and scores it against the point's label.
|
|
35
|
+
*
|
|
36
|
+
* The point is mapped to the routing decision's input, and the questions and state are built, with
|
|
37
|
+
* the same builders the chat uses (`@memberjunction/ai-core-plus`), so the eval sends exactly what
|
|
38
|
+
* production sends. One `AIDecisionRunner.ExecuteDecision` answers it, and the oracles score the
|
|
39
|
+
* answer. The prompt run is linked as the test run's target, so cost comes from it.
|
|
40
|
+
*
|
|
41
|
+
* **Pinning.** A cell that names `modelId` and/or `vendorId` pins them through the runner's own
|
|
42
|
+
* mechanism, `AIDecisionParams.override`, and runs with failover off ({@link PinnedDecisionRunner})
|
|
43
|
+
* unless the cell sets `failover: true`. The model that answered is recorded; a pinned run answered
|
|
44
|
+
* by another model or vendor is flagged, and when failover was off it is an `Error`, not a data point.
|
|
45
|
+
*
|
|
46
|
+
* **Sampling.** `temperature` and `seed` are recorded but do not reach the model: the decision path
|
|
47
|
+
* has no parameter for them (see {@link SAMPLING_NOT_APPLIED}).
|
|
48
|
+
*
|
|
49
|
+
* **Agent discovery.** A test whose `Configuration.decision` is `agent-discovery` asks production's
|
|
50
|
+
* discovery decision instead (plan Task 3.1): the options come from `BuildDecisionDiscoveryOptionSet`
|
|
51
|
+
* over the agents the run's user may run, with the real semantic search, and the questions from
|
|
52
|
+
* `BuildDecisionDiscoveryQuestions`, both from `@memberjunction/ai-agents`, the code `BaseAgent`
|
|
53
|
+
* runs. Production gives up after {@link DECISION_DISCOVERY_TIMEOUT_MS}, counted from building the
|
|
54
|
+
* options, so the driver times the same span and records an answer that came later as not injected.
|
|
55
|
+
* The call itself runs to the end, so the late answer is still recorded. A `semantic-search`
|
|
56
|
+
* baseline cell makes no decision call: it records what `Find Candidate Agents` would have listed
|
|
57
|
+
* first.
|
|
58
|
+
*
|
|
59
|
+
* **Never throws.** A bad test, a missing prompt and a failed decision come back as an `Error` run
|
|
60
|
+
* with the reason. A point or request with nothing to decide is `Skipped`: production makes no call there.
|
|
61
|
+
*/
|
|
62
|
+
let DecisionEvalDriver = class DecisionEvalDriver extends BaseTestDriver {
|
|
63
|
+
async Execute(context) {
|
|
64
|
+
const startedAt = Date.now();
|
|
65
|
+
let test = null;
|
|
66
|
+
try {
|
|
67
|
+
if (ReadDecisionEvalKind(context.test) === 'agent-discovery') {
|
|
68
|
+
const discovery = ParseDiscoveryEvalTest(context.test);
|
|
69
|
+
test = discovery;
|
|
70
|
+
return await this.evaluateDiscoveryTest(discovery, context, startedAt);
|
|
71
|
+
}
|
|
72
|
+
const routing = ParseDecisionEvalTest(context.test);
|
|
73
|
+
test = routing;
|
|
74
|
+
return await this.evaluateTest(routing, context, startedAt);
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
78
|
+
this.logToTestRun(context, 'error', `Decision evaluation failed: ${message}`);
|
|
79
|
+
return this.errorResult(message, test, null, [], startedAt);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
async Validate(test) {
|
|
83
|
+
const base = await super.Validate(test);
|
|
84
|
+
if (!base.valid) {
|
|
85
|
+
return base;
|
|
86
|
+
}
|
|
87
|
+
try {
|
|
88
|
+
if (ReadDecisionEvalKind(test) === 'agent-discovery') {
|
|
89
|
+
ParseDiscoveryEvalTest(test);
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
ParseDecisionEvalTest(test);
|
|
93
|
+
}
|
|
94
|
+
return base;
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
return {
|
|
98
|
+
valid: false,
|
|
99
|
+
errors: [{ category: 'configuration', message: error instanceof Error ? error.message : String(error), field: 'Configuration' }],
|
|
100
|
+
warnings: base.warnings
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Loads what one run needs: `AIEngine`, the decision prompt by name, the agent catalog and the
|
|
106
|
+
* conversation manager. Throws when the prompt is missing. Overridable, so a test can run the
|
|
107
|
+
* driver without an engine.
|
|
108
|
+
*/
|
|
109
|
+
async LoadEnvironment(config, context) {
|
|
110
|
+
await AIEngine.Instance.Config(false, context.contextUser);
|
|
111
|
+
const prompt = this.findDecisionPrompt(config.promptName ?? DEFAULT_DECISION_PROMPT_NAME);
|
|
112
|
+
const agents = AIEngine.Instance.Agents;
|
|
113
|
+
const manager = agents.find(a => a.Name?.trim().toLowerCase() === CONVERSATION_MANAGER_NAME.toLowerCase());
|
|
114
|
+
return {
|
|
115
|
+
Prompt: prompt,
|
|
116
|
+
Catalog: {
|
|
117
|
+
FindAgent: (agentId) => agents.find(a => UUIDsEqual(a.ID, agentId)),
|
|
118
|
+
ConversationManager: manager ?? null
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Loads what one discovery run needs, the way production's discovery loads it: `AIEngine`, the
|
|
124
|
+
* decision prompt by name (not for a baseline cell, which makes no call), the conversation
|
|
125
|
+
* manager, the agents the run's user may run, the prompt's option cap, and the semantic search
|
|
126
|
+
* when the provider can run it. Throws when the prompt or the conversation manager is missing.
|
|
127
|
+
* Overridable, so a test can run the driver without an engine or a provider.
|
|
128
|
+
*/
|
|
129
|
+
async LoadDiscoveryEnvironment(config, context) {
|
|
130
|
+
await AIEngine.Instance.Config(false, context.contextUser);
|
|
131
|
+
const promptName = config.promptName ?? DEFAULT_DECISION_PROMPT_NAME;
|
|
132
|
+
const agents = AIEngine.Instance.Agents;
|
|
133
|
+
const manager = agents.find(a => a.Name?.trim().toLowerCase() === CONVERSATION_MANAGER_NAME.toLowerCase());
|
|
134
|
+
if (!manager) {
|
|
135
|
+
throw new Error(`The conversation manager '${CONVERSATION_MANAGER_NAME}' is not in AIEngine metadata, and discovery runs as it`);
|
|
136
|
+
}
|
|
137
|
+
const provider = this.Provider;
|
|
138
|
+
const searcher = CanSearchEntities(provider) ? provider : undefined;
|
|
139
|
+
return {
|
|
140
|
+
Prompt: config.baseline ? null : this.findDecisionPrompt(promptName),
|
|
141
|
+
ConversationManager: manager,
|
|
142
|
+
AllAgents: agents,
|
|
143
|
+
RunnableAgents: await DecisionDiscoveryRunnableAgents(agents, context.contextUser),
|
|
144
|
+
DeclaredCap: DecisionPromptOptionCap(AIEngine.Instance, promptName),
|
|
145
|
+
SearchFor: searcher ? (request) => DecisionDiscoveryAgentSearch(searcher, request, context.contextUser) : undefined
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* The runner for one call: failover as the prompt configures it, or none. Overridable, so a
|
|
150
|
+
* test can supply a fake runner.
|
|
151
|
+
*
|
|
152
|
+
* @param failoverAllowed Whether the runner may fail over.
|
|
153
|
+
*/
|
|
154
|
+
CreateRunner(failoverAllowed) {
|
|
155
|
+
return failoverAllowed ? new AIDecisionRunner() : new PinnedDecisionRunner();
|
|
156
|
+
}
|
|
157
|
+
/** The decision prompt by name, from the loaded `AIEngine`. Throws when it is missing. */
|
|
158
|
+
findDecisionPrompt(promptName) {
|
|
159
|
+
const prompt = AIEngine.Instance.Prompts.find(p => p.Name?.trim().toLowerCase() === promptName.trim().toLowerCase());
|
|
160
|
+
if (!prompt) {
|
|
161
|
+
throw new Error(`Decision prompt '${promptName}' not found in AIEngine metadata`);
|
|
162
|
+
}
|
|
163
|
+
return prompt;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Maps the request to production's state, then runs the `semantic-search` baseline, or builds
|
|
167
|
+
* the options and runs the one decision, and scores it. A request production would ask nothing
|
|
168
|
+
* about is Skipped, including one with fewer than {@link DECISION_DISCOVERY_MIN_OPTIONS} options;
|
|
169
|
+
* options that cannot be built are an Error. Every corpus request is a conversation's opening
|
|
170
|
+
* request, the only turn production's discovery asks about.
|
|
171
|
+
*/
|
|
172
|
+
async evaluateDiscoveryTest(test, context, startedAt) {
|
|
173
|
+
const environment = await this.LoadDiscoveryEnvironment(test.Config, context);
|
|
174
|
+
const request = DiscoveryDecisionState(test.Input.request);
|
|
175
|
+
const skip = DiscoverySkipReason(request, environment);
|
|
176
|
+
if (skip) {
|
|
177
|
+
return { ...this.errorResult(skip, test, null, [], startedAt), status: 'Skipped' };
|
|
178
|
+
}
|
|
179
|
+
if (test.Config.baseline) {
|
|
180
|
+
const baseline = await this.runSemanticSearchBaseline(test, environment, request);
|
|
181
|
+
return this.completedResult(test, baseline, await this.runOracles(test, baseline, undefined, context), undefined, context, startedAt);
|
|
182
|
+
}
|
|
183
|
+
// Production's timeout covers the options (and their semantic search) as well as the call.
|
|
184
|
+
const discoveryStarted = Date.now();
|
|
185
|
+
const optionSet = await BuildDecisionDiscoveryOptionSet({
|
|
186
|
+
Agents: environment.RunnableAgents,
|
|
187
|
+
RunningAgentID: environment.ConversationManager.ID,
|
|
188
|
+
DeclaredCap: environment.DeclaredCap,
|
|
189
|
+
Search: environment.SearchFor?.(request)
|
|
190
|
+
});
|
|
191
|
+
if (optionSet.Error) {
|
|
192
|
+
throw new Error(`The options could not be built: ${optionSet.Error}`);
|
|
193
|
+
}
|
|
194
|
+
if (optionSet.Options.length < DECISION_DISCOVERY_MIN_OPTIONS) {
|
|
195
|
+
const reason = `There are ${optionSet.Options.length} agents to choose from, fewer than the ${DECISION_DISCOVERY_MIN_OPTIONS} production's `
|
|
196
|
+
+ 'discovery needs, so production asks nothing.';
|
|
197
|
+
return { ...this.errorResult(reason, test, null, [], startedAt), status: 'Skipped' };
|
|
198
|
+
}
|
|
199
|
+
this.logToTestRun(context, 'info', `Asking agent discovery with '${environment.Prompt?.Name}' over ${optionSet.Options.length} option(s)`);
|
|
200
|
+
const call = await this.callDiscoveryDecision(test.Config, request, optionSet, environment.Prompt, context, discoveryStarted);
|
|
201
|
+
const actual = BuildDiscoveryEvalActualOutput(test.Config, environment.Prompt?.Name ?? DEFAULT_DECISION_PROMPT_NAME, call, test.Expected);
|
|
202
|
+
return this.completedResult(test, actual, await this.runOracles(test, actual, call.Result, context), call.Result, context, startedAt);
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Builds the discovery decision's parameters and makes the one call, waiting for the prompt run to
|
|
206
|
+
* be saved. `discoveryStarted` is when building the options began, where production's timeout starts.
|
|
207
|
+
*/
|
|
208
|
+
async callDiscoveryDecision(config, request, optionSet, prompt, context, discoveryStarted) {
|
|
209
|
+
if (!prompt) {
|
|
210
|
+
throw new Error('No decision prompt was loaded for a decision cell');
|
|
211
|
+
}
|
|
212
|
+
const params = BuildDiscoveryDecisionParams(config, request, optionSet.Options, prompt, context, this.getEffectiveTimeout(context.test));
|
|
213
|
+
const runner = this.CreateRunner(IsFailoverAllowed(config));
|
|
214
|
+
const callStarted = Date.now();
|
|
215
|
+
const result = await runner.ExecuteDecision(params);
|
|
216
|
+
const callEnded = Date.now();
|
|
217
|
+
// Prompt-run persistence is fire-and-forget: settle it before the run links to the row.
|
|
218
|
+
await runner.WaitForPendingPromptRunSaves();
|
|
219
|
+
return { OptionSet: optionSet, Result: result, LatencyMs: callEnded - callStarted, DiscoveryLatencyMs: callEnded - discoveryStarted };
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* The `semantic-search` baseline: no decision call. The search `Find Candidate Agents` runs, over
|
|
223
|
+
* the request, read as the action reads it. Throws when the provider cannot run the search.
|
|
224
|
+
*/
|
|
225
|
+
async runSemanticSearchBaseline(test, environment, request) {
|
|
226
|
+
if (!environment.SearchFor) {
|
|
227
|
+
throw new Error('The provider cannot run the semantic search the baseline measures');
|
|
228
|
+
}
|
|
229
|
+
const candidates = DecisionDiscoveryCatalog(environment.RunnableAgents, environment.ConversationManager.ID);
|
|
230
|
+
const searchStarted = Date.now();
|
|
231
|
+
const results = await environment.SearchFor(request)(FIND_CANDIDATE_AGENTS_TOP_K);
|
|
232
|
+
const latencyMs = Date.now() - searchStarted;
|
|
233
|
+
return BuildBaselineEvalActualOutput(test.Config, RankSemanticSearchBaseline(results, candidates), latencyMs, test.Expected, candidates);
|
|
234
|
+
}
|
|
235
|
+
/** Maps the point, runs the one decision, and scores it. */
|
|
236
|
+
async evaluateTest(test, context, startedAt) {
|
|
237
|
+
const environment = await this.LoadEnvironment(test.Config, context);
|
|
238
|
+
const input = MapPointToRoutingInput(test.Input.point, environment.Catalog);
|
|
239
|
+
if (!CanAskRoutingDecision(input)) {
|
|
240
|
+
// Production asks nothing for this point, so there is no decision to measure: Skipped,
|
|
241
|
+
// not Error, which would read as a failure of the model under test
|
|
242
|
+
return {
|
|
243
|
+
...this.errorResult('Nothing to decide: the previous agent is not among the history\'s agents, '
|
|
244
|
+
+ 'or the agent Choice would have fewer than two options. Production makes no call here.', test, null, [], startedAt),
|
|
245
|
+
status: 'Skipped'
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
this.logToTestRun(context, 'info', `Deciding point ${test.Input.point.id} with '${environment.Prompt.Name}' (${test.Config.stateLayout} state)`);
|
|
249
|
+
const call = await this.callDecision(test.Config, input, environment.Prompt, context);
|
|
250
|
+
const actual = BuildDecisionEvalActualOutput(test.Config, environment.Prompt.Name ?? DEFAULT_DECISION_PROMPT_NAME, call);
|
|
251
|
+
const oracleResults = await this.runOracles(test, actual, call.Result, context);
|
|
252
|
+
return this.completedResult(test, actual, oracleResults, call.Result, context, startedAt);
|
|
253
|
+
}
|
|
254
|
+
/** Builds the parameters and makes the one call, waiting for the prompt run to be saved. */
|
|
255
|
+
async callDecision(config, input, prompt, context) {
|
|
256
|
+
const params = BuildDecisionEvalParams(config, input, prompt, context, this.getEffectiveTimeout(context.test));
|
|
257
|
+
const runner = this.CreateRunner(IsFailoverAllowed(config));
|
|
258
|
+
const callStarted = Date.now();
|
|
259
|
+
const result = await runner.ExecuteDecision(params);
|
|
260
|
+
const latencyMs = Date.now() - callStarted;
|
|
261
|
+
// Prompt-run persistence is fire-and-forget: settle it before the run links to the row.
|
|
262
|
+
await runner.WaitForPendingPromptRunSaves();
|
|
263
|
+
return { Input: input, Result: result, LatencyMs: latencyMs };
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Runs the configured oracles. A missing oracle is a failed result naming it, never a skip:
|
|
267
|
+
* a weighted check that cannot run is a failure of the test, not an absence of one.
|
|
268
|
+
*/
|
|
269
|
+
async runOracles(test, actual, result, context) {
|
|
270
|
+
const results = [];
|
|
271
|
+
const oracles = OraclesWithNamedRubric(test.Config.oracles, {
|
|
272
|
+
runRubricId: context.options.rubricId,
|
|
273
|
+
runVersionId: context.options.rubricVersionId,
|
|
274
|
+
testRubricId: context.test.RubricID,
|
|
275
|
+
});
|
|
276
|
+
for (const spec of oracles) {
|
|
277
|
+
const oracle = context.oracleRegistry.get(spec.type);
|
|
278
|
+
if (!oracle) {
|
|
279
|
+
results.push({ oracleType: spec.type, passed: false, score: 0, message: `Oracle '${spec.type}' is not registered — its weight cannot be scored` });
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
const oracleInput = {
|
|
283
|
+
test: context.test,
|
|
284
|
+
testRunId: context.testRun.ID,
|
|
285
|
+
expectedOutput: test.Expected,
|
|
286
|
+
actualOutput: actual,
|
|
287
|
+
targetEntity: result?.promptRun,
|
|
288
|
+
contextUser: context.contextUser
|
|
289
|
+
};
|
|
290
|
+
try {
|
|
291
|
+
results.push(await oracle.evaluate(oracleInput, spec.config ?? {}));
|
|
292
|
+
}
|
|
293
|
+
catch (error) {
|
|
294
|
+
results.push({ oracleType: spec.type, passed: false, score: 0, message: `Oracle execution failed: ${error instanceof Error ? error.message : String(error)}` });
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
return results;
|
|
298
|
+
}
|
|
299
|
+
/** The result of a run that reached the model (or, for a baseline, the search). */
|
|
300
|
+
completedResult(test, actual, oracleResults, result, context, startedAt) {
|
|
301
|
+
const problem = this.runProblem(actual);
|
|
302
|
+
if (problem) {
|
|
303
|
+
this.logToTestRun(context, 'warn', problem);
|
|
304
|
+
return this.errorResult(problem, test, actual, oracleResults, startedAt, result);
|
|
305
|
+
}
|
|
306
|
+
const gating = oracleResults.filter(r => !r.advisory);
|
|
307
|
+
const passed = gating.filter(r => r.passed).length;
|
|
308
|
+
return {
|
|
309
|
+
...this.targetLink(result),
|
|
310
|
+
status: gating.length === 0 ? 'Skipped' : gating.every(r => r.passed) ? 'Passed' : 'Failed',
|
|
311
|
+
score: gating.length === 0 ? 0 : this.calculateScore(gating, oracleWeights(test.Config)),
|
|
312
|
+
oracleResults,
|
|
313
|
+
passedChecks: passed,
|
|
314
|
+
failedChecks: gating.length - passed,
|
|
315
|
+
totalChecks: gating.length,
|
|
316
|
+
skippedChecks: oracleResults.length - gating.length,
|
|
317
|
+
inputData: test.Input,
|
|
318
|
+
expectedOutput: test.Expected,
|
|
319
|
+
actualOutput: actual,
|
|
320
|
+
totalCost: actual.CostUSD ?? 0,
|
|
321
|
+
durationMs: Date.now() - startedAt
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
/** Why a run that reached the model is still not an observation, or null. A baseline run has no model. */
|
|
325
|
+
runProblem(actual) {
|
|
326
|
+
if (actual.Error) {
|
|
327
|
+
return `The decision failed: ${actual.Error}`;
|
|
328
|
+
}
|
|
329
|
+
const model = actual.Model;
|
|
330
|
+
if (model && model.FailedOver && !model.FailoverAllowed) {
|
|
331
|
+
return `Answered by ${model.AnsweredModelName ?? model.AnsweredModelId ?? 'another model'}`
|
|
332
|
+
+ `${model.AnsweredVendorName ? ` via ${model.AnsweredVendorName}` : ''}, not the pinned `
|
|
333
|
+
+ `${model.PinnedModelId ? `model ${model.PinnedModelId}` : ''}`
|
|
334
|
+
+ `${model.PinnedVendorId ? ` vendor ${model.PinnedVendorId}` : ''}, with failover off`;
|
|
335
|
+
}
|
|
336
|
+
return null;
|
|
337
|
+
}
|
|
338
|
+
/** A run that produced no observation: status `Error`, with the reason. */
|
|
339
|
+
errorResult(message, test, actual, oracleResults, startedAt, result) {
|
|
340
|
+
return {
|
|
341
|
+
...this.targetLink(result),
|
|
342
|
+
status: 'Error',
|
|
343
|
+
score: 0,
|
|
344
|
+
oracleResults,
|
|
345
|
+
passedChecks: 0,
|
|
346
|
+
failedChecks: 0,
|
|
347
|
+
totalChecks: 0,
|
|
348
|
+
skippedChecks: oracleResults.length,
|
|
349
|
+
inputData: test?.Input,
|
|
350
|
+
expectedOutput: test?.Expected,
|
|
351
|
+
actualOutput: actual ?? undefined,
|
|
352
|
+
totalCost: actual?.CostUSD ?? 0,
|
|
353
|
+
durationMs: Date.now() - startedAt,
|
|
354
|
+
errorMessage: message
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
/** Links the prompt run as the test run's target, when there is one. */
|
|
358
|
+
targetLink(result) {
|
|
359
|
+
return {
|
|
360
|
+
targetType: 'AI Prompt',
|
|
361
|
+
targetLogEntityId: this.Provider?.EntityByName('MJ: AI Prompt Runs')?.ID,
|
|
362
|
+
targetLogId: result?.promptRun?.ID ?? ''
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
DecisionEvalDriver = __decorate([
|
|
367
|
+
RegisterClass(BaseTestDriver, 'DecisionEvalDriver')
|
|
368
|
+
], DecisionEvalDriver);
|
|
369
|
+
export { DecisionEvalDriver };
|
|
370
|
+
/**
|
|
371
|
+
* Validates a test's `Configuration`, `InputDefinition` and `ExpectedOutcomes`. Throws naming the
|
|
372
|
+
* column and the first problem.
|
|
373
|
+
*
|
|
374
|
+
* @param test The test.
|
|
375
|
+
*/
|
|
376
|
+
export function ParseDecisionEvalTest(test) {
|
|
377
|
+
return {
|
|
378
|
+
Config: parseColumn('Configuration', test.Configuration, DecisionEvalConfigSchema),
|
|
379
|
+
Input: parseColumn('InputDefinition', test.InputDefinition, DecisionEvalInputSchema),
|
|
380
|
+
Expected: parseColumn('ExpectedOutcomes', test.ExpectedOutcomes, DecisionEvalExpectedSchema)
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Whether a cell's runner may fail over: as the cell says, and otherwise only when it pins nothing.
|
|
385
|
+
*
|
|
386
|
+
* @param config The cell's configuration.
|
|
387
|
+
*/
|
|
388
|
+
export function IsFailoverAllowed(config) {
|
|
389
|
+
return config.failover ?? !(config.modelId || config.vendorId);
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* The runner's parameters for one call: the prompt, the context user, the cell's state layout, the
|
|
393
|
+
* shared questions, a time bound, and the cell's pinning as `override`.
|
|
394
|
+
*
|
|
395
|
+
* @param config The cell's configuration.
|
|
396
|
+
* @param input The routing input.
|
|
397
|
+
* @param prompt The decision prompt.
|
|
398
|
+
* @param context The run's context, for its user.
|
|
399
|
+
* @param timeoutMS Bounds the model call.
|
|
400
|
+
*/
|
|
401
|
+
export function BuildDecisionEvalParams(config, input, prompt, context, timeoutMS) {
|
|
402
|
+
const params = new AIDecisionParams();
|
|
403
|
+
params.prompt = prompt;
|
|
404
|
+
// Explicit, never the provider's CurrentUser, which is null on the CLI (#3251).
|
|
405
|
+
params.contextUser = context.contextUser;
|
|
406
|
+
params.State = config.stateLayout === 'structured' ? BuildRoutingStateStructured(input) : BuildRoutingState(input);
|
|
407
|
+
params.Questions = BuildRoutingQuestions(input);
|
|
408
|
+
params.timeoutMS = timeoutMS;
|
|
409
|
+
if (config.modelId || config.vendorId) {
|
|
410
|
+
params.override = { modelId: config.modelId ?? undefined, vendorId: config.vendorId ?? undefined };
|
|
411
|
+
}
|
|
412
|
+
return params;
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* What a run records as its `ActualOutput`: the summarized answers, the `continues` probability,
|
|
416
|
+
* the agent Choice, production's verdict and the policy it was reached under, the model record, the
|
|
417
|
+
* sampling record, the latency, the prompt run and its cost, and the error when there are no answers.
|
|
418
|
+
*
|
|
419
|
+
* The verdict is production's: the answers are read by `InterpretRoutingAnswers` with the model
|
|
420
|
+
* that answered and the model behind it, as the chat passes them from `RunDecision`, so the thread
|
|
421
|
+
* Likelihood is calibrated exactly when production would calibrate it.
|
|
422
|
+
*
|
|
423
|
+
* @param config The cell's configuration.
|
|
424
|
+
* @param promptName The decision prompt's name.
|
|
425
|
+
* @param call The call and its result.
|
|
426
|
+
*/
|
|
427
|
+
export function BuildDecisionEvalActualOutput(config, promptName, call) {
|
|
428
|
+
const { Result: result } = call;
|
|
429
|
+
const answers = result.success ? result.Answers : {};
|
|
430
|
+
const continues = answers[ROUTING_CONTINUES_QUESTION];
|
|
431
|
+
const route = answers[ROUTING_ROUTE_QUESTION];
|
|
432
|
+
const answeredBy = answeringModelOf(result);
|
|
433
|
+
return {
|
|
434
|
+
Decision: config.decision,
|
|
435
|
+
StateLayout: config.stateLayout,
|
|
436
|
+
PromptName: promptName,
|
|
437
|
+
Answers: SummarizeDecisionEvalAnswers(answers),
|
|
438
|
+
ContinuesProbability: continues?.Kind === 'Likelihood' ? continues.Probability : null,
|
|
439
|
+
Route: route?.Kind === 'Choice' ? { Value: route.Value, Confidence: route.Confidence } : null,
|
|
440
|
+
RoutingVerdict: result.success ? InterpretRoutingAnswers(call.Input, { Success: true, Answers: answers, ...answeredBy }).Verdict : null,
|
|
441
|
+
RoutingPolicy: result.success ? routingPolicyFor(answeredBy) : null,
|
|
442
|
+
Model: modelRecord(config, result),
|
|
443
|
+
Sampling: samplingRecord(config),
|
|
444
|
+
LatencyMs: call.LatencyMs,
|
|
445
|
+
PromptRunId: result.promptRun?.ID ?? null,
|
|
446
|
+
CostUSD: result.promptRun?.TotalCost ?? result.promptRun?.Cost ?? result.cost ?? null,
|
|
447
|
+
Error: result.success ? null : (result.errorMessage || 'the decision failed with no message')
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* The model that answered a decision, as `RunDecision` reports it to the chat: the MJ decision
|
|
452
|
+
* model (`modelInfo.modelName`) and the exact model behind it (`DecisionResult.ResolvedModel`).
|
|
453
|
+
*
|
|
454
|
+
* @param result The runner's result.
|
|
455
|
+
*/
|
|
456
|
+
function answeringModelOf(result) {
|
|
457
|
+
return { ModelName: result.modelInfo?.modelName, ResolvedModel: result.DecisionResult?.ResolvedModel };
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* The routing policy production applies to an answer from this model: the confidence bar, the
|
|
461
|
+
* timeout, and the thread Likelihood's calibration for this exact model, or null when it has none.
|
|
462
|
+
*
|
|
463
|
+
* @param answeredBy The model that answered.
|
|
464
|
+
*/
|
|
465
|
+
function routingPolicyFor(answeredBy) {
|
|
466
|
+
const calibration = FindDecisionCalibration(ROUTING_CONTINUES_CALIBRATION, answeredBy);
|
|
467
|
+
return {
|
|
468
|
+
MinConfidence: DECISION_ROUTING_MIN_CONFIDENCE,
|
|
469
|
+
TimeoutMs: DECISION_ROUTING_TIMEOUT_MS,
|
|
470
|
+
Calibration: calibration ? { A: calibration.A, B: calibration.B } : null
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* Summarizes answers for the record: a Likelihood's probability; a Choice's or Score's value and
|
|
475
|
+
* confidence, keeping its full distribution.
|
|
476
|
+
*
|
|
477
|
+
* @param answers The answers by question key.
|
|
478
|
+
*/
|
|
479
|
+
export function SummarizeDecisionEvalAnswers(answers) {
|
|
480
|
+
const summary = {};
|
|
481
|
+
for (const [key, answer] of Object.entries(answers)) {
|
|
482
|
+
summary[key] = answer.Kind === 'Likelihood'
|
|
483
|
+
? { Kind: 'Likelihood', Probability: answer.Probability }
|
|
484
|
+
: { Kind: answer.Kind, Value: answer.Value, Confidence: answer.Confidence, Probabilities: { ...answer.Probabilities } };
|
|
485
|
+
}
|
|
486
|
+
return summary;
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Which decision a test asks, from its `Configuration`. Throws naming the column when the
|
|
490
|
+
* configuration is missing, is not JSON, or names no known decision.
|
|
491
|
+
*
|
|
492
|
+
* @param test The test.
|
|
493
|
+
*/
|
|
494
|
+
export function ReadDecisionEvalKind(test) {
|
|
495
|
+
return parseColumn('Configuration', test.Configuration, DecisionEvalKindSchema).decision;
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* Validates a discovery test's `Configuration`, `InputDefinition` and `ExpectedOutcomes`. Throws
|
|
499
|
+
* naming the column and the first problem.
|
|
500
|
+
*
|
|
501
|
+
* @param test The test.
|
|
502
|
+
*/
|
|
503
|
+
export function ParseDiscoveryEvalTest(test) {
|
|
504
|
+
return {
|
|
505
|
+
Config: parseColumn('Configuration', test.Configuration, DiscoveryEvalConfigSchema),
|
|
506
|
+
Input: parseColumn('InputDefinition', test.InputDefinition, DiscoveryEvalInputSchema),
|
|
507
|
+
Expected: parseColumn('ExpectedOutcomes', test.ExpectedOutcomes, DiscoveryEvalExpectedSchema)
|
|
508
|
+
};
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* Why production's discovery would ask nothing about a request, or null when it would ask:
|
|
512
|
+
* the request is empty, or it @mentions an agent other than the conversation manager
|
|
513
|
+
* (`MentionsAgent`, as `BaseAgent` checks it).
|
|
514
|
+
*
|
|
515
|
+
* @param state The request as production reads it (`DiscoveryDecisionState`).
|
|
516
|
+
* @param environment The catalog and the conversation manager.
|
|
517
|
+
*/
|
|
518
|
+
export function DiscoverySkipReason(state, environment) {
|
|
519
|
+
if (!state) {
|
|
520
|
+
return 'The request is empty, so production asks nothing.';
|
|
521
|
+
}
|
|
522
|
+
if (MentionsAgent(state, environment.AllAgents, environment.ConversationManager.ID)) {
|
|
523
|
+
return 'The request @mentions an agent, so production asks nothing: the user has already chosen.';
|
|
524
|
+
}
|
|
525
|
+
return null;
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* The runner's parameters for one discovery call: the prompt, the context user, the request as the
|
|
529
|
+
* state, production's questions over the options, a time bound, and the cell's pinning as
|
|
530
|
+
* `override`. The prompt run is not attributed to the conversation manager (production sets
|
|
531
|
+
* `agentId`, which only labels the row), so eval runs stay out of its analytics.
|
|
532
|
+
*
|
|
533
|
+
* @param config The cell's configuration.
|
|
534
|
+
* @param state The request as production reads it (`DiscoveryDecisionState`).
|
|
535
|
+
* @param options The Choice's options (`BuildDecisionDiscoveryOptionSet`).
|
|
536
|
+
* @param prompt The decision prompt.
|
|
537
|
+
* @param context The run's context, for its user.
|
|
538
|
+
* @param timeoutMS Bounds the model call.
|
|
539
|
+
*/
|
|
540
|
+
export function BuildDiscoveryDecisionParams(config, state, options, prompt, context, timeoutMS) {
|
|
541
|
+
const params = new AIDecisionParams();
|
|
542
|
+
params.prompt = prompt;
|
|
543
|
+
// Explicit, never the provider's CurrentUser, which is null on the CLI (#3251).
|
|
544
|
+
params.contextUser = context.contextUser;
|
|
545
|
+
params.State = state;
|
|
546
|
+
params.Questions = BuildDecisionDiscoveryQuestions(options);
|
|
547
|
+
params.timeoutMS = timeoutMS;
|
|
548
|
+
if (config.modelId || config.vendorId) {
|
|
549
|
+
params.override = { modelId: config.modelId ?? undefined, vendorId: config.vendorId ?? undefined };
|
|
550
|
+
}
|
|
551
|
+
return params;
|
|
552
|
+
}
|
|
553
|
+
/**
|
|
554
|
+
* What a discovery decision run records as its `ActualOutput`: the options, the summarized answers,
|
|
555
|
+
* the chosen agent with its raw confidence, the raw `anyApplies` probability, production's own
|
|
556
|
+
* verdict (`DecisionDiscoveryFromResult`: calibrated for the answering model, at production's
|
|
557
|
+
* threshold), whether the labelled agent was an option, the model and sampling records, the call's
|
|
558
|
+
* latency and the whole discovery's, the prompt run and its cost, and the error when there are no
|
|
559
|
+
* answers.
|
|
560
|
+
*
|
|
561
|
+
* A discovery that took longer than {@link DECISION_DISCOVERY_TIMEOUT_MS} is recorded as not
|
|
562
|
+
* injected, with a "timed out" reason, whatever its answer: production would have given up by then.
|
|
563
|
+
*
|
|
564
|
+
* @param config The cell's configuration.
|
|
565
|
+
* @param promptName The decision prompt's name.
|
|
566
|
+
* @param call The call, its options and its result.
|
|
567
|
+
* @param expected The request's label.
|
|
568
|
+
*/
|
|
569
|
+
export function BuildDiscoveryEvalActualOutput(config, promptName, call, expected) {
|
|
570
|
+
const { Result: result, OptionSet: optionSet } = call;
|
|
571
|
+
const answers = result.success ? result.Answers : {};
|
|
572
|
+
// The raw answers are recorded, because calibration is fitted on them; whether production would
|
|
573
|
+
// inject, and why not, come from production's own calibrated path.
|
|
574
|
+
const verdict = result.success ? JudgeDecisionDiscovery(answers, optionSet.Options, DECISION_DISCOVERY_MIN_CONFIDENCE) : null;
|
|
575
|
+
const answer = verdict?.Answer;
|
|
576
|
+
const production = answer ? DecisionDiscoveryFromResult(result, optionSet.Options, DECISION_DISCOVERY_MIN_CONFIDENCE) : null;
|
|
577
|
+
const onTime = call.DiscoveryLatencyMs <= DECISION_DISCOVERY_TIMEOUT_MS;
|
|
578
|
+
return {
|
|
579
|
+
Decision: 'agent-discovery',
|
|
580
|
+
Arm: 'decision',
|
|
581
|
+
PromptName: promptName,
|
|
582
|
+
Options: optionsRecord(optionSet),
|
|
583
|
+
LabelledAgentOffered: expected.label === 'agent' ? optionSet.Options.some(o => UUIDsEqual(o.ID, expected.agentId)) : null,
|
|
584
|
+
Answers: SummarizeDecisionEvalAnswers(answers),
|
|
585
|
+
ChosenAgentId: answer?.Agent.ID ?? null,
|
|
586
|
+
ChosenAgentName: answer?.Agent.Name ?? null,
|
|
587
|
+
Confidence: answer?.Confidence ?? null,
|
|
588
|
+
AnyApplies: answer?.AnyApplies ?? null,
|
|
589
|
+
WouldInject: production ? production.Injected && onTime : null,
|
|
590
|
+
MinConfidence: DECISION_DISCOVERY_MIN_CONFIDENCE,
|
|
591
|
+
VerdictReason: production && !onTime
|
|
592
|
+
? DiscoveryTimedOutReason(call.DiscoveryLatencyMs)
|
|
593
|
+
: production ? production.Reason ?? null : verdict?.Reason ?? null,
|
|
594
|
+
Baseline: null,
|
|
595
|
+
Model: modelRecord(config, result),
|
|
596
|
+
Sampling: samplingRecord(config),
|
|
597
|
+
LatencyMs: call.LatencyMs,
|
|
598
|
+
DiscoveryLatencyMs: call.DiscoveryLatencyMs,
|
|
599
|
+
WithinProductionTimeout: result.success ? onTime : null,
|
|
600
|
+
PromptRunId: result.promptRun?.ID ?? null,
|
|
601
|
+
CostUSD: result.promptRun?.TotalCost ?? result.promptRun?.Cost ?? result.cost ?? null,
|
|
602
|
+
Error: result.success ? null : (result.errorMessage || 'the decision failed with no message')
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
/**
|
|
606
|
+
* What a `semantic-search` baseline run records as its `ActualOutput`: the ranking, the action's
|
|
607
|
+
* first row as the chosen agent, and whether it lists anything at all as `WouldInject`. It has no
|
|
608
|
+
* answers, no model and no cost.
|
|
609
|
+
*
|
|
610
|
+
* @param config The cell's configuration.
|
|
611
|
+
* @param baseline The ranking (`RankSemanticSearchBaseline`).
|
|
612
|
+
* @param latencyMs Wall-clock time of the search.
|
|
613
|
+
* @param expected The request's label.
|
|
614
|
+
* @param candidates The agents the action may list.
|
|
615
|
+
*/
|
|
616
|
+
export function BuildBaselineEvalActualOutput(config, baseline, latencyMs, expected, candidates) {
|
|
617
|
+
return {
|
|
618
|
+
Decision: 'agent-discovery',
|
|
619
|
+
Arm: 'semantic-search',
|
|
620
|
+
PromptName: null,
|
|
621
|
+
Options: null,
|
|
622
|
+
LabelledAgentOffered: expected.label === 'agent' ? candidates.some(c => UUIDsEqual(c.ID, expected.agentId)) : null,
|
|
623
|
+
Answers: {},
|
|
624
|
+
ChosenAgentId: baseline.TopMatch?.AgentId ?? null,
|
|
625
|
+
ChosenAgentName: baseline.TopMatch?.AgentName ?? null,
|
|
626
|
+
Confidence: null,
|
|
627
|
+
AnyApplies: null,
|
|
628
|
+
WouldInject: baseline.TopMatch !== null,
|
|
629
|
+
MinConfidence: null,
|
|
630
|
+
VerdictReason: baseline.TopMatch ? null : `no candidate reaches the similarity floor of ${baseline.Floor}`,
|
|
631
|
+
Baseline: baseline,
|
|
632
|
+
Model: null,
|
|
633
|
+
Sampling: samplingRecord(config),
|
|
634
|
+
LatencyMs: latencyMs,
|
|
635
|
+
DiscoveryLatencyMs: null,
|
|
636
|
+
WithinProductionTimeout: null,
|
|
637
|
+
PromptRunId: null,
|
|
638
|
+
CostUSD: null,
|
|
639
|
+
Error: null
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
/**
|
|
643
|
+
* Why a discovery that answered too late injects nothing: production had given up.
|
|
644
|
+
*
|
|
645
|
+
* @param discoveryLatencyMs How long the discovery took, options and call.
|
|
646
|
+
*/
|
|
647
|
+
export function DiscoveryTimedOutReason(discoveryLatencyMs) {
|
|
648
|
+
return `timed out: the discovery took ${Math.round(discoveryLatencyMs)} ms, past production's ${DECISION_DISCOVERY_TIMEOUT_MS} ms limit, `
|
|
649
|
+
+ 'so production would have given up and injected nothing';
|
|
650
|
+
}
|
|
651
|
+
/** How the options were reached, for the record. */
|
|
652
|
+
function optionsRecord(optionSet) {
|
|
653
|
+
return {
|
|
654
|
+
Count: optionSet.Options.length,
|
|
655
|
+
Limit: optionSet.OptionLimit,
|
|
656
|
+
CatalogSize: optionSet.CatalogSize,
|
|
657
|
+
WithoutDescription: optionSet.WithoutDescription.length,
|
|
658
|
+
DeclaredCap: optionSet.DeclaredOptionCap ?? null,
|
|
659
|
+
NarrowedFrom: optionSet.NarrowedFrom ?? null
|
|
660
|
+
};
|
|
661
|
+
}
|
|
662
|
+
/** Which model was pinned, which answered (or, for a failed call, was selected), and whether they match. */
|
|
663
|
+
function modelRecord(config, result) {
|
|
664
|
+
const pinnedModel = config.modelId ?? null;
|
|
665
|
+
const pinnedVendor = config.vendorId ?? null;
|
|
666
|
+
const answered = result.modelInfo;
|
|
667
|
+
const matches = !answered || (!pinnedModel && !pinnedVendor)
|
|
668
|
+
? null
|
|
669
|
+
: (!pinnedModel || UUIDsEqual(answered.modelId, pinnedModel)) && (!pinnedVendor || UUIDsEqual(answered.vendorId, pinnedVendor));
|
|
670
|
+
return {
|
|
671
|
+
PinnedModelId: pinnedModel,
|
|
672
|
+
PinnedVendorId: pinnedVendor,
|
|
673
|
+
FailoverAllowed: IsFailoverAllowed(config),
|
|
674
|
+
AnsweredModelId: answered?.modelId ?? null,
|
|
675
|
+
AnsweredModelName: answered?.modelName ?? null,
|
|
676
|
+
AnsweredVendorId: answered?.vendorId ?? null,
|
|
677
|
+
AnsweredVendorName: answered?.vendorName ?? null,
|
|
678
|
+
DriverClass: result.DriverClass ?? null,
|
|
679
|
+
ResolvedModel: result.DecisionResult?.ResolvedModel ?? null,
|
|
680
|
+
AnsweredByPinned: matches,
|
|
681
|
+
FailedOver: result.success && matches === false
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
/** The sampling the cell asked for, recorded as not applied. */
|
|
685
|
+
function samplingRecord(config) {
|
|
686
|
+
const requested = config.temperature != null || config.seed != null;
|
|
687
|
+
return {
|
|
688
|
+
RequestedTemperature: config.temperature ?? null,
|
|
689
|
+
RequestedSeed: config.seed ?? null,
|
|
690
|
+
Applied: false,
|
|
691
|
+
Note: requested ? SAMPLING_NOT_APPLIED : null
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
/** Each oracle's weight by type, defaulting to 1. */
|
|
695
|
+
function oracleWeights(config) {
|
|
696
|
+
return Object.fromEntries(config.oracles.map(o => [o.type, o.weight ?? 1]));
|
|
697
|
+
}
|
|
698
|
+
/** One JSON column, parsed and validated. */
|
|
699
|
+
function parseColumn(column, text, schema) {
|
|
700
|
+
if (!text || text.trim() === '') {
|
|
701
|
+
throw new Error(`${column} is required`);
|
|
702
|
+
}
|
|
703
|
+
let json;
|
|
704
|
+
try {
|
|
705
|
+
json = JSON.parse(text);
|
|
706
|
+
}
|
|
707
|
+
catch (error) {
|
|
708
|
+
throw new Error(`${column} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
709
|
+
}
|
|
710
|
+
const result = schema.safeParse(json);
|
|
711
|
+
if (!result.success) {
|
|
712
|
+
throw new Error(`${column}: ${DescribeZodError(result.error)}`);
|
|
713
|
+
}
|
|
714
|
+
return result.data;
|
|
715
|
+
}
|
|
716
|
+
//# sourceMappingURL=DecisionEvalDriver.js.map
|