huggingface/smolagents · error · ValueError

Your code snippet is invalid, because the regex pattern {cod

Error message

Your code snippet is invalid, because the regex pattern {code_block_tags[0]}(.*?){code_block_tags[1]} was not found in it.
Here is your code snippet:
{text}
It seems like you're trying to return the final answer, you can do it as follows:
{code_block_tags[0]}
final_answer("YOUR FINAL ANSWER HERE")
{code_block_tags[1]}

What it means

In CodeAgent flows, parse_code_blobs first tries ast.parse on the whole text; on SyntaxError it looks for a code block between the language's code_block_tags (e.g. ```python ... ```). If the regex fails and the text mentions 'final' and 'answer', this error tells the user to wrap the final answer in final_answer(...) inside a proper code block.

Source

Thrown at src/smolagents/utils.py:225

        `str`: Extracted code block.

    Raises:
        ValueError: If no valid code block is found in the text.
    """
    matches = extract_code_from_text(text, code_block_tags)
    if not matches:  # Fallback to markdown pattern
        matches = extract_code_from_text(text, ("```(?:python|py)", "\n```"))
    if matches:
        return matches
    # Maybe the LLM outputted a code blob directly
    try:
        ast.parse(text)
        return text
    except SyntaxError:
        pass

    if "final" in text and "answer" in text:
        raise ValueError(
            dedent(
                f"""
                Your code snippet is invalid, because the regex pattern {code_block_tags[0]}(.*?){code_block_tags[1]} was not found in it.
                Here is your code snippet:
                {text}
                It seems like you're trying to return the final answer, you can do it as follows:
                {code_block_tags[0]}
                final_answer("YOUR FINAL ANSWER HERE")
                {code_block_tags[1]}
                """
            ).strip()
        )
    raise ValueError(
        dedent(
            f"""
            Your code snippet is invalid, because the regex pattern {code_block_tags[0]}(.*?){code_block_tags[1]} was not found in it.
            Here is your code snippet:
            {text}

View on GitHub (pinned to 30bb116109)

Solutions

  1. Feed the error back to the model and retry (its message includes the exact correct pattern)
  2. Use a model/prompt template that reliably emits ```python blocks
  3. Explicitly instruct in the task or system prompt that final answers must use final_answer(...) in a code block

Example fix

# before (model output)
Thought: I'm done.
Final answer: 42

# after
Thought: I'm done.
```python
final_answer("42")
```
Defensive patterns

Strategy: retry

Validate before calling

import re
def has_final_answer_block(text: str, tags=('```python', '```')) -> bool:
    return bool(re.search(re.escape(tags[0]) + r'(.*?)' + re.escape(tags[1]), text, re.DOTALL)) or 'final_answer(' in text

Type guard

def is_valid_code_agent_output(text: str) -> bool:
    import ast, re
    try:
        ast.parse(text)
        return True
    except SyntaxError:
        return bool(re.search(r'```\w*\n.*?```', text, re.DOTALL))

Try / catch

try:
    code = parse_code_blobs(text)
except ValueError as e:
    # message contains the correct pattern; return it to the model and retry the step
    raise

Prevention

When it happens

Trigger: A CodeAgent model writes 'final answer: ...' as plain text without a fenced code block containing final_answer(...); the code-block regex finds nothing.

Common situations: Small models skipping the code-block format; prompts where few-shot examples show plain-text final answers; using a chat model that ignores markdown fences.

Related errors


AI-assisted analysis of huggingface/smolagents@30bb116109 (2026-08-28). Data as JSON: /api/errors/e20b7e6d32dd29a8. Report an issue: GitHub.