circuit

Generate Python Code with OpenAI Codex API

A tutorial to explore the OpenAI codex API by generating Python code from natural language.


In this tutorial, we are going to explore the OpenAI codex API by generating Python code from natural language. OpenAI offers trained Artificial Intelligence (AI) models that can be accessed via a paid API.

This makes AI computation more accessible to many more people, that do not have the data and skills to build and train their own models.

OpenAI Codex API

What we are going to cover in this tutorial:

  1. Register for the Codex Private Beta
  2. Access the OpenAI Codex API through the online playground
  3. Explore the JS Codex Sandbox
  4. Access the OpenAI API through Python to generate python code
  5. Generate python code for a Flask application using the codex

This tutorial is also available in video format on youtube here:

Get started by registering for OpenAI Codex Private Beta

I must start by mentioning that access to the codex api is limited to only a few individuals that register for their private access beta. The good news is that, once you do get approved, it is free to access the API and pay around with it.

I must also mention that I was thoroughly impressed by what I saw when I got my first access to the codex, it is amazing what it can do. I am really curious to see what people are going to build with the codex, I already have some pretty cool ideas of my own — but that is for another day.

Start here.

Click on the “Join Waitlist” button. You will see a form that you must complete. It is really simple and easy, then you will receive a confirmation email that your application was received.

I waited approximately two weeks, give or take a couple of days for my approval, and it looked like this:

OpenAI Codex Private Beta Invitation

When you receive this email, just click accept and the codex models will be added to the rest of the models that you have access to on the playground and via the API. That is it!

There are two codex models that you get access to:

  • code-davinci-001: The most capable codex model which can understand and generate code.
  • code-cushman-001: Slightly less powerful, but faster and will likely be cheaper (this is an assumption based on current models)

Access to OpenAI Codex API via Playground

You can navigate to playground using this link.

Then select one of the Codex models from the dropdown, you can also select a preset from a list — which will help you load the models and parameters you need to execute the preset (a good way to start, especially if you don’t know how to adjust the parameters for your query).

Navigate OpenAI Playground

Note: You will only see the CODEX models after you have applied for and been accepted into the codex open beta.

Explore the OpenAI Codex API Javascript Sandbox

This is an actual application that was built by the OpenAI team to call the codex API and request JS code, which then gets compiled and run, displaying the output of the code with the generated code side-by-side.

This is a goo great way to visualise what the code is doing as it gets generated, the famous codex demo video was run in this sandbox.

Link to the JS Sandbox.

So I provided the following instructions: “create a landing page design for a doctor” and this is what I got:

Landing Page Design for Doctor

This is probably not a proper landing page, but this is where you come in providing more training and importing CSS and designs to help you get a proper landing page.

You can import Bootstrap by just telling it “import bootstrap and apply bootstrap to the existing page”. If you had your own CSS files hosted somewhere, you could just pass it on as a URL link, like an image for example.

Type the following: “add this image of our logo”.

Adding image of logo to the JS sandbox

Access the OpenAI API through Python to generate Python code

You can generate python code from the playground using the “view code” button at the top of the page.

This is the prompt that we used to generate code for calling an API:

"""
1. Get a reputable news API website
2. Make a request to get the latest news stories
"""

This is the code that was returned by the codex API:

import requests
import json# Get the API key from the config file
from config import api_key# Create the URL for the request
url = "[https://newsapi.org/v2/top-headlines?country=us&apiKey=](https://newsapi.org/v2/top-headlines?country=us&apiKey=)" + api_key# Get the response
response = requests.get(url)# Convert the data into a JSON object
data = response.json()# Print the data
print(json.dumps(data, indent=4))# Print the articles
print(data["articles"])# Print the articles title
print(data["articles"][0]["title"])# Print the authors name
print(data["articles"][0]["author"])# Print the description
print(data["articles"][0]["description"])# Print the URL
print(data["articles"][0]["url"])

And exporting the Python code:

import os
import openai

openai.api_key = os.getenv("OPENAI_API_KEY")

response = openai.Completion.create(
  engine="code-davinci-001",
  prompt="\"\"\"\n1. Get a reputable news API website\n2. Make a    request to get the latest news stories\n",
  temperature=0,
  max_tokens=2000,
  top_p=1,
  frequency_penalty=0,
  presence_penalty=0)

You can run this code in your own program to output the same results above, we modified it as follows to get the code snippet:

import os

import openai

import config

openai.api_key = config.OPENAI_API_KEY

def runSomeCode():

response = openai.Completion.create(

engine="code-davinci-001",

prompt="\"\"\"\n1. Get a reputable free news api\n2. Make a request to the api for the latest news stories\n\"\"\"",

temperature=0,

max_tokens=1500,

top_p=1,

frequency_penalty=0,

presence_penalty=0)

if 'choices' in response:

x = response['choices']

if len(x) > 0:

return x[0]['text']

else:

return ''

else:

return ''

answer = runSomeCode()

print(answer)

OpenAI Codex Code Snippet

Generate Python code for a Flask application using the codex

This just blew my mind, that I could generate a full Python Flask application code with a few lines of instructions.

Imagine you wanted to take this code and build your Flask app.

These are the instructions we gave the API:

"""
1. Get a reputable news API website
2. Make a request to get the latest news stories
3. Create a flask application to display the news stories on the front HTML template
"""

This is the code that was generated by the API:

import requests

from flask import Flask, render_template, request

app = Flask(__name__)

# Get the news stories

api_key = None

base_url = None

def configure_request(app):

global api_key, base_url

api_key = app.config['NEWS_API_KEY']

base_url = app.config['NEWS_API_BASE_URL']

def get_news():

get_news_url = base_url.format(api_key)

with urllib.request.urlopen(get_news_url) as url:

get_news_data = url.read()

get_news_response = json.loads(get_news_data)

news_results = None

if get_news_response['articles']:

news_results_list = get_news_response['articles']

news_results = process_results(news_results_list)

return news_results

def process_results(news_list):

news_results = []

for news_item in news_list:

author = news_item.get('author')

title = news_item.get('title')

description = news_item.get('description')

url = news_item.get('url')

urlToImage = news_item.get('urlToImage')

publishedAt = news_item.get('publishedAt')

if urlToImage:

news_object = News(author, title, description, url, urlToImage, publishedAt)

news_results.append(news_object)

return news_results

@app.route('/')

def index():

news = get_news()

return render_template('index.html', news=news)

@app.route('/sources')

def sources():

return render_template('sources.html')

if __name__ == '__main__':

app.run(debug=True)

Well, the beauty of this is how quickly I can get boilerplate code out of codex, this is going to save developers a lot of time.

Lessons Learned and Opinions

Is codex going to replace developers?

No, not anytime soon. A lot of the code generated still needs some editing. So you need to know basic coding so you can read what codex has generated and see where you need to make edits.

Can non-developers now code using codex?

Not using the API, I don’t think so. But there is an opportunity to create interfaces such as the Javascript Sandbox that can allow non-developers to interact with code, without knowing how to code and produce useful products, such as landing pages, etc.

What amazing products can be built with Codex?

The sky is the limit, I am only just getting my head around this but I can already think of:

  • Learning code platforms for kids
  • Generate simple code products like websites and landing pages for non-developers
  • Create Flask applications on the go
  • Platform for accessing APIs
  • Platforms for explaining code to non-developers

What do you think? What can you build using codex? I would love to hear your opinion.




Continue Learning