huggingface/smolagents · error · ValueError

The JSON blob you used is invalid due to the following error

Error message

The JSON blob you used is invalid due to the following error: {e}.\nJSON blob was: {json_blob}, decoding failed on that specific part of the blob:\n'{json_blob[place - 4 : place + 5]}'.

What it means

The generic JSON-decode failure branch of parse_json_blob: the extracted blob is not valid JSON. The message embeds the json.JSONDecodeError, the full blob, and a 9-character window around the failing position to pinpoint the syntax error.

Source

Thrown at src/smolagents/utils.py:182


def parse_json_blob(json_blob: str) -> tuple[dict[str, str], str]:
    "Extracts the JSON blob from the input and returns the JSON data and the rest of the input."
    try:
        first_accolade_index = json_blob.find("{")
        last_accolade_index = [a.start() for a in list(re.finditer("}", json_blob))][-1]
        json_str = json_blob[first_accolade_index : last_accolade_index + 1]
        json_data = json.loads(json_str, strict=False)
        return json_data, json_blob[:first_accolade_index]
    except IndexError:
        raise ValueError("The model output does not contain any JSON blob.")
    except json.JSONDecodeError as e:
        place = e.pos
        if json_blob[place - 1 : place + 2] == "},\n":
            raise ValueError(
                "JSON is invalid: you probably tried to provide multiple tool calls in one action. PROVIDE ONLY ONE TOOL CALL."
            )
        raise ValueError(
            f"The JSON blob you used is invalid due to the following error: {e}.\n"
            f"JSON blob was: {json_blob}, decoding failed on that specific part of the blob:\n"
            f"'{json_blob[place - 4 : place + 5]}'."
        )


def extract_code_from_text(text: str, code_block_tags: tuple[str, str]) -> str | None:
    """Extract code from the LLM's output."""
    pattern = rf"{code_block_tags[0]}(.*?){code_block_tags[1]}"
    matches = re.findall(pattern, text, re.DOTALL)
    if matches:
        return "\n\n".join(match.strip() for match in matches)
    return None


def parse_code_blobs(text: str, code_block_tags: tuple[str, str]) -> str:
    """Extract code blocs from the LLM's output.

View on GitHub (pinned to 30bb116109)

Solutions

  1. Feed the error back to the model and retry the step (agent loop does this automatically)
  2. Switch to or configure a model that reliably emits JSON, or use native function-calling models (e.g. OpenAIServerModel with tool calling)
  3. Sanitize common issues (single quotes, Python literals) in a pre-parse hook if you control the text
  4. Increase max_tokens to avoid truncated JSON

Example fix

# before (model output)
{'name': 'search', 'arguments': {'q': 'cats'}}  # single quotes

# after
{"name": "search", "arguments": {"q": "cats"}}
Defensive patterns

Strategy: retry

Validate before calling

import json, re
def try_parse_action(text):
    m = re.search(r'\{.*\}', text, re.DOTALL)
    if not m:
        return None
    try:
        return json.loads(m.group(0))
    except json.JSONDecodeError:
        return None  # trigger retry instead of crashing

Type guard

def is_valid_model_json(text: str) -> bool:
    import json, re
    m = re.search(r'\{.*\}', text, re.DOTALL)
    if not m:
        return False
    try:
        json.loads(m.group(0))
        return True
    except json.JSONDecodeError:
        return False

Try / catch

try:
    data, _ = parse_json_blob(text)
except ValueError as e:
    # message contains position context; log blob excerpt and retry the model step
    raise

Prevention

When it happens

Trigger: Model emits malformed JSON: unescaped quotes/newlines inside strings, trailing commas, Python-style True/None/single quotes, or braces in prose being captured into the blob because parsing takes first '{' to last '}'.

Common situations: Models writing Python dict literals instead of JSON; code or prose containing extra '}' after the JSON causing weird slicing; strict=False only relaxes control characters, not structural errors.

Related errors


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