{"record":{"id":"e20b7e6d32dd29a8","repo":"huggingface/smolagents","slug":"your-code-snippet-is-invalid-because-the-regex-pa","errorCode":null,"errorMessage":"Your code snippet is invalid, because the regex pattern {code_block_tags[0]}(.*?){code_block_tags[1]} was not found in it.\nHere is your code snippet:\n{text}\nIt seems like you're trying to return the final answer, you can do it as follows:\n{code_block_tags[0]}\nfinal_answer(\"YOUR FINAL ANSWER HERE\")\n{code_block_tags[1]}","messagePattern":"Your code snippet is invalid, because the regex pattern (.+?)\\(\\.\\*\\?\\)(.+?) was not found in it\\.\nHere is your code snippet:\n(.+?)\nIt seems like you're trying to return the final answer, you can do it as follows:\n(.+?)\nfinal_answer\\(\"YOUR FINAL ANSWER HERE\"\\)\n(.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/smolagents/utils.py","lineNumber":225,"sourceCode":"        `str`: Extracted code block.\n\n    Raises:\n        ValueError: If no valid code block is found in the text.\n    \"\"\"\n    matches = extract_code_from_text(text, code_block_tags)\n    if not matches:  # Fallback to markdown pattern\n        matches = extract_code_from_text(text, (\"```(?:python|py)\", \"\\n```\"))\n    if matches:\n        return matches\n    # Maybe the LLM outputted a code blob directly\n    try:\n        ast.parse(text)\n        return text\n    except SyntaxError:\n        pass\n\n    if \"final\" in text and \"answer\" in text:\n        raise ValueError(\n            dedent(\n                f\"\"\"\n                Your code snippet is invalid, because the regex pattern {code_block_tags[0]}(.*?){code_block_tags[1]} was not found in it.\n                Here is your code snippet:\n                {text}\n                It seems like you're trying to return the final answer, you can do it as follows:\n                {code_block_tags[0]}\n                final_answer(\"YOUR FINAL ANSWER HERE\")\n                {code_block_tags[1]}\n                \"\"\"\n            ).strip()\n        )\n    raise ValueError(\n        dedent(\n            f\"\"\"\n            Your code snippet is invalid, because the regex pattern {code_block_tags[0]}(.*?){code_block_tags[1]} was not found in it.\n            Here is your code snippet:\n            {text}","sourceCodeStart":207,"sourceCodeEnd":243,"githubUrl":"https://github.com/huggingface/smolagents/blob/30bb1161095dbae2271e6bc3cc4c219cc3897a57/src/smolagents/utils.py#L207-L243","documentation":"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.","triggerScenarios":"A CodeAgent model writes 'final answer: ...' as plain text without a fenced code block containing final_answer(...); the code-block regex finds nothing.","commonSituations":"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.","solutions":["Feed the error back to the model and retry (its message includes the exact correct pattern)","Use a model/prompt template that reliably emits ```python blocks","Explicitly instruct in the task or system prompt that final answers must use final_answer(...) in a code block"],"exampleFix":"# before (model output)\nThought: I'm done.\nFinal answer: 42\n\n# after\nThought: I'm done.\n```python\nfinal_answer(\"42\")\n```","handlingStrategy":"retry","validationCode":"import re\ndef has_final_answer_block(text: str, tags=('```python', '```')) -> bool:\n    return bool(re.search(re.escape(tags[0]) + r'(.*?)' + re.escape(tags[1]), text, re.DOTALL)) or 'final_answer(' in text","typeGuard":"def is_valid_code_agent_output(text: str) -> bool:\n    import ast, re\n    try:\n        ast.parse(text)\n        return True\n    except SyntaxError:\n        return bool(re.search(r'```\\w*\\n.*?```', text, re.DOTALL))","tryCatchPattern":"try:\n    code = parse_code_blobs(text)\nexcept ValueError as e:\n    # message contains the correct pattern; return it to the model and retry the step\n    raise","preventionTips":["Use smolagents' CodeAgent prompt templates unmodified","Test your model with a simple task first to verify format compliance","Instruct: 'always put code in ```python blocks and use final_answer(...)'"],"tags":["smolagents","code-agent","llm-output-parsing","prompt-format"],"backgroundTag":"invalid-model-code-block","analyzedSha":"30bb1161095dbae2271e6bc3cc4c219cc3897a57","analyzedAt":"2026-08-28T18:52:54.169Z","schemaVersion":2},"datasetVersion":"2026-08-28T21:17:43.275Z"}