Skip to main content

Overview

The Parser 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

Parse text using the configured extraction function.
str
The text to parse.
Returns: Result of applying extract_fn to the text.

parse_answer

Extract the answer from a completion.
Messages
Either a string or list of message dictionaries.
Returns: 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

Extract all assistant messages from a completion. Returns: List of messages with role="assistant".

get_system_messages

Extract all system messages from a completion. Returns: List of messages with role="system".

get_user_messages

Extract all user messages from a completion. Returns: List of messages with role="user".

get_tool_messages

Extract all tool messages from a completion. Returns: List of messages with role="tool".

get_format_reward_func

Return a reward function that validates format compliance. Returns: A reward function that returns 1.0 for any completion (base implementation always validates).
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