OpenAI Codex API: For Python Code Generation

This tutorial is mainly based on exploring OpenAI codex API. We will be using it to generate python code from a natural language. A paid API allows users to view and use OpenAI’s trained Artificial Intelligence (AI) models.

AI computations can now be performed by a wider audience, which includes those who lack the data and skills to build and train their own models.

OpenAI Codex API
OpenAI Codex API

This tutorial will cover:

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

On YouTube, you can also watch this tutorial in video format:

Register for the Codex Private Beta

As a starting point, I would like to emphasise that access to the codex API is restricted to individuals who register for the private access beta program. After you are approved for the API, you can access and experiment with it for free.

Having seen what the codex can do for the first time when I got my first access, I was thoroughly impressed by what it can do. The codex is an extremely interesting concept, and I’m looking forward to seeing what people build with it. I already have some amazing ideas of my own that I’d like to use – but that’s for another time.

Start here: OpenAI CodexWe’ve created an improved version of OpenAI Codex, our AI system that translates natural language to code, and we are…openai.com

You can join the waitlist by clicking the “Join Waitlist” button. An online form will appear. This is a very simple, easy process. After submitting the application, you’ll receive an email confirming that it’s been received.

My approval took approximately two weeks to receive, plus or minus a couple of days. The invitation will look like:

OpenAI Codex API
Invitation

By clicking accept in the email, you will be adding the codex models to those that are already on the playground and the API. Easy!

There are two codex models that you get access to:

  • code-davinci-001: Codex model that is capable of understanding and generating code.
  • code-cushman-001: (This is an assumption based on current models) A bit less powerful, but faster and probably more affordable.

Access the OpenAI Codex API through the online playground

You can navigate to playground using this link: OpenAI APIAn API for accessing new AI models developed by OpenAI

Then, from the menu, choose one of the Codex models. You may also choose a preset from a list, which will assist you in loading the models and settings you’ll need to run the preset (a excellent place to start, especially if you’re not sure how to alter the variables for your query).

OpenAI Codex API
OpenAI Playground

Note: The CODEX models will only appear after you have applied for and been approved into the codex open beta.

Explore the JS Codex Sandbox

The OpenAI team designed this software to access the codex API and request JS code, which is then built and run, presenting the result of the code alongside the produced code side-by-side.

Sandboxes like this make it very easy to visualise what code is doing as it is generated. The famous codex demo was done in a sandbox.

Link to the JS Sandbox: OpenAI API

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

Landing Page 

There are probably some kinks in this landing page, but here’s where you help explaining more and importing CSS and designs to improve it.

Using the “import bootstrap and apply bootstrap to existing page” command, you can import Bootstrap. You can just pass on a URL linking to your own CSS files if you already have them hosted somewhere else.

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

Adding image of logo to the JS sandbox

To generate Python code, use the OpenAI API with Python

Use the “view code” button at the top of the page to generate python code directly from the playground.

We created code for an API call with the following prompt:

"""
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=" + 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)

This code snippet will yield the same results in your own program; however, we modified it as follows to get the code snippet we provided:

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)

Create python code for a Flask application using the codex

What struck me as so amazing was that I was able to generate an entire Python Flask application with only a few lines of instructions.

Assume that you were looking to build your own Flask application from this code.

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)

I am saving a lot of developers’ time by getting boilerplate code out of Codex quickly.

Observations and Lessons Learned

Will codex replace developers?

I don’t see that happening anytime soon. There’s still a lot of editing to do on the code. Having basic knowledge of coding allows you to read the codex output and decide where edits need to be made.

Is coding with codex now possible for non-developers?

Not using the API, I don’t think so. However, there is an opportunity for creating interfaces that allow non-developers to communicate with code without having to learn how to code, such as the Javascript Sandbox, which can produce useful products such as landing pages.

How can Codex help you create amazing products?

Though I have only recently been introduced to this concept, I am already thinking 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

Would you mind sharing your thoughts? Could you build something with codex? Let me know what you think. Check out our previous blog here: AI Content Generator

Leave a Reply

Your email address will not be published.

Subscribe to our mailing list

And get this 💃💃 Free😀 eBook !

Holler Box