Overview
MaybeThinkParser is a flexible parser that extracts content after </think> tags if present, or returns the text unchanged if no think tags exist. This makes it suitable for models that may optionally include reasoning tags.
Class Signature
Parameters
Callable[[str], str]
default:"lambda x: x"
Optional extraction function to further process the parsed text. For example, you can use this to extract boxed answers from math problems.
Methods
parse
Extracts content after the last</think> tag, or returns the text unchanged.
str
required
The text to parse, potentially containing
<think>...</think> tags</think> tag if present, otherwise the original text. The result is passed through extract_fn if provided.
Behavior:
- If
</think>is found: Returns everything after the last</think>tag (stripped) - If
</think>is NOT found: Returns the original text unchanged (stripped) - Always applies the
extract_fnto the result
Usage Examples
Basic Usage with Think Tags
Basic Usage without Think Tags
With Custom Extraction Function
Parsing Message Completions
In a Math Rubric
Handling Edge Cases
When to Use MaybeThinkParser
UseMaybeThinkParser when:
- Your model may or may not include
<think>...</think>tags - You want flexible parsing that works with both reasoning and non-reasoning models
- You’re working with models that sometimes generate think tags (e.g., during fine-tuning)
- You need graceful handling when think tags are absent
Common Use Cases
Math Problem Solving
MaybeThinkParser is commonly used with math rubrics since it can handle both reasoning and direct answers:
Fine-tuning Scenarios
During fine-tuning, models may transition from always using think tags to using them selectively:See Also
- ThinkParser - For strict think tag enforcement
- Parser - Base parser class
- MathRubric - Uses MaybeThinkParser by default
- XMLParser - For XML-formatted responses