Skip to content

Instantly share code, notes, and snippets.

@jstarcher
Created August 1, 2024 00:27
Show Gist options
  • Save jstarcher/c44c278f3b25e3af3d0d375a64e88480 to your computer and use it in GitHub Desktop.
Save jstarcher/c44c278f3b25e3af3d0d375a64e88480 to your computer and use it in GitHub Desktop.
ChatGPT loop
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment