langchain-ai/langchain · error · ValueError

Could not extract Python code from Groq tool arguments. Expe

Error message

Could not extract Python code from Groq tool arguments. Expected a JSON object with a 'code' field.

What it means

Raised when langchain-core tries to recover Python source code from a Groq code-interpreter tool call and the argument string does not match the exact shape `{"code": "..."}`. Groq frequently emits unescaped quotes inside the code string, so the strict regex fullmatch (or JSON parsing) fails and the extractor gives up with this ValueError.

Source

Thrown at libs/core/langchain_core/messages/block_translators/groq.py:47

def _parse_code_json(s: str) -> dict[str, Any]:
    """Extract Python code from Groq built-in tool content.

    Extracts the value of the 'code' field from a string of the form:
    {"code": some_arbitrary_text_with_unescaped_quotes}

    As Groq may not escape quotes in the executed tools, e.g.:
    ```
    '{"code": "import math; print("The square root of 101 is: "); print(math.sqrt(101))"}'
    ```
    """  # noqa: E501
    m = re.fullmatch(r'\s*\{\s*"code"\s*:\s*"(.*)"\s*\}\s*', s, flags=re.DOTALL)
    if not m:
        msg = (
            "Could not extract Python code from Groq tool arguments. "
            "Expected a JSON object with a 'code' field."
        )
        raise ValueError(msg)
    return {"code": m.group(1)}


def _convert_to_v1_from_groq(message: AIMessage) -> list[types.ContentBlock]:
    """Convert groq message content to v1 format."""
    content_blocks: list[types.ContentBlock] = []

    if reasoning_block := _extract_reasoning_from_additional_kwargs(message):
        content_blocks.append(reasoning_block)

    if executed_tools := message.additional_kwargs.get("executed_tools"):
        for idx, executed_tool in enumerate(executed_tools):
            args: dict[str, Any] | None = None
            if arguments := executed_tool.get("arguments"):
                try:
                    args = json.loads(arguments)
                except json.JSONDecodeError:
                    if executed_tool.get("type") == "python":

View on GitHub (pinned to e32fa9a52e)

Solutions

  1. If you control the tool result, store the arguments as strict JSON: `json.dumps({"code": source})`
  2. Escape embedded quotes in the code string before passing it (or let json.dumps handle escaping)
  3. If you only need the raw string, bypass extraction and read the tool arguments directly instead of relying on the v1 block conversion
  4. Catch ValueError and fall back to `json.loads` with `strict=False` or a manual quote-repair pass

Example fix

# before
tool_args = '{"code": "import math; print("sqrt:", math.sqrt(101))"}'  # unescaped quotes -> ValueError

# after
import json
tool_args = json.dumps({"code": 'import math; print("sqrt:", math.sqrt(101))'})
Defensive patterns

Strategy: try-catch

Validate before calling

import re

def is_groq_code_arg(s: str) -> bool:
    return re.fullmatch(r'\s*\{\s*"code"\s*:\s*"(.*)"\s*\}\s*', s, flags=re.DOTALL) is not None

Try / catch

try:
    code = _extract_code(tool_args)
except ValueError:
    # fall back to lenient parsing or keep raw string
    code = tool_args

Prevention

When it happens

Trigger: Converting an AIMessage that has `additional_kwargs['executed_tools']` entries whose `code` argument contains unescaped quotes/newlines (e.g. `print("hello")`), or tool arguments that are not a single JSON object with a 'code' field at all (multi-key JSON, plain code string, truncated payload).

Common situations: Using Groq models with a code-interpreter/executed-tools flow where the generated code embeds string literals; replaying or serializing Groq tool results that were truncated; model output that wraps code differently than expected.

Related errors


AI-assisted analysis of langchain-ai/langchain@e32fa9a52e (2026-08-14). Data as JSON: /api/errors/99eda60398ee7505. Report an issue: GitHub.