OpenAI Codex
OpenAI Codex Reference Guide & Cheat Sheet
Complete documentation for OpenAI Codex parameters, system directives, API configurations, and prompt engineering frameworks across Codex, GPT-4o, and Reasoning models.
Total Parameters: 0
| Category | Introduced / Model | Parameter | Syntax / Key | Accepted Values / Range | Code Example | Description & Notes |
|---|---|---|---|---|---|---|
| 1. Core Model | All Models | Model ID | model |
gpt-4o, gpt-4o-mini, o3-mini, o1, code-davinci-002 | "model": "gpt-4o" |
Selects the underlying engine. Use gpt-4o for production coding or o3-mini for complex algorithmic reasoning. |
| 1. Core Model | All Models | Temperature | temperature |
0.0 – 2.0 (Default 1.0; 0.0 for code) | "temperature": 0.0 |
Controls randomness. Use 0.0 for deterministic, syntax-exact code generation and math tasks. |
| 1. Core Model | All Models | Max Tokens | max_completion_tokens |
1 – 128,000 (Model dependent) | "max_completion_tokens": 2048 |
Sets the maximum number of output tokens (code + reasoning) generated in a single completion response. |
| 1. Core Model | All Models | Top P | top_p |
0.0 – 1.0 (Default 1.0) | "top_p": 0.1 |
Nucleus sampling alternative to temperature. 0.1 means only top 10% probability mass tokens are evaluated. |
| 2. Code Control | Modern API | Response Format | response_format |
json_object, json_schema, text | "type": "json_schema" |
Guarantees output conforms strictly to a JSON Schema or valid JSON object. Ideal for automated AST/code parsing. |
| 2. Code Control | All Models | Stop Sequences | stop |
String or Array (Up to 4 strings) | "stop": ["\nclass ", "```"] |
Halts code generation immediately when specified tokens are encountered (e.g. stop at function/class boundary). |
| 2. Code Control | Function Calling | Tools / Functions | tools |
Array of function objects | "type": "function" |
Enables Codex to output structured call arguments to run sandbox tools, execute Python, or invoke external APIs. |
| 2. Code Control | Reproducibility | Seed | seed |
Integer (e.g., 42, 1337) | "seed": 42 |
Enables deterministic sampling for repeatable test runs and consistent code benchmarking. |
| 3. Optimization | o-series | Reasoning Effort | reasoning_effort |
low, medium, high (Default medium) | "reasoning_effort": "high" |
Controls internal chain-of-thought depth for o1 / o3-mini models before outputting final code. |
| 3. Optimization | All Models | Frequency Penalty | frequency_penalty |
-2.0 – 2.0 (Default 0.0) | "frequency_penalty": 0.5 |
Penalizes tokens based on their existing frequency in output. Prevents repetitive code loops and infinite loops. |
| 3. Optimization | All Models | Presence Penalty | presence_penalty |
-2.0 – 2.0 (Default 0.0) | "presence_penalty": 0.3 |
Encourages the model to introduce new programming concepts and functions rather than echoing existing text. |
| 3. Optimization | All Models | Logit Bias | logit_bias |
Map of Token IDs to values (-100 to 100) | "logit_bias": {"1234": -100} |
Forces or bans specific tokens from code output (e.g. banning deprecated library calls or unwanted keywords). |
| 4. Codex Infill | Codex Infill | Suffix (FIM) | suffix |
String (Code coming after cursor) | "suffix": "\n return result" |
Enables Fill-In-the-Middle (FIM) code completion by providing trailing context after the insertion point. |
| 4. System Roles | All Models | System Message | role: "system" |
Developer system prompt | "role": "developer" |
Sets global coding guidelines, language constraints (e.g., Python 3.12, strict TypeScript), and coding style. |
Codex Prompt Architecture & Vocabulary
[SYSTEM DIRECTIVE] + [CONTEXT & IMPORTS] + [DOCSTRING / GOAL] + [SIGNATURE / SPEC] => EXECUTABLE CODE
1. Context & Environment
Define language versions, core libraries, and target runtimes (e.g., Python 3.12, AsyncPG, Pydantic v2).
2. Interface Definition
Provide function signatures, class scaffolding, or TypeScript interfaces to anchor structural intent.
3. Guardrails & Limits
Specify error handling strategies, edge cases, performance constraints, and forbidden operations.
4. Expected Output
Request raw executable code without conversational commentary using explicit Markdown code blocks.
Infill & Completion Patterns
Code Quality Modalities
Codex Power Tips & Best Practices
Zero Temperature for Deterministic Code
When generating production logic, always pass
temperature: 0.0. This prevents creative syntax variations and enforces reliable, repeatable code execution.
"temperature": 0.0
Tip: Use higher temperature (0.7+) only when generating alternative algorithms.
Docstring-First Prompting
Codex generates significantly higher quality code when given a detailed docstring with type annotations before the code block.
def parse_jwt(token: str) -> dict:
"""Extracts claims safely..."""
Tip: Include @param and @return directives inside comments.
Stop Sequences for Clean Truncation
Prevent Codex from adding extraneous conversational explanations by setting stop sequences on function or class headers.
"stop": ["\ndef ", "\nclass ", "```"]
Tip: Keeps response tokens minimal and prevents multi-function spillover.
Prompt Framework & Production Example
Core Rules for OpenAI Codex Generation
- Specify Exact Versions: Always state library versions (e.g.,
Pydantic v2,React 18 ESM) to prevent deprecated API syntax. - Provide Input/Output Examples: Include 1–2 JSON or type examples showing expected input payloads and returned outputs.
- Enforce Type Safety: Require strict typing (e.g. TypeScript interfaces, Python type hints) for immediate static analysis validation.
- Test-Driven Construction (TDD): Provide unit test cases first and ask Codex to write code that satisfies all assertions.
Standard Production Code Prompt Template
// SYSTEM DIRECTIVE: You are a Senior Backend Engineer writing production Python 3.12 code.
// REQ: Generate an async function with full typing, error handling, and docstrings.
import asyncio
from pydantic import BaseModel, EmailStr
class UserRegistration(BaseModel):
username: str
email: EmailStr
async def register_user(payload: UserRegistration) -> dict:
"""
Validates user credentials, creates a database record, and sends a welcome event.
@param payload: Validated Pydantic user registration schema.
@return: Dict containing user_id and creation status.
@raises ValueError: If user already exists in datastore.
"""
# CODE CONTINUATION HERE...