Skip to content

Instantly share code, notes, and snippets.

@roxsross
Last active August 29, 2023 10:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save roxsross/e27806a97a19b2c0cd69fdaa0d1026ef to your computer and use it in GitHub Desktop.
Save roxsross/e27806a97a19b2c0cd69fdaa0d1026ef to your computer and use it in GitHub Desktop.
Python automation with ChatGPT
"""
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)}")
@kn0wm4d
Copy link

kn0wm4d commented Jul 12, 2023

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.

import requests
import argparse
import os
import re

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": "gpt-3.5-turbo",
    "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"]
    if '```python' in response_text:
        matches = re.findall(r'```python(.*?)```', response_text, re.DOTALL)
        for n, python_code in enumerate(matches):
            if n > 1:
                open(args.file_name + '_' + str(n) + '.py', "w").write(python_code)
            else:
                open(args.file_name + '.py', "w").write(python_code)
    else:
        with open(args.file_name + '.py', "w") as file:
            file.write(response_text)
else:
    print(f"Request failed with status code: {str(response.status_code)}")

@roxsross
Copy link
Author

gracias por el aporte @kn0wm4d

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment