{"record":{"id":"99eda60398ee7505","repo":"langchain-ai/langchain","slug":"could-not-extract-python-code-from-groq-tool-argum","errorCode":null,"errorMessage":"Could not extract Python code from Groq tool arguments. Expected a JSON object with a 'code' field.","messagePattern":"Could not extract Python code from Groq tool arguments\\. Expected a JSON object with a 'code' field\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"libs/core/langchain_core/messages/block_translators/groq.py","lineNumber":47,"sourceCode":"\ndef _parse_code_json(s: str) -> dict[str, Any]:\n    \"\"\"Extract Python code from Groq built-in tool content.\n\n    Extracts the value of the 'code' field from a string of the form:\n    {\"code\": some_arbitrary_text_with_unescaped_quotes}\n\n    As Groq may not escape quotes in the executed tools, e.g.:\n    ```\n    '{\"code\": \"import math; print(\"The square root of 101 is: \"); print(math.sqrt(101))\"}'\n    ```\n    \"\"\"  # noqa: E501\n    m = re.fullmatch(r'\\s*\\{\\s*\"code\"\\s*:\\s*\"(.*)\"\\s*\\}\\s*', s, flags=re.DOTALL)\n    if not m:\n        msg = (\n            \"Could not extract Python code from Groq tool arguments. \"\n            \"Expected a JSON object with a 'code' field.\"\n        )\n        raise ValueError(msg)\n    return {\"code\": m.group(1)}\n\n\ndef _convert_to_v1_from_groq(message: AIMessage) -> list[types.ContentBlock]:\n    \"\"\"Convert groq message content to v1 format.\"\"\"\n    content_blocks: list[types.ContentBlock] = []\n\n    if reasoning_block := _extract_reasoning_from_additional_kwargs(message):\n        content_blocks.append(reasoning_block)\n\n    if executed_tools := message.additional_kwargs.get(\"executed_tools\"):\n        for idx, executed_tool in enumerate(executed_tools):\n            args: dict[str, Any] | None = None\n            if arguments := executed_tool.get(\"arguments\"):\n                try:\n                    args = json.loads(arguments)\n                except json.JSONDecodeError:\n                    if executed_tool.get(\"type\") == \"python\":","sourceCodeStart":29,"sourceCodeEnd":65,"githubUrl":"https://github.com/langchain-ai/langchain/blob/e32fa9a52eab3b61ad7a45399bfde59b3e580fc4/libs/core/langchain_core/messages/block_translators/groq.py#L29-L65","documentation":"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.","triggerScenarios":"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).","commonSituations":"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.","solutions":["If you control the tool result, store the arguments as strict JSON: `json.dumps({\"code\": source})`","Escape embedded quotes in the code string before passing it (or let json.dumps handle escaping)","If you only need the raw string, bypass extraction and read the tool arguments directly instead of relying on the v1 block conversion","Catch ValueError and fall back to `json.loads` with `strict=False` or a manual quote-repair pass"],"exampleFix":"# before\ntool_args = '{\"code\": \"import math; print(\"sqrt:\", math.sqrt(101))\"}'  # unescaped quotes -> ValueError\n\n# after\nimport json\ntool_args = json.dumps({\"code\": 'import math; print(\"sqrt:\", math.sqrt(101))'})","handlingStrategy":"try-catch","validationCode":"import re\n\ndef is_groq_code_arg(s: str) -> bool:\n    return re.fullmatch(r'\\s*\\{\\s*\"code\"\\s*:\\s*\"(.*)\"\\s*\\}\\s*', s, flags=re.DOTALL) is not None","typeGuard":null,"tryCatchPattern":"try:\n    code = _extract_code(tool_args)\nexcept ValueError:\n    # fall back to lenient parsing or keep raw string\n    code = tool_args","preventionTips":["Serialize executed-tool arguments with json.dumps so quotes are escaped","Keep tool argument payloads as strict JSON objects with a single 'code' key","Don't hand-edit or re-template the JSON string produced by Groq"],"tags":["groq","tool-calls","code-interpreter","json-parsing"],"backgroundTag":null,"analyzedSha":"e32fa9a52eab3b61ad7a45399bfde59b3e580fc4","analyzedAt":"2026-08-14T18:42:09.092Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}