gpt-3 python write code

GPT-3 and its forms have taken the world by storm and for good reason. It’s an exciting time full of possibilities. The limits are being pushed every day. Python as an SEO skill has always been a bit niche due to some learning curve. Today, we start blowing that learning curve out of the water!

In what may be my last tutorial, I’m going to show you in less than 20 lines of code how to use GPT-3 prompts to build your own scripts and run them automatically. This like most of my tutorials is barebones and can be the foundation for auto-generation and execution of tasks via Python using GPT-3 prompts.

Disclaimer: the prompts are best left for data analysis and generally harmless processes. Trying to modify something on your machine, not a great idea, might nuke your machine. Trying to connect to a database, not a good idea, you can nuke your database. If you are doing something even moderately risky you can build in guard rails. For example, after getting the code response from GPT-3 search the code programmatically for risky modules and functions, and then abort if found, etc.

Here is our basic challenge for the tutorials. Let’s say I have a CSV file named keywords.csv and inside contains the data below. We simply want to sort that data by descending rank. This is a simple start, but just imagine the possibilities you can come up with. A small caveat, guess what, it won’t always work. It depends on how well you write your prompt and some trial and error.

name  rank
sarah  4
pan    22
bert   1
andy   5
greg   3

Let’s first start by installing the OpenAI module. Remember if you’re using a notebook, include an exclamation mark at the beginning.

pip3 install openai

Now we import the libraries we’ll need to start the script.

  • os: to help us write and open the Python file we’re going to dynamically create
  • openai: to communicate with the GPT-3 API
  • Popen: to open the Python file we created and execute it within the same script
import os
import openai
from subprocess import Popen

This chunk is 100% boilerplate OpenAI API code with default parameters that you’ll likely not need to adjust much. Enter your API key at the top. Then an object is created that includes:

  • model: there are several to choose from but “text-davinci-003” is the newest and generally best
  • prompt: this is the directions you give the model. As you can see I plainly explain what I want the code to do that GPT-3 will generate.
  • temperature: the temperature controls how much randomness is in the output.
  • max_tokens: this is essentially the max word count you want back. For longer scripts, you’ll need to adjust this higher.
  • top_p: another dial for controlling the randomness and creativity.
  • frequency_penalty: allow you to control the level of repetition
  • presence_penalty: allow you to control the level of repetition
openai.api_key=""

response = openai.Completion.create(
  model="text-davinci-003",
  prompt="write me python code that opens a csv file named \"/path/filename.csv\", imports the data into a pandas dataframe and then sorts the data by the column named \"rank\" in descending order and prints the dataframe",
  temperature=0.7,
  max_tokens=256,
  top_p=1,
  frequency_penalty=0,
  presence_penalty=0
)

So the API request has been made and we’ve been sent back the response which should be the code. If you are debugging, feel free to print out the response to make sure it’s what you want and expect. Next, we create the contents for the Python file we’re going to create using the code from GPT-3. This will include the shebang at the top which tells the computer what to use for execution and then we append the GPT-3 provided code.

text = "#!/usr/bin/python3 " + " \n\n " + response['choices'][0]['text']

Just for kicks, the GPT-3 code response from my above API call is below and it’s correct!

import pandas as pd 

csv_file = '/home/greg/Downloads/keywords.csv'
df = pd.read_csv(csv_file)
df.sort_values('rank', ascending=False, inplace=True)
df

We then create a new Python file and write the contents we just created into it. You’ll need to change the path for the environment you’re working in and think of a filename. Lastly here we give the new file execution permissions.

with open('/path/filename.py', 'w') as file:
    file.write(text)

os.chmod('/path/filename.py',0o777)

Finally, we have our new Python file created from the GPT-3 prompt response. The only thing left to do is open and run the file.

Popen('/path/filename.py')

Here is the output. Remember we had a small CSV with some data and we wanted to sort it by rank ascending and display the dataframe. Simple, but magic. Just think of the possibilities.

name  rank
pan    22
andy   5
sarah  4
greg   3
bert   1

At a time when advancements seem to be getting ever more technical, we can actually use that in our favor to simplify our development and lower the learning curve. I’m still all about learning Python and not skipping steps, but this has been really fun and time-saving. This may very well be my last tutorial. You can now write a script using English. Now you have the start of a framework to begin writing scripts using just prompt responses from GPT-3. Remember to try and make my code even more efficient and extend it in ways I never thought of!

Remember my disclaimer: the prompts are best left for data analysis and generally harmless processes. It’s possible for GPT-3 to create destructive code depending on your prompt. Build in guard rails and be careful.

Now get out there and try it out! Follow me on Twitter and let me know your applications and ideas!

Greg Bernhardt
Follow me

Leave a Reply