import json from pathlib import Path def json_string_to_py(json_text: str, output_file: str = "generated.py"): """ Convert an AI response containing: { "file_name": "...", "script": "..." } into a valid Python .py file. """ # Parse the JSON response data = json.loads(json_text) # Validate that the script exists if "script" not in data: raise ValueError("JSON does not contain a 'script' field.") script = data["script"] if not isinstance(script, str): raise TypeError("'script' must be a string.") # Write the Python source code exactly as provided output_path = Path("builders/" + output_file) output_path.write_text(script, encoding="utf-8") print(f"Created: {output_path.resolve()}") return output_path # Example usage if __name__ == "__main__": ai_response = r''' { "file_name": "small_oak_tree", "script": "import random\n\nSEED = 42\nrandom.seed(SEED)\n\nprint(\"Hello, World!\")" } ''' data = json.loads(ai_response) # Prefer the AI-provided filename filename = data.get("file_name", "generated") output_file = f"{filename}.py" json_string_to_py(ai_response, output_file)