Repository navigation
Expand file tree
/
Copy pathclassify.ts
More file actions
244 lines (228 loc) · 7.01 KB
/
Copy pathclassify.ts
File metadata and controls
244 lines (228 loc) · 7.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import {
ParsedReportSchema,
type ParsedReport,
type Triage,
} from '../schema/parsed-report';
import {
LLMOutputSchema,
llmToolInputJSONSchema,
toolInputSchemaFor,
} from '../llm/tool-schema';
import { DRAFT_SYSTEM_BLOCKS, SYSTEM_BLOCKS } from '../llm/prompt';
import {
type AnthropicClient,
type MessagesResponse,
type MessagesUsage,
type ToolUseBlock,
DEFAULT_MODEL,
DEFAULT_MAX_TOKENS,
} from '../llm/client';
import type { JevClient } from '../jev/client';
import { decideBucket } from '../jev/triage';
import {
nonBugFromDecision,
tooVagueFromDecision,
triageFromDecision,
} from './templates';
export interface ClassifyOptions {
model?: string;
maxTokens?: number;
}
/** A classified report plus the call metadata the eval scripts need. */
export interface ClassifyResult {
report: ParsedReport;
/** Absent when the client did not report usage (mocked clients) or no LLM call was made. */
usage?: MessagesUsage;
latencyMs: number;
}
export type ClassifyErrorStage =
| 'no_tool_use'
| 'wrong_tool_name'
| 'bucket_mismatch'
| 'llm_schema'
| 'final_schema';
export class ClassifyError extends Error {
constructor(
message: string,
public override readonly cause: unknown,
public readonly stage: ClassifyErrorStage,
) {
super(message);
this.name = 'ClassifyError';
}
}
const TOOL_NAME = 'classify_bug_report';
const TOOL_DESCRIPTION =
'Classify a user-submitted bug report into one of four structured outputs. Call exactly once.';
const DRAFT_TOOL_DESCRIPTION =
'Fill in the structured output for a bug report whose classification has already been decided. Call exactly once.';
// Runner-owned fields attached after the LLM call. The LLM is never allowed to
// emit any of these (see OMIT in tool-schema.ts).
interface RunnerFields {
report_id: string;
original_input: string;
triage?: Triage;
}
function extractToolInput(response: MessagesResponse): unknown {
const toolUse = response.content.find(
(b): b is ToolUseBlock => b.type === 'tool_use',
);
if (!toolUse) {
throw new ClassifyError(
`Expected tool_use block in response (stop_reason=${response.stop_reason})`,
response,
'no_tool_use',
);
}
if (toolUse.name !== TOOL_NAME) {
throw new ClassifyError(
`Unexpected tool name: ${toolUse.name}`,
toolUse,
'wrong_tool_name',
);
}
return toolUse.input;
}
// Validation pass 1 blames the model precisely; pass 2 asserts the full
// contract after the runner-owned fields are merged in.
function validateAndMerge(input: unknown, runnerFields: RunnerFields): ParsedReport {
const llmParsed = LLMOutputSchema.safeParse(input);
if (!llmParsed.success) {
throw new ClassifyError(
'LLM tool_use.input failed schema validation',
llmParsed.error,
'llm_schema',
);
}
const merged = { ...llmParsed.data, ...runnerFields };
const finalParsed = ParsedReportSchema.safeParse(merged);
if (!finalParsed.success) {
throw new ClassifyError(
'Merged result failed final ParsedReport validation',
finalParsed.error,
'final_schema',
);
}
return finalParsed.data;
}
export async function classifyReport(
reportId: string,
rawInput: string,
client: AnthropicClient,
options: ClassifyOptions = {},
): Promise<ParsedReport> {
const result = await classifyReportWithMeta(reportId, rawInput, client, options);
return result.report;
}
export async function classifyReportWithMeta(
reportId: string,
rawInput: string,
client: AnthropicClient,
options: ClassifyOptions = {},
): Promise<ClassifyResult> {
const started = performance.now();
const response = await client.createMessage({
model: options.model ?? DEFAULT_MODEL,
max_tokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
system: SYSTEM_BLOCKS,
tools: [
{
name: TOOL_NAME,
description: TOOL_DESCRIPTION,
input_schema: llmToolInputJSONSchema,
},
],
tool_choice: { type: 'tool', name: TOOL_NAME },
messages: [{ role: 'user', content: `Bug report:\n\n${rawInput}` }],
});
const input = extractToolInput(response);
const report = validateAndMerge(input, {
report_id: reportId,
original_input: rawInput,
});
return {
report,
...(response.usage ? { usage: response.usage } : {}),
latencyMs: performance.now() - started,
};
}
/**
* Hybrid engine: Jev decides the bucket, the LLM drafts only when there is
* something to draft.
*
* - too_vague and non_bug are answered from templates with no LLM call.
* - actionable and partial go to the LLM with the bucket pinned in the tool
* schema and the decision order removed from the prompt. If the LLM returns
* a different classification anyway, that is reported as bucket_mismatch
* before any schema validation runs, so an override is never misattributed
* as a generic schema failure.
*/
export async function classifyReportHybrid(
reportId: string,
rawInput: string,
jev: JevClient,
anthropic: AnthropicClient,
options: ClassifyOptions = {},
): Promise<ClassifyResult> {
const started = performance.now();
const decision = await decideBucket(rawInput, jev, { includeRoute: true });
if (
decision.bucket === 'too_vague_request_more_info' ||
decision.bucket === 'non_bug_support_question'
) {
const draft =
decision.bucket === 'too_vague_request_more_info'
? tooVagueFromDecision(reportId, rawInput, decision)
: nonBugFromDecision(reportId, rawInput, decision);
const parsed = ParsedReportSchema.safeParse(draft);
if (!parsed.success) {
throw new ClassifyError(
'Templated result failed final ParsedReport validation',
parsed.error,
'final_schema',
);
}
return { report: parsed.data, latencyMs: performance.now() - started };
}
const response = await anthropic.createMessage({
model: options.model ?? DEFAULT_MODEL,
max_tokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
system: DRAFT_SYSTEM_BLOCKS,
tools: [
{
name: TOOL_NAME,
description: DRAFT_TOOL_DESCRIPTION,
input_schema: toolInputSchemaFor(decision.bucket),
},
],
tool_choice: { type: 'tool', name: TOOL_NAME },
messages: [
{
role: 'user',
content: `Classification (already decided): ${decision.bucket}\n\nBug report:\n\n${rawInput}`,
},
],
});
const input = extractToolInput(response);
const returned =
typeof input === 'object' && input !== null && 'classification' in input
? (input as { classification: unknown }).classification
: undefined;
if (returned !== decision.bucket) {
throw new ClassifyError(
`LLM returned classification ${String(returned)} but the pinned bucket is ${decision.bucket}`,
input,
'bucket_mismatch',
);
}
const report = validateAndMerge(input, {
report_id: reportId,
original_input: rawInput,
triage: triageFromDecision(decision, true),
});
return {
report,
...(response.usage ? { usage: response.usage } : {}),
latencyMs: performance.now() - started,
};
}