-
Notifications
You must be signed in to change notification settings - Fork 298
Expand file tree
/
Copy pathjson-schema.ts
More file actions
47 lines (43 loc) · 1.47 KB
/
json-schema.ts
File metadata and controls
47 lines (43 loc) · 1.47 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
import { FromSchema, JSONSchema } from 'json-schema-to-ts';
import { AutoParseableOutputFormat } from '../lib/parser';
import { AnthropicError } from '../core/error';
import { transformJSONSchema } from '../lib/transform-json-schema';
/**
* Creates a JSON schema output format object from the given JSON schema.
* If this is passed to the `.parse()` method then the response message will contain a
* `.parsed_output` property that is the result of parsing the content with the given JSON schema.
*
* Note: When `transform` is enabled (the default), the schema is deep-cloned before transformation,
* so the original schema object is not modified.
*/
export function jsonSchemaOutputFormat<
const Schema extends Exclude<JSONSchema, boolean> & { type: 'object' },
>(
jsonSchema: Schema,
options?: {
transform?: boolean;
},
): AutoParseableOutputFormat<NoInfer<FromSchema<Schema>>> {
if (jsonSchema.type !== 'object') {
throw new Error(`JSON schema must be an object, but got ${jsonSchema.type}`);
}
const transform = options?.transform ?? true;
if (transform) {
jsonSchema = transformJSONSchema(jsonSchema) as Schema;
}
return {
type: 'json_schema',
schema: {
...jsonSchema,
},
parse: (content) => {
try {
return JSON.parse(content);
} catch (error) {
throw new AnthropicError(
`Failed to parse structured output: ${error instanceof Error ? error.message : String(error)}`,
);
}
},
};
}