Created
August 1, 2024 00:27
-
-
Save jstarcher/c44c278f3b25e3af3d0d375a64e88480 to your computer and use it in GitHub Desktop.
Revisions
-
jstarcher created this gist
Aug 1, 2024 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,56 @@ import openai import subprocess # Set your OpenAI API key openai.api_key = 'your_openai_api_key' def generate_code(prompt): response = openai.Completion.create( engine="text-davinci-003", prompt=prompt, max_tokens=150, n=1, stop=None, temperature=0.5 ) return response.choices[0].text.strip() def run_tests(file_path): try: result = subprocess.run(['python', file_path], capture_output=True, text=True) return result.stdout, result.stderr except Exception as e: return '', str(e) def correct_code(prompt): return generate_code(prompt) def main(): initial_prompt = "Write a Python function to add two numbers." iteration = 0 max_iterations = 10 while iteration < max_iterations: iteration += 1 print(f"Iteration {iteration}") code = generate_code(initial_prompt) print(f"Generated Code:\n{code}") file_path = 'generated_code.py' with open(file_path, 'w') as f: f.write(code) stdout, stderr = run_tests(file_path) if stderr: print(f"Error:\n{stderr}") new_prompt = f"The following code produced an error:\n{code}\nError: {stderr}\nPlease correct the code." initial_prompt = new_prompt else: print("Code executed successfully.") print(f"Output:\n{stdout}") break if __name__ == "__main__": main()