metrale_grammar/schema/
api.rs1use super::converter::JsonSchemaConverter;
8use super::error::{SchemaError, SchemaResult};
9use super::json_value::JsonValue;
10use super::options::{JsonFormat, SchemaConverterOptions};
11use super::parser::SchemaParser;
12use crate::grammar::{GrammarData, parse_ebnf_default};
13
14pub fn json_value_to_ebnf(
18 schema: &JsonValue,
19 options: &SchemaConverterOptions,
20) -> SchemaResult<String> {
21 let mut parser = SchemaParser::new(schema.clone(), options.strict_mode);
22 let spec = parser.parse(schema, "root", None)?;
23 let mut converter = JsonSchemaConverter::new(options, &mut parser);
24 converter.convert(&spec)
25}
26
27pub fn json_schema_to_ebnf(schema: &str, options: &SchemaConverterOptions) -> SchemaResult<String> {
30 let value = JsonValue::parse(schema)
31 .map_err(|e| SchemaError::invalid(format!("Failed to parse JSON schema: {e}")))?;
32 json_value_to_ebnf(&value, options)
33}
34
35pub fn json_schema_to_grammar(
38 schema: &str,
39 options: &SchemaConverterOptions,
40) -> SchemaResult<GrammarData> {
41 let ebnf = json_schema_to_ebnf(schema, options)?;
42 parse_ebnf_default(&ebnf)
43 .map_err(|e| SchemaError::invalid(format!("generated EBNF failed to parse: {e}")))
44}
45
46fn xml_tool_calling_to_ebnf(schema: &str, format: JsonFormat) -> SchemaResult<String> {
49 let value = JsonValue::parse(schema)
50 .map_err(|e| SchemaError::invalid(format!("Failed to parse JSON schema: {e}")))?;
51 if value.as_bool().is_some() {
52 return Err(SchemaError::invalid(
53 "Expected JSON schema object, got boolean",
54 ));
55 }
56 match value.get("type").and_then(JsonValue::as_str) {
57 Some("object") => {}
58 _ => {
59 return Err(SchemaError::invalid(
60 "Function calling must have a 'type' field of 'object'",
61 ));
62 }
63 }
64 let options = SchemaConverterOptions {
65 json_format: format,
66 ..SchemaConverterOptions::default()
67 };
68 json_value_to_ebnf(&value, &options)
69}
70
71pub fn qwen_xml_tool_calling_to_ebnf(schema: &str) -> SchemaResult<String> {
74 xml_tool_calling_to_ebnf(schema, JsonFormat::QwenXml)
75}
76
77pub fn minimax_xml_tool_calling_to_ebnf(schema: &str) -> SchemaResult<String> {
80 xml_tool_calling_to_ebnf(schema, JsonFormat::MiniMaxXml)
81}
82
83pub fn deepseek_xml_tool_calling_to_ebnf(schema: &str) -> SchemaResult<String> {
86 xml_tool_calling_to_ebnf(schema, JsonFormat::DeepSeekXml)
87}
88
89pub fn builtin_json_grammar_ebnf() -> String {
96 json_schema_to_ebnf("{}", &SchemaConverterOptions::default()).unwrap_or_default()
98}
99
100pub fn builtin_json_grammar() -> SchemaResult<GrammarData> {
102 json_schema_to_grammar("{}", &SchemaConverterOptions::default())
103}