Repository navigation
Expand file tree
/
Copy pathstructured-output.ts
More file actions
65 lines (58 loc) · 1.71 KB
/
Copy pathstructured-output.ts
File metadata and controls
65 lines (58 loc) · 1.71 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
/**
* Structured output example.
*
* Defines the expected output once with zod, sends it to Droid as a JSON
* schema via `outputFormat`, and validates `result.structuredOutput` with the
* same schema.
*
* Usage:
* npx tsx examples/node/structured-output.ts
*/
import { OutputFormatType, run } from '@factory/droid-sdk/node';
// `zod/v4` provides `z.toJSONSchema()`. sdk-mcp-tool.ts imports `zod` instead,
// because the SDK `tool()` helper expects zod v3 schemas.
import { z } from 'zod/v4';
const CodeReviewSchema = z.strictObject({
summary: z.string(),
findings: z.array(
z.strictObject({
line: z.number(),
severity: z.enum(['low', 'medium', 'high']),
message: z.string(),
})
),
});
const result = await run(
`Review this code for correctness issues:
function getDisplayName(user) {
return user.profile.name.trim();
}`,
{
outputFormat: {
type: OutputFormatType.JsonSchema,
// Droid validates schemas as JSON Schema draft-07; zod defaults to 2020-12.
schema: z.toJSONSchema(CodeReviewSchema, { target: 'draft-7' }),
},
}
);
if (!result.success) {
const detail =
result.structuredOutputError?.message ??
result.error?.message ??
'Unknown error';
throw new Error(`run() failed (${result.subtype}): ${detail}`);
}
// The SDK returns `unknown`; validate it before reading fields.
const parsed = CodeReviewSchema.safeParse(result.structuredOutput);
if (!parsed.success) {
throw new Error(
`Unexpected structured output:\n${z.prettifyError(parsed.error)}`
);
}
const review = parsed.data;
console.log(review.summary);
for (const finding of review.findings) {
console.log(
`- line ${finding.line} [${finding.severity}] ${finding.message}`
);
}