Last active
August 29, 2023 10:29
-
-
Save roxsross/e27806a97a19b2c0cd69fdaa0d1026ef to your computer and use it in GitHub Desktop.
Python automation with ChatGPT
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 characters
""" | |
Python automation with ChatGPT byRoxsRoss | |
### DEFINED VARIABLE OPENAI_API_KEY | |
export OPENAI_API_KEY=your-key-here | |
### GENERATE PYTHON CODE from Open AI | |
python3 chatgpt.py "leer version package.json" "script.py" | |
""" | |
import requests | |
import argparse | |
import os | |
parser = argparse.ArgumentParser() | |
parser.add_argument("prompt", help="Send prompt to OpenAI API") | |
parser.add_argument("file_name", help="Name Python script") | |
args = parser.parse_args() | |
api_endpoint = "https://api.openai.com/v1/completions" | |
api_key = os.getenv("OPENAI_API_KEY") | |
request_headers = { | |
"Content-Type": "application/json", | |
"Authorization": "Bearer " + api_key | |
} | |
request_data = { | |
"model": "text-davinci-003", | |
"prompt": f"Write python script to {args.prompt}. Provide only code, no text", | |
"max_tokens": 500, | |
"temperature": 0.5 | |
} | |
response = requests.post(api_endpoint, headers=request_headers, json=request_data) | |
if response.status_code == 200: | |
response_text = response.json()["choices"][0]["text"] | |
with open(args.file_name, "w") as file: | |
file.write(response_text) | |
else: | |
print(f"Request failed with status code: {str(response.status_code)}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
La API de OpenAI te devuelve el código Python en formato markdown, almenos con el modelo GPT-3.5, por lo que encapsula el código entre ```python y ```. Con una expresion regular puedes capturar todos los códigos python, e incluso guardar varios scripts con una sola consulta.