AI Generates Code Using Python and OpenAI’s GPT-3

Dipesh Pal
Analytics Vidhya
Published in
8 min readJul 10, 2021

Today AI is generating all the code you need, you no need to write the code you can just do the supervision. If you want and focus more on logic and get more productivity. Since the GPT-3 is released, it changes how we deal with text in the AI-ML world. Given any text prompt like a phrase or a sentence, GPT-3 returns a text completion in natural language. Developers can “program” GPT-3 by showing it just a few examples or “prompts.”

You must hear about Github Copilot, well is that really true that AI will replace humans? Let me know your thoughts.

AI Generates Code

In this article, we will talk about the basic usages of GPT-3. The contents of the articles are-

  1. How to get API access for GPT-3?
  2. What GPT-3 can do?
  3. Use Cases
  4. Code examples with Python (Explanation)
  5. Github Code
  6. YouTube Video Demo and Quick Explanation
  7. What next?
  8. You might be interested in…
  9. Contact me
  10. Sources and Resources

1. How to get API access for GPT-3?

  • Method 1 (Application form)- The first thing is to send an application on OpenAI’s official API Waitlist form. The form is fairly simple and basically only asks about your intended use case.
  • Method 2 (Outreach)- There was a way to fast-track access by emailing Greg Brockman, OpenAI’s CTO.
  • Method 3 (Stand out)- If you don’t receive access to the above methods, our suggestion is to do something that shows your enthusiasm and gets OpenAI excited about you and your use case

2. What GPT-3 can do?

3. Use Cases

Some of the great folks did magnificently works, let's see some of the samples-

  • Code Generator-
  • Designer: Here is a beautiful integration of the Figma plugin and GPT-3 to generate beautiful web templates. The developer inputs the following text:

“An app that has a navigation bar with a camera icon, “Photos” title, and a message icon. A feed of photos with each photo having a user icon, a photo, a heart icon, and a chat bubble icon”

And generates this beautiful, simple application.

  • JSX Layout Maker: This was one of the first examples of GPT-3 to generate code that caught the attention of the tweeple. It shows how to generate a JSX layout just by defining it in plain English.
  • Regex Generator: You input the Regex you want in plain English, provide an example string that will match, and generates the Regex in seconds.

Sources and Other Use Cases-

  1. Code Oracle
  2. Designer
  3. JSX Layout maker
  4. Regex Generator
  5. Website mocker
  6. Object use-case generation
  7. Autoplotter
  8. A complete evaluation
  9. Quiz Producer
  10. Learn from anyone
  11. The Philosopher
  12. The AI recursion
  13. The Meme Maker
  14. The LaTeX Fabricator
  15. The Animator
  16. The Interactive Voice Response creator
  17. The 3-D Scene generator
  18. Resume Creator
  19. Dev Ops Engineer
  20. Cricket Commentator

4. Code examples with Python (Explanation)

Let's talk about some technical aspects then I’ll show you the complete code as well.

The folder structure of my project is-

  • I have put some Python code in examples in the ‘examples’ directory with the program name/title as the file name. These examples I’ll feed later to GPT-3.
  • gpt.py- Some of the useful functions to use Openai’s GPT-3. It contains functions to add examples, predict, configure, etc. Basically, you do need to worry about this file. You can use this piece of code in your code file (main.py in our case).
  • main.py- It is the treasure for which you are here. Well just have a look into the code then I’ll explain-
from key import *
import glob
import openai
from gpt import GPT
from gpt import Example

# configure GPT
openai.api_key = key
gpt = GPT(engine="davinci",
temperature=0.5,
output_prefix="Output: \n\n",
max_tokens=100)

# add some code examples
for file in glob.glob("examples/*"):
title = file.replace("_", " ")
with open(f"{file}", "r") as f:
code = f.read()
gpt.add_example(Example(title, code))

# add some calculation examples
gpt.add_example(Example("add 3+5", "8"))
gpt.add_example(Example("add 8+5", "13"))
gpt.add_example(Example("add 50+25", "75"))

