@@ -173,14 +173,18 @@ def serialize_guidance_grammar(
173
173
disable_any_whitespace : bool = False ,
174
174
no_additional_properties : bool = False ,
175
175
) -> str :
176
- if request_type == StructuredOutputOptions .JSON :
176
+
177
+ def _process_schema (grammar_spec : Union [str , dict [str , Any ]], ) -> str :
177
178
if no_additional_properties :
178
179
grammar_spec = process_for_additional_properties (grammar_spec )
179
180
return llguidance .LLMatcher .grammar_from_json_schema (
180
181
grammar_spec ,
181
182
defaults = {
182
183
"whitespace_flexible" : not disable_any_whitespace ,
183
184
})
185
+
186
+ if request_type == StructuredOutputOptions .JSON :
187
+ return _process_schema (grammar_spec )
184
188
elif request_type == StructuredOutputOptions .JSON_OBJECT :
185
189
return llguidance .LLMatcher .grammar_from_json_schema (
186
190
'{"type": "object"}' ,
@@ -195,8 +199,29 @@ def serialize_guidance_grammar(
195
199
elif request_type == StructuredOutputOptions .CHOICE :
196
200
tp = "choice"
197
201
elif request_type == StructuredOutputOptions .STRUCTURAL_TAG :
198
- raise ValueError ("Structural tag is not supported "
199
- "for guidance backend yet" )
202
+ if isinstance (grammar_spec , str ):
203
+ s_tag = json .loads (grammar_spec )
204
+ else :
205
+ s_tag = grammar_spec
206
+ triggers : list [str ] = s_tag ["triggers" ]
207
+ tags : list [llguidance .StructTag ] = []
208
+ for s in s_tag ["structures" ]:
209
+ begin : str = s ["begin" ]
210
+ trig = next ((t for t in triggers if begin .startswith (t )), None )
211
+ if trig is None :
212
+ raise ValueError (
213
+ f"Trigger { begin } not found in triggers { triggers } " )
214
+ tags .append (
215
+ llguidance .StructTag (
216
+ trigger = trig ,
217
+ begin = s ["begin" ],
218
+ grammar = _process_schema (s ["schema" ]),
219
+ end = s ["end" ],
220
+ ))
221
+ if not tags :
222
+ raise ValueError (
223
+ "No structural tags found in the grammar spec." )
224
+ return llguidance .StructTag .to_grammar (tags )
200
225
else :
201
226
logger .error ("Validation should have already occurred. "
202
227
"Please file an issue." )
0 commit comments