dsh-eval 0.1.0-rc.6 → 0.3.0
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 +66 -6
- package/lib/index.js +28 -3
- package/lib/types/command.d.ts +7 -0
- package/lib/types/compare.d.ts +28 -0
- package/lib/types/import.d.ts +36 -0
- package/lib/types/index.d.ts +12 -1
- package/lib/types/judge.d.ts +76 -0
- package/lib/types/runner.d.ts +3 -0
- package/lib/types/trace.d.ts +15 -0
- package/lib/types/types.d.ts +43 -0
- package/package.json +1 -1
- package/src/benchmark.ts +21 -0
- package/src/command.ts +27 -0
- package/src/compare.ts +135 -2
- package/src/import.ts +327 -0
- package/src/index.ts +33 -3
- package/src/judge.ts +198 -0
- package/src/report.ts +47 -13
- package/src/runner.ts +95 -24
- package/src/trace.ts +43 -0
- package/src/types.ts +46 -0
package/src/judge.ts
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LLM-judge scoring for dsh-eval: builds a judging prompt from the case and
|
|
3
|
+
* its trace, calls an injected chat seam, and parses the model's strict-JSON
|
|
4
|
+
* verdict into a final-answer score and hallucination flag. The production
|
|
5
|
+
* seam wraps the dsh-llm stream API; tests inject a fake so the suite stays
|
|
6
|
+
* keyless.
|
|
7
|
+
*
|
|
8
|
+
* @module dsh-eval/judge
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { BlockAssembler, createMessage, type LlmRuntime } from '@deepseek-ai/dsh-llm'
|
|
12
|
+
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
|
|
13
|
+
import type { BenchmarkCase, BenchmarkJudge, EvalJudgeVerdict, EvalTrace } from './types.ts'
|
|
14
|
+
|
|
15
|
+
/** One judge chat call: system instructions plus the single task prompt. */
|
|
16
|
+
export interface JudgeChatRequest {
|
|
17
|
+
/** Provider route, e.g. `deepseek`. */
|
|
18
|
+
provider: string
|
|
19
|
+
/** Judge model id. */
|
|
20
|
+
model: string
|
|
21
|
+
/** System instructions demanding strict JSON output. */
|
|
22
|
+
system: string
|
|
23
|
+
/** The task and trace summary to judge. */
|
|
24
|
+
prompt: string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The injected chat seam; returns the model's raw text reply. */
|
|
28
|
+
export type JudgeChat = (request: JudgeChatRequest) => Promise<string>
|
|
29
|
+
|
|
30
|
+
/** Concatenate one message's text blocks. */
|
|
31
|
+
function blockText(blocks: readonly ContentBlock[]): string {
|
|
32
|
+
return blocks.flatMap(block => block.type === 'text' ? [block.text] : []).join('')
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Summarize a trace for the judge: final assistant answer, the distinct tool
|
|
37
|
+
* names called, and the failure counters a hallucination call needs.
|
|
38
|
+
* @param trace - the merged trial trace.
|
|
39
|
+
* @returns a compact human-readable summary.
|
|
40
|
+
*/
|
|
41
|
+
export function summarizeTrace(trace: EvalTrace): string {
|
|
42
|
+
let finalAnswer = ''
|
|
43
|
+
const toolNames: string[] = []
|
|
44
|
+
let invalidToolCalls = 0
|
|
45
|
+
let retries = 0
|
|
46
|
+
for (const event of trace.events) {
|
|
47
|
+
if (event.type === 'assistant/message') finalAnswer = blockText(event.data.message.content)
|
|
48
|
+
if (event.type === 'tool/call') {
|
|
49
|
+
if (!toolNames.includes(event.data.name)) toolNames.push(event.data.name)
|
|
50
|
+
}
|
|
51
|
+
if (event.type === 'tool/result' && event.data.error !== undefined) invalidToolCalls += 1
|
|
52
|
+
if (event.type === 'llm/retry') retries += 1
|
|
53
|
+
}
|
|
54
|
+
return [
|
|
55
|
+
`final answer: ${finalAnswer === '' ? '(none)' : finalAnswer}`,
|
|
56
|
+
`tools called: ${toolNames.length === 0 ? '(none)' : toolNames.join(', ')}`,
|
|
57
|
+
`invalid tool calls: ${invalidToolCalls}`,
|
|
58
|
+
`llm retries: ${retries}`,
|
|
59
|
+
].join('\n')
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Build the judge's system instructions and task prompt.
|
|
64
|
+
* @param caseValue - the benchmark case being judged.
|
|
65
|
+
* @param trace - the merged trial trace.
|
|
66
|
+
* @param judge - the judge configuration.
|
|
67
|
+
* @returns the system and prompt texts.
|
|
68
|
+
*/
|
|
69
|
+
export function buildJudgePrompt(
|
|
70
|
+
caseValue: BenchmarkCase,
|
|
71
|
+
trace: EvalTrace,
|
|
72
|
+
judge: BenchmarkJudge,
|
|
73
|
+
): { system: string; prompt: string } {
|
|
74
|
+
const system = [
|
|
75
|
+
'You are an impartial evaluation judge for agent task completion.',
|
|
76
|
+
`Score the agent's final answer from 0 to ${judge.maxScore} against the task,`,
|
|
77
|
+
'and set "hallucination" to true only when the final answer asserts facts',
|
|
78
|
+
'not supported by the task or the trace.',
|
|
79
|
+
'Return STRICT JSON with exactly these fields:',
|
|
80
|
+
`{"finalAnswerScore": <integer 0..${judge.maxScore}>, "hallucination": <true|false>, "rationale": "<one short sentence>"}`,
|
|
81
|
+
...(judge.rubric !== undefined ? ['Rubric:', judge.rubric] : []),
|
|
82
|
+
].join('\n')
|
|
83
|
+
const prompt = [
|
|
84
|
+
`Task id: ${caseValue.id}`,
|
|
85
|
+
`Task: ${caseValue.prompt}`,
|
|
86
|
+
'Trace summary:',
|
|
87
|
+
summarizeTrace(trace),
|
|
88
|
+
].join('\n')
|
|
89
|
+
return { system, prompt }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Extract the JSON object from a model reply, accepting fenced output. */
|
|
93
|
+
function parseJsonObject(text: string): Record<string, unknown> | null {
|
|
94
|
+
const cleaned = text.trim()
|
|
95
|
+
const fenced = cleaned.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/u)
|
|
96
|
+
const candidate = fenced?.[1] ?? cleaned
|
|
97
|
+
try {
|
|
98
|
+
const value: unknown = JSON.parse(candidate)
|
|
99
|
+
return typeof value === 'object' && value !== null
|
|
100
|
+
? value as Record<string, unknown>
|
|
101
|
+
: null
|
|
102
|
+
} catch {
|
|
103
|
+
return null
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Parse the judge model's strict-JSON reply into a verdict. Unusable output
|
|
109
|
+
* yields null fields, never a fabricated verdict.
|
|
110
|
+
* @param text - the raw model reply.
|
|
111
|
+
* @param maxScore - the configured maximum score.
|
|
112
|
+
* @returns the parsed verdict.
|
|
113
|
+
*/
|
|
114
|
+
export function parseJudgeVerdict(text: string, maxScore: number): EvalJudgeVerdict {
|
|
115
|
+
const value = parseJsonObject(text)
|
|
116
|
+
if (value === null) return { finalAnswerScore: null, hallucination: null }
|
|
117
|
+
const score = value.finalAnswerScore
|
|
118
|
+
const hallucination = value.hallucination
|
|
119
|
+
const rationale = value.rationale
|
|
120
|
+
const finalAnswerScore = typeof score === 'number' && Number.isFinite(score) && score >= 0 && score <= maxScore
|
|
121
|
+
? score
|
|
122
|
+
: null
|
|
123
|
+
const parsedHallucination = typeof hallucination === 'boolean' ? hallucination : null
|
|
124
|
+
const parsedRationale = typeof rationale === 'string' && rationale.trim() !== '' ? rationale : undefined
|
|
125
|
+
return {
|
|
126
|
+
finalAnswerScore,
|
|
127
|
+
hallucination: parsedHallucination,
|
|
128
|
+
...(parsedRationale !== undefined ? { rationale: parsedRationale } : {}),
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Judge one trial through the chat seam.
|
|
134
|
+
* @param caseValue - the benchmark case being judged.
|
|
135
|
+
* @param trace - the merged trial trace.
|
|
136
|
+
* @param judge - the judge configuration.
|
|
137
|
+
* @param chat - the injected chat seam.
|
|
138
|
+
* @returns the parsed verdict; a chat failure rejects.
|
|
139
|
+
*/
|
|
140
|
+
export async function judgeTrial(
|
|
141
|
+
caseValue: BenchmarkCase,
|
|
142
|
+
trace: EvalTrace,
|
|
143
|
+
judge: BenchmarkJudge,
|
|
144
|
+
chat: JudgeChat,
|
|
145
|
+
): Promise<EvalJudgeVerdict> {
|
|
146
|
+
const { system, prompt } = buildJudgePrompt(caseValue, trace, judge)
|
|
147
|
+
return parseJudgeVerdict(await chat({ provider: judge.provider, model: judge.model, system, prompt }), judge.maxScore)
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Judge one trial, converting a chat failure into an all-null verdict so a
|
|
152
|
+
* judge outage reads as unjudged rather than a failed trial.
|
|
153
|
+
* @param caseValue - the benchmark case being judged.
|
|
154
|
+
* @param trace - the merged trial trace.
|
|
155
|
+
* @param judge - the judge configuration.
|
|
156
|
+
* @param chat - the injected chat seam.
|
|
157
|
+
* @returns the parsed verdict, or all-null when the chat call threw.
|
|
158
|
+
*/
|
|
159
|
+
export async function tryJudgeTrial(
|
|
160
|
+
caseValue: BenchmarkCase,
|
|
161
|
+
trace: EvalTrace,
|
|
162
|
+
judge: BenchmarkJudge,
|
|
163
|
+
chat: JudgeChat,
|
|
164
|
+
): Promise<EvalJudgeVerdict> {
|
|
165
|
+
try {
|
|
166
|
+
return await judgeTrial(caseValue, trace, judge, chat)
|
|
167
|
+
} catch {
|
|
168
|
+
return { finalAnswerScore: null, hallucination: null }
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Build the production chat seam over a dsh-llm stream: one user turn, zero
|
|
174
|
+
* temperature, and text-block assembly of the reply.
|
|
175
|
+
* @param stream - the llm service's stream method.
|
|
176
|
+
* @returns a chat seam reading only text blocks from the stream.
|
|
177
|
+
*/
|
|
178
|
+
export function llmJudgeChat(stream: LlmRuntime['stream']): JudgeChat {
|
|
179
|
+
return async (request) => {
|
|
180
|
+
const assembler = new BlockAssembler()
|
|
181
|
+
for await (const chunk of stream({
|
|
182
|
+
provider: request.provider,
|
|
183
|
+
model: request.model,
|
|
184
|
+
system: request.system,
|
|
185
|
+
messages: [createMessage({
|
|
186
|
+
role: 'user',
|
|
187
|
+
content: [{ type: 'text', text: request.prompt }],
|
|
188
|
+
source: { kind: 'user' },
|
|
189
|
+
})],
|
|
190
|
+
temperature: 0,
|
|
191
|
+
})) {
|
|
192
|
+
assembler.push(chunk)
|
|
193
|
+
}
|
|
194
|
+
return assembler.message().content
|
|
195
|
+
.flatMap(block => block.type === 'text' ? [block.text] : [])
|
|
196
|
+
.join('')
|
|
197
|
+
}
|
|
198
|
+
}
|
package/src/report.ts
CHANGED
|
@@ -48,6 +48,11 @@ function formatGrade(value: boolean | null): string {
|
|
|
48
48
|
return value === null ? '–' : value ? 'yes' : 'no'
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
+
/** Render a nullable score as `value/max` with a dash placeholder. */
|
|
52
|
+
function formatScore(value: number | null, maxScore: number): string {
|
|
53
|
+
return value === null ? '–' : `${value.toFixed(1)}/${maxScore}`
|
|
54
|
+
}
|
|
55
|
+
|
|
51
56
|
/**
|
|
52
57
|
* Render a run report as a markdown table: one row per trial plus the
|
|
53
58
|
* aggregate row.
|
|
@@ -55,13 +60,20 @@ function formatGrade(value: boolean | null): string {
|
|
|
55
60
|
* @returns the markdown text.
|
|
56
61
|
*/
|
|
57
62
|
export function renderMarkdownReport(run: EvalRun): string {
|
|
58
|
-
const
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
63
|
+
const judge = run.judge
|
|
64
|
+
const judged = judge !== undefined
|
|
65
|
+
const header = judged
|
|
66
|
+
? [
|
|
67
|
+
'| case | trial | status | steps | tools | success | invalid | retries | tokens | cost | latency ms | task | tool-acc | score | halluc |',
|
|
68
|
+
'|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|',
|
|
69
|
+
]
|
|
70
|
+
: [
|
|
71
|
+
'| case | trial | status | steps | tools | success | invalid | retries | tokens | cost | latency ms | task | tool-acc |',
|
|
72
|
+
'|---|---|---|---|---|---|---|---|---|---|---|---|---|',
|
|
73
|
+
]
|
|
62
74
|
const rows = run.cases.map((result) => {
|
|
63
75
|
const metrics = result.metrics
|
|
64
|
-
const
|
|
76
|
+
const base = metrics === undefined
|
|
65
77
|
? ['–', '–', '–', '–', '–', '–', '–', '–', '–', '–']
|
|
66
78
|
: [
|
|
67
79
|
String(metrics.steps),
|
|
@@ -75,20 +87,42 @@ export function renderMarkdownReport(run: EvalRun): string {
|
|
|
75
87
|
formatGrade(result.grade?.taskSuccess ?? null),
|
|
76
88
|
formatGrade(result.grade?.toolSelectionAccuracy ?? null),
|
|
77
89
|
]
|
|
78
|
-
|
|
90
|
+
const judgeCells = judged
|
|
91
|
+
? [
|
|
92
|
+
formatScore(result.judge?.finalAnswerScore ?? null, judge.maxScore),
|
|
93
|
+
formatGrade(result.judge?.hallucination ?? null),
|
|
94
|
+
]
|
|
95
|
+
: []
|
|
96
|
+
return `| ${result.caseId} | ${result.trial} | ${result.status} | ${[...base, ...judgeCells].join(' | ')} |`
|
|
79
97
|
})
|
|
80
98
|
const aggregate = run.aggregate
|
|
81
|
-
const
|
|
82
|
-
?
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
99
|
+
const aggregateJudgeCells = judged
|
|
100
|
+
? [
|
|
101
|
+
formatScore(run.grading?.finalAnswerScore ?? null, judge.maxScore),
|
|
102
|
+
formatRate(run.grading?.hallucinationRate ?? null),
|
|
103
|
+
]
|
|
104
|
+
: []
|
|
105
|
+
const aggregateCells = aggregate === null
|
|
106
|
+
? ['no completed trials', '–', '–', '–', '–', '–', '–', '–', '–', '–', '–']
|
|
107
|
+
: [
|
|
108
|
+
'completed',
|
|
109
|
+
aggregate.steps.toFixed(1),
|
|
110
|
+
aggregate.toolCalls.toFixed(1),
|
|
111
|
+
formatRate(aggregate.toolSuccessRate),
|
|
112
|
+
aggregate.invalidToolCalls.toFixed(1),
|
|
113
|
+
aggregate.retries.toFixed(1),
|
|
114
|
+
aggregate.totalTokens.toFixed(1),
|
|
115
|
+
formatUsd(aggregate.costUsd),
|
|
116
|
+
aggregate.latencyMs.toFixed(1),
|
|
117
|
+
formatRate(run.grading?.taskSuccessRate ?? null),
|
|
118
|
+
formatRate(run.grading?.toolSelectionAccuracyRate ?? null),
|
|
119
|
+
]
|
|
120
|
+
const aggregateRow = `| aggregate | – | ${[...aggregateCells, ...aggregateJudgeCells].join(' | ')} |`
|
|
88
121
|
return [
|
|
89
122
|
`# Eval: ${run.benchmark}`,
|
|
90
123
|
'',
|
|
91
124
|
`- model: ${run.model}`,
|
|
125
|
+
...(judged ? [`- judge: ${judge.model}`] : []),
|
|
92
126
|
`- trials per case: ${run.trials}`,
|
|
93
127
|
`- created: ${new Date(run.createdAt).toISOString()}`,
|
|
94
128
|
`- traces: ${run.tempRoot}`,
|
package/src/runner.ts
CHANGED
|
@@ -19,23 +19,9 @@ import { tmpdir } from 'node:os'
|
|
|
19
19
|
import { join } from 'node:path'
|
|
20
20
|
import type { Benchmark, EvalRun, EvalTrialResult } from './types.ts'
|
|
21
21
|
import type { EvalGrade, EvalRunGrading } from './types.ts'
|
|
22
|
+
import { tryJudgeTrial, type JudgeChat } from './judge.ts'
|
|
22
23
|
import { aggregateMetrics, computeMetrics } from './metrics.ts'
|
|
23
|
-
import {
|
|
24
|
-
|
|
25
|
-
/** Overlay forcing the harvested log to plain JSONL and the run to be non-interactive. */
|
|
26
|
-
const EVAL_OVERLAY = `- id: session-persistence-jsonl
|
|
27
|
-
config:
|
|
28
|
-
root: !!js dshHomePath('sessions')
|
|
29
|
-
packChunks: false
|
|
30
|
-
compression: none
|
|
31
|
-
- id: sandbox-policy
|
|
32
|
-
config:
|
|
33
|
-
mode: workspace-write
|
|
34
|
-
workspaceRoot: !!js process.cwd()
|
|
35
|
-
- id: approval
|
|
36
|
-
config:
|
|
37
|
-
policy: never
|
|
38
|
-
`
|
|
24
|
+
import { findSessionLogs, loadTrace, mergeTraces } from './trace.ts'
|
|
39
25
|
|
|
40
26
|
/** Cap per-stream child output so a runaway trial cannot exhaust memory. */
|
|
41
27
|
const MAX_OUTPUT_BYTES = 512 * 1024
|
|
@@ -50,6 +36,8 @@ export interface RunOptions {
|
|
|
50
36
|
trials?: number
|
|
51
37
|
/** Root for trial directories; defaults to the platform temp dir. */
|
|
52
38
|
tempRoot?: string
|
|
39
|
+
/** LLM-judge chat seam; required when the benchmark configures a judge. */
|
|
40
|
+
judgeChat?: JudgeChat
|
|
53
41
|
}
|
|
54
42
|
|
|
55
43
|
/** One child process's orthogonal outcome facts. */
|
|
@@ -79,6 +67,39 @@ function sanitizeSegment(value: string): string {
|
|
|
79
67
|
return safe === '' ? 'case' : safe
|
|
80
68
|
}
|
|
81
69
|
|
|
70
|
+
/**
|
|
71
|
+
* Build the per-trial overlay: plain-JSONL persistence, non-interactive
|
|
72
|
+
* permissions, and the keyless replay plugin when recorded logs exist.
|
|
73
|
+
* @param replay - the replay primary log and child logs, or undefined.
|
|
74
|
+
* @returns the overlay YAML text.
|
|
75
|
+
*/
|
|
76
|
+
function evalOverlay(replay: { file: string; childFiles: readonly string[] } | undefined): string {
|
|
77
|
+
const lines = [
|
|
78
|
+
'- id: session-persistence-jsonl',
|
|
79
|
+
' config:',
|
|
80
|
+
" root: !!js dshHomePath('sessions')",
|
|
81
|
+
' packChunks: false',
|
|
82
|
+
' compression: none',
|
|
83
|
+
'- id: sandbox-policy',
|
|
84
|
+
' config:',
|
|
85
|
+
' mode: workspace-write',
|
|
86
|
+
' workspaceRoot: !!js process.cwd()',
|
|
87
|
+
'- id: approval',
|
|
88
|
+
' config:',
|
|
89
|
+
' policy: never',
|
|
90
|
+
]
|
|
91
|
+
if (replay !== undefined) {
|
|
92
|
+
lines.push(
|
|
93
|
+
'- id: llm-replay',
|
|
94
|
+
" name: '@deepseek-ai/dsh-llm-replay'",
|
|
95
|
+
' config:',
|
|
96
|
+
` file: ${JSON.stringify(replay.file)}`,
|
|
97
|
+
...(replay.childFiles.length === 0 ? [] : [` childFiles: ${JSON.stringify(replay.childFiles)}`]),
|
|
98
|
+
)
|
|
99
|
+
}
|
|
100
|
+
return `${lines.join('\n')}\n`
|
|
101
|
+
}
|
|
102
|
+
|
|
82
103
|
/** Split a single command string into argv on whitespace. */
|
|
83
104
|
function splitWords(value: string): string[] {
|
|
84
105
|
return value.trim().split(/\s+/u).filter(part => part !== '')
|
|
@@ -131,9 +152,22 @@ function pooledRate(items: readonly EvalTrialResult[], select: (grade: EvalGrade
|
|
|
131
152
|
function gradingOf(results: readonly EvalTrialResult[]): EvalRunGrading | null {
|
|
132
153
|
const taskSuccessRate = pooledRate(results, grade => grade?.taskSuccess ?? null)
|
|
133
154
|
const toolSelectionAccuracyRate = pooledRate(results, grade => grade?.toolSelectionAccuracy ?? null)
|
|
155
|
+
const finalScores = results
|
|
156
|
+
.map(result => result.judge?.finalAnswerScore ?? null)
|
|
157
|
+
.filter((value): value is number => value !== null)
|
|
158
|
+
const finalAnswerScore = finalScores.length === 0
|
|
159
|
+
? null
|
|
160
|
+
: finalScores.reduce((total, value) => total + value, 0) / finalScores.length
|
|
161
|
+
const hallucinated = results
|
|
162
|
+
.map(result => result.judge?.hallucination ?? null)
|
|
163
|
+
.filter((value): value is boolean => value !== null)
|
|
164
|
+
const hallucinationRate = hallucinated.length === 0
|
|
165
|
+
? null
|
|
166
|
+
: hallucinated.filter(value => value).length / hallucinated.length
|
|
134
167
|
return taskSuccessRate === null && toolSelectionAccuracyRate === null
|
|
168
|
+
&& finalAnswerScore === null && hallucinationRate === null
|
|
135
169
|
? null
|
|
136
|
-
: { taskSuccessRate, toolSelectionAccuracyRate }
|
|
170
|
+
: { taskSuccessRate, toolSelectionAccuracyRate, finalAnswerScore, hallucinationRate }
|
|
137
171
|
}
|
|
138
172
|
|
|
139
173
|
/**
|
|
@@ -212,6 +246,7 @@ async function runCaseTrial(
|
|
|
212
246
|
caseValue: Benchmark['cases'][number],
|
|
213
247
|
trial: number,
|
|
214
248
|
root: string,
|
|
249
|
+
judgeChat: JudgeChat | undefined,
|
|
215
250
|
): Promise<EvalTrialResult> {
|
|
216
251
|
const trialDir = join(root, `${sanitizeSegment(caseValue.id)}-${trial}`)
|
|
217
252
|
const workspace = join(trialDir, 'workspace')
|
|
@@ -219,8 +254,27 @@ async function runCaseTrial(
|
|
|
219
254
|
await mkdir(workspace, { recursive: true })
|
|
220
255
|
await mkdir(dshHome, { recursive: true, mode: 0o700 })
|
|
221
256
|
if (caseValue.workspace !== undefined) await cp(caseValue.workspace, workspace, { recursive: true })
|
|
257
|
+
const replayFixture = benchmark.replay === undefined
|
|
258
|
+
? undefined
|
|
259
|
+
: join(benchmark.replay.dir, `${sanitizeSegment(caseValue.id)}-${trial}`)
|
|
260
|
+
let replay: { file: string; childFiles: string[] } | undefined
|
|
261
|
+
if (replayFixture !== undefined) {
|
|
262
|
+
const logs = await findSessionLogs(replayFixture)
|
|
263
|
+
if (logs.length === 0) {
|
|
264
|
+
return {
|
|
265
|
+
caseId: caseValue.id,
|
|
266
|
+
trial,
|
|
267
|
+
status: 'error',
|
|
268
|
+
error: `no replay fixture found at ${replayFixture}`,
|
|
269
|
+
exitCode: null,
|
|
270
|
+
timedOut: false,
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
const primary = logs[0]!
|
|
274
|
+
replay = { file: primary, childFiles: logs.slice(1) }
|
|
275
|
+
}
|
|
222
276
|
const overlayPath = join(trialDir, 'eval.cordis.yml')
|
|
223
|
-
await writeFile(overlayPath,
|
|
277
|
+
await writeFile(overlayPath, evalOverlay(replay), 'utf8')
|
|
224
278
|
let outcome: SpawnOutcome
|
|
225
279
|
try {
|
|
226
280
|
outcome = await runCommand(
|
|
@@ -240,8 +294,8 @@ async function runCaseTrial(
|
|
|
240
294
|
timedOut: false,
|
|
241
295
|
}
|
|
242
296
|
}
|
|
243
|
-
const
|
|
244
|
-
if (
|
|
297
|
+
const tracePaths = await findSessionLogs(dshHome)
|
|
298
|
+
if (tracePaths.length === 0) {
|
|
245
299
|
return {
|
|
246
300
|
caseId: caseValue.id,
|
|
247
301
|
trial,
|
|
@@ -252,26 +306,36 @@ async function runCaseTrial(
|
|
|
252
306
|
}
|
|
253
307
|
}
|
|
254
308
|
try {
|
|
255
|
-
const trace =
|
|
309
|
+
const loaded: { path: string; trace: Awaited<ReturnType<typeof loadTrace>> }[] = []
|
|
310
|
+
for (const path of tracePaths) loaded.push({ path, trace: await loadTrace(path) })
|
|
311
|
+
loaded.sort((a, b) => a.trace.createdAt - b.trace.createdAt)
|
|
312
|
+
// tracePaths.length > 0 above guarantees a non-empty loaded list.
|
|
313
|
+
const primaryPath = loaded[0]!.path
|
|
314
|
+
const trace = mergeTraces(loaded.map(entry => entry.trace))
|
|
256
315
|
const pricing = benchmark.pricing?.[benchmark.model]
|
|
257
316
|
const metrics = computeMetrics(trace.events, pricing)
|
|
258
317
|
const grade = await gradeTrial(caseValue, trace, workspace, benchmark.timeoutMs)
|
|
318
|
+
const judge = benchmark.judge === undefined || judgeChat === undefined
|
|
319
|
+
? undefined
|
|
320
|
+
: await tryJudgeTrial(caseValue, trace, benchmark.judge, judgeChat)
|
|
259
321
|
return {
|
|
260
322
|
caseId: caseValue.id,
|
|
261
323
|
trial,
|
|
262
324
|
status: 'completed',
|
|
263
|
-
tracePath,
|
|
325
|
+
tracePath: primaryPath,
|
|
326
|
+
tracePaths: loaded.map(entry => entry.path),
|
|
264
327
|
exitCode: outcome.exitCode,
|
|
265
328
|
timedOut: outcome.timedOut,
|
|
266
329
|
metrics,
|
|
267
330
|
...(grade.taskSuccess !== null || grade.toolSelectionAccuracy !== null ? { grade } : {}),
|
|
331
|
+
...(judge !== undefined ? { judge } : {}),
|
|
268
332
|
}
|
|
269
333
|
} catch (error) {
|
|
270
334
|
return {
|
|
271
335
|
caseId: caseValue.id,
|
|
272
336
|
trial,
|
|
273
337
|
status: 'error',
|
|
274
|
-
error: `failed to read trace
|
|
338
|
+
error: `failed to read trace: ${message(error)}`,
|
|
275
339
|
exitCode: outcome.exitCode,
|
|
276
340
|
timedOut: outcome.timedOut,
|
|
277
341
|
}
|
|
@@ -285,6 +349,12 @@ async function runCaseTrial(
|
|
|
285
349
|
* @returns the completed run record, written by the caller.
|
|
286
350
|
*/
|
|
287
351
|
export async function runBenchmark(benchmark: Benchmark, options: RunOptions = {}): Promise<EvalRun> {
|
|
352
|
+
if (benchmark.judge !== undefined && options.judgeChat === undefined) {
|
|
353
|
+
throw new Error('eval: benchmark configures a judge but no LLM chat seam is available')
|
|
354
|
+
}
|
|
355
|
+
if (benchmark.judge !== undefined && benchmark.replay !== undefined) {
|
|
356
|
+
throw new Error('eval: judge and replay cannot be combined in one run')
|
|
357
|
+
}
|
|
288
358
|
const root = await mkdtemp(join(options.tempRoot ?? tmpdir(), 'dsh-eval-'))
|
|
289
359
|
const trials = options.trials ?? benchmark.trials
|
|
290
360
|
const effective: Benchmark = {
|
|
@@ -295,7 +365,7 @@ export async function runBenchmark(benchmark: Benchmark, options: RunOptions = {
|
|
|
295
365
|
const results: EvalTrialResult[] = []
|
|
296
366
|
for (const caseValue of effective.cases) {
|
|
297
367
|
for (let trial = 1; trial <= trials; trial++) {
|
|
298
|
-
results.push(await runCaseTrial(effective, caseValue, trial, root))
|
|
368
|
+
results.push(await runCaseTrial(effective, caseValue, trial, root, options.judgeChat))
|
|
299
369
|
}
|
|
300
370
|
}
|
|
301
371
|
const completed = results.filter(
|
|
@@ -309,6 +379,7 @@ export async function runBenchmark(benchmark: Benchmark, options: RunOptions = {
|
|
|
309
379
|
trials,
|
|
310
380
|
seed: benchmark.seed,
|
|
311
381
|
pricing: benchmark.pricing?.[benchmark.model] ?? null,
|
|
382
|
+
...(benchmark.judge !== undefined ? { judge: benchmark.judge } : {}),
|
|
312
383
|
tempRoot: root,
|
|
313
384
|
cases: results,
|
|
314
385
|
aggregate: aggregateMetrics(completed.map(result => result.metrics)),
|
package/src/trace.ts
CHANGED
|
@@ -92,3 +92,46 @@ export async function findPrimarySessionLog(root: string): Promise<string | null
|
|
|
92
92
|
}
|
|
93
93
|
return best?.path ?? null
|
|
94
94
|
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Find every `session.jsonl` under a DSH_HOME tree, sorted by modification
|
|
98
|
+
* time ascending so the parent session (started first) comes first.
|
|
99
|
+
* @param root - the DSH_HOME directory to scan.
|
|
100
|
+
* @returns absolute log paths in ascending mtime order.
|
|
101
|
+
*/
|
|
102
|
+
export async function findSessionLogs(root: string): Promise<string[]> {
|
|
103
|
+
let entries
|
|
104
|
+
try {
|
|
105
|
+
entries = await readdir(root, { withFileTypes: true })
|
|
106
|
+
} catch {
|
|
107
|
+
return []
|
|
108
|
+
}
|
|
109
|
+
const found: { path: string; mtime: number }[] = []
|
|
110
|
+
for (const entry of entries) {
|
|
111
|
+
if (entry.isDirectory()) {
|
|
112
|
+
for (const nested of await findSessionLogs(join(root, entry.name))) {
|
|
113
|
+
found.push({ path: nested, mtime: (await stat(nested)).mtimeMs })
|
|
114
|
+
}
|
|
115
|
+
} else if (entry.isFile() && entry.name === 'session.jsonl') {
|
|
116
|
+
found.push({ path: join(root, entry.name), mtime: (await stat(join(root, entry.name))).mtimeMs })
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return found.sort((a, b) => a.mtime - b.mtime).map(entry => entry.path)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Merge traces into one timeline: events from every trace sorted by event
|
|
124
|
+
* time, ties broken by source order. The primary trace's header (session id
|
|
125
|
+
* and creation time) labels the merged trace.
|
|
126
|
+
* @param traces - harvested traces, primary first.
|
|
127
|
+
* @returns the merged trace.
|
|
128
|
+
*/
|
|
129
|
+
export function mergeTraces(traces: readonly EvalTrace[]): EvalTrace {
|
|
130
|
+
const primary = traces[0]
|
|
131
|
+
if (primary === undefined) throw new Error('mergeTraces requires at least one trace')
|
|
132
|
+
const events = traces
|
|
133
|
+
.flatMap((trace, source) => trace.events.map(event => ({ event, source })))
|
|
134
|
+
.sort((a, b) => a.event.time - b.event.time || a.source - b.source)
|
|
135
|
+
.map(entry => entry.event)
|
|
136
|
+
return { sessionId: primary.sessionId, createdAt: primary.createdAt, events }
|
|
137
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -40,6 +40,28 @@ export interface BenchmarkExpectation {
|
|
|
40
40
|
check?: string
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
+
/** LLM-judge configuration: scores final answers and flags hallucinations. */
|
|
44
|
+
export interface BenchmarkJudge {
|
|
45
|
+
/** Provider route for the judge call, e.g. `deepseek`. */
|
|
46
|
+
provider: string
|
|
47
|
+
/** Judge model id; defaults to the benchmark model when unset. */
|
|
48
|
+
model: string
|
|
49
|
+
/** Optional task rubric appended to the default judging instructions. */
|
|
50
|
+
rubric?: string
|
|
51
|
+
/** Maximum final-answer score; defaults to 10. */
|
|
52
|
+
maxScore: number
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Keyless replay configuration: recorded session logs replayed instead of live model calls. */
|
|
56
|
+
export interface BenchmarkReplay {
|
|
57
|
+
/**
|
|
58
|
+
* Directory holding one recorded-log tree per trial, named
|
|
59
|
+
* `<caseId>-<trial>/session.jsonl` (child logs ride alongside). A run with
|
|
60
|
+
* a key records these under its `tempRoot`.
|
|
61
|
+
*/
|
|
62
|
+
dir: string
|
|
63
|
+
}
|
|
64
|
+
|
|
43
65
|
/** A validated benchmark document. */
|
|
44
66
|
export interface Benchmark {
|
|
45
67
|
/** Benchmark name; also the run record's `benchmark` field. */
|
|
@@ -60,6 +82,10 @@ export interface Benchmark {
|
|
|
60
82
|
cases: readonly BenchmarkCase[]
|
|
61
83
|
/** Pricing keyed by model id; an absent model reports `costUsd: null`. */
|
|
62
84
|
pricing?: Readonly<Record<string, BenchmarkPricing>>
|
|
85
|
+
/** LLM-judge configuration, when final-answer scoring is enabled. */
|
|
86
|
+
judge?: BenchmarkJudge
|
|
87
|
+
/** Keyless replay configuration, when model calls replay from recorded logs. */
|
|
88
|
+
replay?: BenchmarkReplay
|
|
63
89
|
/** Directory the benchmark document was loaded from; relative paths resolve against it. */
|
|
64
90
|
baseDir: string
|
|
65
91
|
}
|
|
@@ -138,6 +164,8 @@ export interface EvalTrialResult {
|
|
|
138
164
|
error?: string
|
|
139
165
|
/** Absolute path of the harvested primary session log. */
|
|
140
166
|
tracePath?: string
|
|
167
|
+
/** Absolute paths of every harvested session log, primary first. */
|
|
168
|
+
tracePaths?: readonly string[]
|
|
141
169
|
/** The child process's exit code, or null when it was killed. */
|
|
142
170
|
exitCode: number | null
|
|
143
171
|
/** Whether the trial hit its timeout and killed the child. */
|
|
@@ -146,6 +174,8 @@ export interface EvalTrialResult {
|
|
|
146
174
|
metrics?: EvalCaseMetrics
|
|
147
175
|
/** Scripted grading outcome for `completed` trials with expectations. */
|
|
148
176
|
grade?: EvalGrade
|
|
177
|
+
/** LLM-judge verdict for `completed` trials with a configured judge. */
|
|
178
|
+
judge?: EvalJudgeVerdict
|
|
149
179
|
}
|
|
150
180
|
|
|
151
181
|
/** Scripted grading outcome for one trial. */
|
|
@@ -156,12 +186,26 @@ export interface EvalGrade {
|
|
|
156
186
|
toolSelectionAccuracy: boolean | null
|
|
157
187
|
}
|
|
158
188
|
|
|
189
|
+
/** LLM-judge verdict for one trial. */
|
|
190
|
+
export interface EvalJudgeVerdict {
|
|
191
|
+
/** Final-answer score within the benchmark's `maxScore`, or null when the judge output was unusable. */
|
|
192
|
+
finalAnswerScore: number | null
|
|
193
|
+
/** Whether the judge flagged hallucinated content, or null when the judge output was unusable. */
|
|
194
|
+
hallucination: boolean | null
|
|
195
|
+
/** Judge rationale, when the model returned one. */
|
|
196
|
+
rationale?: string
|
|
197
|
+
}
|
|
198
|
+
|
|
159
199
|
/** Pooled grading rates over completed trials. */
|
|
160
200
|
export interface EvalRunGrading {
|
|
161
201
|
/** Pooled task-success rate, or null when no trial carried a check. */
|
|
162
202
|
taskSuccessRate: number | null
|
|
163
203
|
/** Pooled tool-selection-accuracy rate, or null when no trial carried an expected tool. */
|
|
164
204
|
toolSelectionAccuracyRate: number | null
|
|
205
|
+
/** Mean final-answer score over judged trials, or null when nothing was judged. */
|
|
206
|
+
finalAnswerScore: number | null
|
|
207
|
+
/** Pooled hallucination rate over judged trials, or null when nothing was judged. */
|
|
208
|
+
hallucinationRate: number | null
|
|
165
209
|
}
|
|
166
210
|
|
|
167
211
|
/** A persisted eval run. */
|
|
@@ -178,6 +222,8 @@ export interface EvalRun {
|
|
|
178
222
|
seed: number
|
|
179
223
|
/** Resolved pricing for the benchmark model, or null without one. */
|
|
180
224
|
pricing: BenchmarkPricing | null
|
|
225
|
+
/** The judge configuration the run used, when one was configured. */
|
|
226
|
+
judge?: BenchmarkJudge
|
|
181
227
|
/** Root holding every trial's workspace, overlay, and harvested trace. */
|
|
182
228
|
tempRoot: string
|
|
183
229
|
/** Per-trial outcomes in execution order. */
|