Overview
TheParser class provides the foundation for extracting answers from LLM completions. It handles both string and message-based completions and can be customized with extraction functions.
Constructor
Callable[[str], str]
default:"lambda x: x"
Function to extract or transform text. Applied to content after extraction from messages.
Methods
parse
str
The text to parse.
extract_fn to the text.
parse_answer
Messages
Either a string or list of message dictionaries.
str | None - Parsed answer from the last assistant message, or None if no assistant messages exist.
For string completions, applies
parse() directly. For message lists, extracts the last assistant message’s content and then parses it.Helper Methods
These methods help extract specific message types from completions:get_assistant_messages
role="assistant".
get_system_messages
role="system".
get_user_messages
role="user".
get_tool_messages
role="tool".
get_format_reward_func
Subclasses like
XMLParser override this to provide actual format checking.Attributes
Callable[[str], str]
The extraction function applied during parsing.
logging.Logger
Logger instance for the parser.
Example Usage
Basic String Parsing
Custom Extraction Function
Extracting Boxed Answers
Parsing Message Completions
Extracting Specific Message Types
Multimodal Content
Using in a Reward Function
Custom Parser Subclass
Message Format Compatibility
The parser handles both dictionary and object message formats:Edge Cases
See Also
- XMLParser - Structured XML parsing
- Rubric - Using parsers with rubrics
- MathRubric - Example with custom parser