How to run code received from ChatGPT
There was an interesting discussion in the AIA community about different ways to execute code received from LLMs like ChatGPT. Of course, the best solution is provided by OpenAI. But what if someone is brave and curious enough to try a more advanced method? Actually, it's really simple. The only thing you need is Python!
Here is a Python snippet that utilises the OpenAI API key and sends a request to the gpt-3.5-turbo model (the cheapest one). If there is Python code in the ChatGPT response, it will be extracted and printed out, and you will be asked whether to run the code or not. It's a really good idea to check the code first, as it might not be safe to run immediately.
Yes, apart from OpenAI API key you would need to double check that requests library does exist in your environment and if not just do `pip install requests`
import requests
import os
import re
def get_user_question():
question = input("Enter your question: ")
return question
def send_api_request(question):
api_key=os.environ["OPENAI_API_KEY"]
if api_key is None:
raise ValueError("API_KEY didn't found in environment variables")
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json'
}
data = {"model": "gpt-3.5-turbo",
"temperature": 0.7,
"messages": [{"role": "system", "content": ""},
{"role": "user", "content": question}]}
response = requests.post("https://api.openai.com/v1/chat/completions", json=data, headers=headers)
response.raise_for_status()
return response.json()["choices"][0]["message"]["content"]
def extract_python_code(api_response):
if "```python" not in api_response:
return "" # code wan't found in the response
pattern = r"```python(.*?)```"
matches = re.findall(pattern, api_response, re.DOTALL)
return "\n".join(matches)
def execute_code(code_to_execute):
if input("Run the code? y/n ") == "y":
print()
exec(code_to_execute)
def main():
# try:
question = get_user_question()
api_response = send_api_request(question)
python_code = extract_python_code(api_response)
if python_code:
print("Generated code:")
print(python_code, end="\n\n")
execute_code(python_code)
else:
print("\nThere is no code in the response.\n\nResponse:")
print(api_response)
if __name__ == "__main__":
main()
p.s.: instead of loading API key from environment variables as it's suggested by OpenAI and implemented in the code snippet, it's possible to write like that:
领英推荐
api_key="sk-abcdefghijklmnopqrstuvwxyz123456"
Also, you might want to use a more advanced model instead of gpt-3.5-turbo. Feel free to change it! Here are some examples:
"model": "gpt-3.5-turbo"
"model": "gpt-4-turbo"
"model": "gpt-4o"
Senior Managing Director
4 个月Aleksandr Duk Very interesting. Thank you for sharing