This is where we ask the question: Just because you can do it, should you do it? The likely answer to this question in this case is “No” because the following script uses the Python exec() function and it just assumes that ChatGPT is writing proper and ethical code.
However, I because I am a good chat bot…
9_9
Here’s the code.
import asyncio
import os
import openai
from dotenv import load_dotenv
# Get environment variables
load_dotenv()
openai.api_type = "azure"
openai.api_base = os.getenv("OPENAI_API_BASE")
openai.api_version = "2022-12-01"
openai.api_key = os.getenv("OPENAI_API_KEY")
async def main():
response = openai.Completion.create(
engine="gpt-35-turbo-0301",
prompt=f"<|im_start|>system\nYou are a Python developer.\n<|im_end|>\n<|im_start|>user\nWrite a short Python script that prints the words Hello World! Don't explain the code. Don't put the code in a code block.\n\n<|im_end|>\n<|im_start|>assistant",
temperature=1,
max_tokens=4000,
top_p=0.5,
frequency_penalty=0,
presence_penalty=0,
stop=None)
# I haven't figured out why this is in the response yet
# So I just remove it from the string
code = str.replace(response['choices'][0]['text'],"<|im_end|>","")
# Print the code so you can see it before you run it.
print(code)
# Ask if you want to save the code to a file
save = input("Save the code to a file? (y/n): ")
if save == "n":
return
#Save the code to a Python file
with open("hello_world.py", mode="w", encoding="utf-8") as hello:
hello.write(code)
# Ask if you want to run the code
run = input("Run the code? (y/n): ")
if run == "n":
return
# Run the code
with open("hello_world.py", mode="r", encoding="utf-8") as hello:
code = hello.read()
exec(code)
if __name__ == '__main__':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())
P.S. In case you are wondering why I always use async, it is because I sometimes use Azure API long running operations and it is just easier for me to assume that even though a script may not use it now, when I iterate on it, it probably will. So I leave it in there.