Overview
XMLParser extends Parser to extract structured data from XML-tagged completions. It’s useful for prompts that request specific output formats like <reasoning>...</reasoning><answer>...</answer>.
Constructor
list[str | tuple[str, ...]]
List of field definitions. Each can be:
- A string: Fixed XML tag name (e.g.,
"reasoning") - A tuple: Multiple allowed tag names with the first as canonical (e.g.,
("code", "answer"))
str
default:"answer"
Which field contains the final answer for
parse_answer().Callable[[str], str]
default:"lambda x: x"
Additional transformation applied to extracted field values.
Methods
parse
str
The text containing XML tags.
bool
default:"True"
Whether to strip whitespace from field values.
bool
default:"False"
If
True, extract the last occurrence of each tag. If False, extract the first.SimpleNamespace with attributes for each allowed field name. Missing fields are set to None.
parse_answer
Messages
String or list of messages.
None if not found.
format
Field values to format. Keys must match canonical or alternative field names.
ValueError if a required field is missing.
get_format_str
get_fields
get_format_reward_func
- Presence of expected fields (40% weight)
- Proper spacing (20%)
- Starting with first field (20%)
- Ending with last field (20%)
Attributes
str
The field name used for extracting answers.
Example Usage
Basic XML Parsing
Alternative Field Names
Extracting Answers from Messages
Formatting XML Output
Format Validation Reward
Using with Rubric
Last Occurrence Extraction
Complex Multi-Field Example
Error Handling
No Whitespace Stripping
Multi-turn Parsing
Format Reward Function Details
The format reward function scores completions based on:- Field presence (40%): Proportion of expected field sets present
- Proper spacing (20%): Tags have content between them (not just whitespace)
- Starts correctly (20%): Begins with first field’s opening tag
- Ends correctly (20%): Ends with last field’s closing tag
See Also
- Parser - Base parser class
- Rubric - Using parsers with rubrics
- MathRubric - Example with specialized parser