Created
April 15, 2023 19:52
-
-
Save peteralcock/67c90756c22b4d0a60cfc0a68a5ea0ad to your computer and use it in GitHub Desktop.
pyai.py
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
| #!/usr/bin/python3 | |
| import openai | |
| import sys | |
| openai.api_key = 'sk-xxx' | |
| verbose = sys.argv[1] == '-v' | |
| prompt = ' '.join(sys.argv[2 if verbose else 1:]) | |
| resp = openai.ChatCompletion.create( | |
| model="gpt-3.5-turbo", | |
| messages=[ | |
| {"role": "system", "content": "You are Python code generator. Answer with just the Python code."}, | |
| {"role": "user", "content": prompt}, | |
| ] | |
| ) | |
| data = resp['choices'][0]['message']['content'] | |
| if verbose: print(data, 'Usage was:', resp['usage'], sep='\n') | |
| # Extract lines of code from the response tagged with ``` or ```python | |
| lines = [] | |
| ok_start = ['```', '```python', '```py', '```python3', '```py3'] | |
| started = False | |
| for line in data.splitlines(): | |
| if not started: | |
| if line.strip() in ok_start: | |
| started = True | |
| else: | |
| if line.strip() == '```': break | |
| lines.append(line) | |
| # If no lines were extracted, assume whole response is code | |
| if not started: lines = data.splitlines() | |
| import os | |
| import tempfile | |
| # Create a temporary file | |
| with tempfile.NamedTemporaryFile(mode='w', delete=False) as tf: | |
| tf.write("#!/usr/bin/env python3\n") | |
| # Write lines to the file | |
| for line in lines: | |
| tf.write(line + '\n') | |
| # Make the file executable | |
| os.chmod(tf.name, 0o755) | |
| # Run the file with python3 | |
| os.system(tf.name) | |
| # Delete the file | |
| os.unlink(tf.name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment