OpenAI Codex: Natural Language to Code
Discover how to generate, refactor, and explain code using 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
- Code Translation: Provide Codex with code written in Python and ask it to translate the exact logic into JavaScript or C++.
- Docstring Generation: Give Codex a complex algorithm and ask it to write a detailed, PEP-8 compliant docstring explaining the inputs, outputs, and logic.
- Writing Unit Tests: Supply an existing function and ask Codex to generate an exhaustive set of unit tests using `pytest` or `unittest`.
- Explaining Code: If you encounter a cryptic regular expression or obfuscated code snippet, simply ask Codex:
# Explain what the following code does:
Best Practices
To get the best results from Codex, follow these tips:
- Provide Context: Include necessary imports, global variables, and class definitions in your prompt so Codex understands the environment.
- Use Comments for Instructions: When writing prompts, format your instructions as code comments (e.g.,
// Create a fetching function). This helps Codex seamlessly continue into writing code. - Start the Function Signature: Providing the function name and parameters (e.g.,
function calculateTotal(items) {) drastically improves the accuracy of the generated logic.