# Inferences
prompt = "sort list in python"
output = gpt.get_top_reply(prompt)
print(prompt, ":", output)
print("----------------------------------------")

prompt = "Code weather api in python"
output = gpt.get_top_reply(prompt)
print(prompt, ":", output)
print("----------------------------------------")

prompt = "What is 876+89"
output = gpt.get_top_reply(prompt)
print(prompt, ":", output)
print("----------------------------------------")

Most of the code is self-explanatory. Well, I am iterating over the ‘examples’ directory and while iterating I am adding examples in GPT-3 API.

gpt.add_example(Example("add 3+5", "8"))

The above lines take two arguments in Example, “add 3+5” is the input and the “8” is the output that you are expecting GPT-3 to perform.

Similarly, you can feed different kinds of examples to the model and explore the possibilities.

I have given two kinds of examples, in the first example, I have given some python code with a description of code-

# add some code examples
for file in glob.glob("examples/*"):
title = file.replace("_", " ")
with open(f"{file}", "r") as f:
code = f.read()
gpt.add_example(Example(title, code))

In the second example, I have given a basic math calculation example-

# add some calculation examples
gpt.add_example(Example("add 3+5", "8"))
gpt.add_example(Example("add 8+5", "13"))
gpt.add_example(Example("add 50+25", "75"))

Let's check the API’s outputs-

The following is the output for “prompt = ‘Code weather API in python’”

Understand the output- I have “set max_tokens=100” in code, you can change it according to your choice. Well, this will increase or decrease the output length.

The output looks pretty awesome, It has changed the variable name and given lots of other things as output.

The example I have fed to this API is-

The output I have got is-

prompt = "Code weather api in python"
output = gpt.get_top_reply(prompt)
print(prompt, ":", output)

Below is the output for the above prompt-

Code weather api in python : Output:
import requests
r = requests.get('http://api.openweathermap.org/data/2.5/weather?q=London&APPID={APIKEY}')
data = r.json()
print(data['weather'][0]['description'])
print(data['main']['temp'])
print(data['main']['temp_min'])
print(data['main'][

The following is the output for sorting list in python without using sort function-

Understand the output- Well this time it feels like it has remembered my code exactly but yeah this is what I have got.

The example I have fed to this API is-

The output I have got is-

prompt = "sort list in python"
output = gpt.get_top_reply(prompt)
print(prompt, ":", output)

Below is the output for the above prompt-

sort list in python : Output: 

def fun(l):
list_len = len(l)
for i in range(list_len):
if i < list_len - 1:
if l[i] > l[i + 1]:
l[i], l[i + 1

The following is the output for maths calculation in python-

Understand the output- I have fed very basic examples to the API for the addition but it can do the addition of large numbers as well. I am very sure that it will able to solve pretty long mathematical expressions as well.

The example I have fed to this API is-

The output I have got is-

prompt = "What is 876+89"
output = gpt.get_top_reply(prompt)
print(prompt, ":", output)

Below is the output for the above prompt-

What is 876+89 : Output: 

865

5. Github Code-

Just fork it, start it, add your key in the ‘key.py’ file, and then run the ‘main.py’ file.

6. YouTube Video Demo and Quick Explanation

7. What Next?

If you want a tutorial on these then comment down or mail me or DM me on Instagram.

* CLIP: Connecting Text and Images

OpenAI introduces a neural network called CLIP which efficiently learns visual concepts from natural language supervision. CLIP can be applied to any visual classification benchmark by simply providing the names of the visual categories to be recognized, similar to the “zero-shot” capabilities of GPT-2 and GPT-3.

* DALL·E: Creating Images from Text

OpenAI introduces a neural network called DALL·E that creates images from text captions for a wide range of concepts expressible in natural language.

8. You might be interested in…

9. Contact me-

Buy me a coffee:

Don’t have money?

Subscribe to me on YouTube:

Follow me on Instagram:

https://www.instagram.com/dipesh_pal17

--

--

Dipesh Pal
Analytics Vidhya

I'm Data Scientist, Developer, YouTuber, Photograper, and Blogger! www.dipeshpal.in