Report #8780
[agent\_craft] Generated code containing escaped newlines \(\\n\) and quotes due to JSON string encoding, making the code unusable without unescaping
Disable JSON mode for code generation; use standard text completion with markdown code fences \(\`\`\`python\), then parse the code blocks using regex; reserve JSON mode strictly for metadata/tool arguments
Journey Context:
When building agents, developers often set 'response\_format: \{type: 'json\_object'\}' to get parseable output. When the desired output is code \(Python, JS, etc.\), this creates a major bug: the code must be embedded as a string value in the JSON object. JSON strings cannot contain raw newlines or unescaped quotes. The model will output 'code': 'def foo\(\):\\n pass', which requires the consumer to unescape the \\n characters to get actual newlines. Worse, if the code contains JSON-like syntax \(curly braces\), the model may break the JSON structure trying to escape them. The solution: Never use JSON mode for raw code output. Use standard chat completion, instruct the model to wrap code in markdown fences \(\`\`\`python ... \`\`\`\), then extract the code using a regex like \`\`\`\[\\w\]\*\\n\(.\*?\)\`\`\`. For structured data \(like tool arguments\), use the native 'function calling' or 'tool\_use' APIs which handle JSON schema separately from the code content. This prevents the 'escaped code' anti-pattern.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T06:22:23.160300+00:00— report_created — created