Skip to main content

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.
Do NOT include "think" in fields for models like Qwen3 or DeepSeek-R1 that auto-parse thinking tags. This will cause parsing failures.

Methods

parse

Parse XML tags from text and return a namespace object with attributes for each field.
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.
Returns: SimpleNamespace with attributes for each allowed field name. Missing fields are set to None.

parse_answer

Extract the answer field from the last assistant message containing it.
Messages
String or list of messages.
Returns: Content of the answer field, or None if not found.

format

Format keyword arguments into an XML string using canonical field names.
Field values to format. Keys must match canonical or alternative field names.
Returns: XML-formatted string. Raises: ValueError if a required field is missing.

get_format_str

Get a description of the expected XML format. Returns: String showing the XML structure with field names.

get_fields

Get the list of canonical field names. Returns: List of field names in order.

get_format_reward_func

Create a reward function that checks format compliance. Returns: Function that scores completions based on:
  • 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.
All attributes from Parser are also available.

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:
  1. Field presence (40%): Proportion of expected field sets present
  2. Proper spacing (20%): Tags have content between them (not just whitespace)
  3. Starts correctly (20%): Begins with first field’s opening tag
  4. Ends correctly (20%): Ends with last field’s closing tag
Partial credit is given for partial compliance.

See Also