OpenAI Codex: Natural Language to Code

Discover how to generate, refactor, and explain code using Codex.

OpenAI Codex ← Back to Tutorials

What is OpenAI Codex?

OpenAI Codex is the AI model that powers GitHub Copilot. It is highly proficient in over a dozen programming languages, including Python, JavaScript, Go, Perl, PHP, Ruby, Swift and TypeScript. Codex is designed to parse natural language queries and generate robust code snippets, complete functions, and even full-scale algorithms.

Using Codex via API

You can interface with Codex directly using the OpenAI API. It functions similarly to standard GPT models, but you provide instructions specifically geared towards code generation.

import openai
import os

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

response = openai.Completion.create(
  model="code-davinci-002",
  prompt="\"\"\"\nCreate a Python function that connects to a PostgreSQL database and returns all users with an active subscription.\n\"\"\"\n\ndef get_active_users():",
  temperature=0,
  max_tokens=256,
  top_p=1,
  frequency_penalty=0,
  presence_penalty=0
)

print(response.choices[0].text)

Common Use Cases

Best Practices

To get the best results from Codex, follow these tips: