huggingface/smolagents · error · AgentParsingError

Error in code parsing

Error message

Error in code parsing:
{e}
Make sure to provide correct code blobs.

What it means

After generation, CodeAgent._step_stream extracts executable Python from the model output — via json.loads for structured outputs or parse_code_blobs for tagged code blocks — and wraps any failure in AgentParsingError with guidance to provide correct code blobs. It means the model's textual output was not in the expected code format.

Solutions

  1. Ensure your prompt templates instruct code in the same tags configured via code_block_tags (use 'markdown' with the default code-agent.yaml templates).
  2. Retry the run — the parsing error is fed back and models usually correct the format.
  3. Use a stronger model or enable structured outputs so the code field is guaranteed.

Example fix

# before
agent = CodeAgent(model=weak_model, tools=[], code_block_tags='markdown')
# weak model outputs plain prose -> AgentParsingError

# after
agent = CodeAgent(model=stronger_model, tools=[], code_block_tags='markdown')
# or retry loop:
from smolagents.exceptions import AgentParsingError
for _ in range(3):
    try:
        result = agent.run(task); break
    except AgentParsingError:
        continue
Defensive patterns

Strategy: retry

Try / catch

from smolagents.exceptions import AgentParsingError

for attempt in range(3):
    try:
        result = agent.run(task)
        break
    except AgentParsingError as e:
        if 'code parsing' not in str(e):
            raise
        if attempt == 2:
            raise

Prevention

When it happens

Trigger: The model returns prose or malformed code blocks so parse_code_blobs finds no valid code between the configured tags; or with structured outputs, output_text is not valid JSON with a 'code' key.

Common situations: Small/local models ignoring the code-format prompt; code_block_tags mismatch between what the prompt tells the model and what the parser looks for; custom prompt templates that don't instruct ```python fencing when tags are 'markdown'.

Related errors


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

Appendix: source

Thrown at src/smolagents/agents.py:1713

                    memory_step.model_output_message.content = output_text

            memory_step.token_usage = chat_message.token_usage
            memory_step.model_output = output_text
        except Exception as e:
            raise AgentGenerationError(f"Error in generating model output:\n{e}", self.logger) from e

        ### Parse output ###
        try:
            if self._use_structured_outputs_internally:
                code_action = json.loads(output_text)["code"]
                code_action = extract_code_from_text(code_action, self.code_block_tags) or code_action
            else:
                code_action = parse_code_blobs(output_text, self.code_block_tags)
            code_action = fix_final_answer_code(code_action)
            memory_step.code_action = code_action
        except Exception as e:
            error_msg = f"Error in code parsing:\n{e}\nMake sure to provide correct code blobs."
            raise AgentParsingError(error_msg, self.logger)

        tool_call = ToolCall(
            name="python_interpreter",
            arguments=code_action,
            id=f"call_{len(self.memory.steps)}",
        )
        yield tool_call
        memory_step.tool_calls = [tool_call]

        ### Execute action ###
        self.logger.log_code(title="Executing parsed code:", content=code_action, level=LogLevel.INFO)
        try:
            code_output = self.python_executor(code_action)
            execution_outputs_console = []
            if len(code_output.logs) > 0:
                execution_outputs_console += [
                    Text("Execution logs:", style="bold"),
                    Text(code_output.logs),

View on GitHub (pinned to 30bb116109)