Getting Started with OpenAI Codex CLI: Open Source AI Coding Assistant

Community Article Published April 17, 2025

The landscape of software development is constantly evolving, and AI-powered tools are increasingly becoming integral parts of the modern developer's workflow. Enter the OpenAI Codex CLI, a lightweight yet powerful coding agent designed to live right where many developers spend most of their time: the terminal.

Imagine having an assistant directly in your command line that can understand your codebase, write code, refactor components, generate tests, explain complex snippets, manage files, and even execute commands, all while respecting version control and security boundaries. That's the promise of the Codex CLI. It aims to blend the reasoning capabilities of advanced language models like those powering ChatGPT with the practical ability to interact with your local development environment.

This tutorial will guide you through setting up, configuring, and using the OpenAI Codex CLI, transforming how you interact with your code directly from your terminal.

(Image: Codex demo GIF using: codex "explain this codebase to me") (Imagine the GIF provided in the prompt is embedded here, showing Codex CLI analyzing code and providing an explanation in the terminal)


Before diving in, it's crucial to understand that Codex CLI is an experimental project. It's under active development within the open-source community. This means:

  • Stability: It might not be fully stable yet. You may encounter bugs or unexpected behavior.
  • Features: Some features might be incomplete or subject to change.
  • Breaking Changes: Future updates could potentially introduce changes that break compatibility with previous versions or workflows.

The team encourages community involvement through:

  • Bug reports
  • Feature requests
  • Pull requests
  • General feedback ("Good vibes")

By using Codex CLI at this stage, you're participating in its evolution. Help shape its future by contributing via GitHub issues and pull requests!

https://github.com/openai/codex


2. Introduction: Why Codex CLI?

While graphical IDE extensions and web-based AI chat interfaces are powerful, Codex CLI caters specifically to developers who prefer the speed, efficiency, and control of the command line.

Key Advantages:

  • Terminal Native: Designed for developers who live in the terminal.
  • ChatGPT-Level Reasoning: Leverages powerful language models for understanding context and generating code/explanations.
  • Code Execution & File Manipulation: Goes beyond chat; it can actually run code, install dependencies, and modify files in your repository.
  • Version Control Aware: Integrates naturally with Git workflows, allowing you to review and commit AI-generated changes.
  • Zero Setup (Almost): Requires only Node.js and your OpenAI API key to get started.
  • Configurable Autonomy: You decide how much freedom the agent has, from suggesting changes to automatically executing commands.
  • Security Focused: Implements sandboxing to prevent unintended side effects, especially in modes with higher autonomy.
  • Multimodal Potential: Future plans include the ability to understand screenshots or diagrams.
  • Open Source: Transparency in how it works and the ability for anyone to contribute.

In essence, Codex CLI aims to be your chat-driven development partner that deeply understands and interacts with your specific project repository.


3. Prerequisites & System Requirements

Before installing Codex CLI, ensure your system meets the following requirements:

Requirement Details
Operating System macOS 12+, Ubuntu 20.04+/Debian 10+, or Windows 11 via WSL2
Node.js Version 22 or newer (LTS recommended)
npm (or yarn) Comes bundled with Node.js (or install yarn separately)
OpenAI Account You need an account with OpenAI to generate an API key.
OpenAI API Key A secret key to authenticate requests to the OpenAI API.
Git (Optional) Version 2.23+ recommended for best integration and safety nets.
RAM 4 GB minimum, 8 GB recommended for smoother performance.

4. Installation

Installing Codex CLI is straightforward using npm (Node Package Manager) or yarn.

Using npm (Recommended):

Open your terminal and run the following command:

npm install -g @openai/codex

Using yarn:

If you prefer yarn, use this command:

yarn global add @openai/codex

Important Note on Permissions: Avoid using sudo for global npm installs (sudo npm install -g ...). This can lead to permission issues later. If you encounter permission errors (like EACCES), it's better to fix your npm permissions rather than resorting to sudo. Search online for "fix npm permissions" for guides specific to your operating system.

Once the installation completes, you should be able to run the codex command in your terminal.


5. Configuration: API Key and Custom Instructions

a) Setting the OpenAI API Key (Essential)

Codex CLI needs your OpenAI API key to communicate with the OpenAI models. You need to set this key as an environment variable named OPENAI_API_KEY.

For the current terminal session:

export OPENAI_API_KEY="your-api-key-here"

Replace "your-api-key-here" with your actual secret key obtained from the OpenAI platform.

Making the API Key Permanent:

The export command above only sets the variable for your current terminal session. To avoid setting it every time, add the export line to your shell's configuration file:

  • For Zsh (common on macOS): Add the line to ~/.zshrc
  • For Bash (common on Linux/WSL): Add the line to ~/.bashrc or ~/.bash_profile

After adding the line, either restart your terminal or source the configuration file (e.g., source ~/.zshrc).

b) Optional Configuration Files

Codex CLI looks for configuration files in a hidden directory within your home folder: ~/.codex/.

  • ~/.codex/config.yaml: Customize default behavior.

    # Example ~/.codex/config.yaml
    model: o4-mini # Set the default OpenAI model to use (e.g., gpt-4, gpt-3.5-turbo, o4-mini)
    fullAutoErrorMode: ask-user # What to do if a command fails in full-auto mode: 'ask-user' or 'ignore-and-continue'
    
  • ~/.codex/instructions.md: Provide global, personal instructions or guidelines for the AI model. This Markdown file lets you shape how Codex responds across all your projects.

    # Example ~/.codex/instructions.md
    - Always explain code changes clearly.
    - Prefer functional programming approaches where appropriate.
    - Use TypeScript for any new JavaScript/TypeScript files.
    - Avoid using force pushes (`git push -f`) unless explicitly told.
    

These global instructions can be augmented or overridden by project-specific files (see Advanced Usage).


6. Quickstart: Your First Interaction

With installation and API key configuration complete, you can start using Codex CLI.

1. Interactive Mode:

Navigate to a project directory in your terminal and simply run:

codex

This starts an interactive session (REPL - Read-Eval-Print Loop). Codex will likely ask you for an initial prompt or goal. You can then chat with it, asking it to perform tasks related to the code in your current directory.

2. Running with an Initial Prompt:

You can provide your first instruction directly as an argument:

cd /path/to/your/project
codex "explain the purpose of the main function in main.py"

or

cd /path/to/your/project
codex "refactor the UserCard component to use styled-components"

Codex will read your prompt, analyze the relevant files (if necessary), propose a plan or code changes, and wait for your approval before proceeding.

3. Running with Auto-Approval (Use with Caution):

You can grant Codex more autonomy using the --approval-mode flag. For example, to automatically apply file edits but still ask before running shell commands:

codex --approval-mode auto-edit "add JSDoc comments to all functions in utils.js"

Or, for maximum autonomy (automatically applying file edits and running shell commands):

codex --approval-mode full-auto "create a basic express server with a health check endpoint"

Warning: full-auto mode should be used cautiously, especially in projects not tracked by Git. Codex will issue a warning if you start in auto-edit or full-auto in an untracked directory.


7. Core Concepts: Interactive Loop & Approval Modes

Understanding the interaction flow and approval levels is key to using Codex CLI effectively and safely.

a) The Interactive Loop:

When you give Codex CLI a task, it typically follows these steps:

  1. Understand: Parses your prompt and analyzes the relevant context (code files, project structure).
  2. Plan: Determines the steps needed (e.g., read file A, modify function B, run command C).
  3. Propose: Presents the proposed action to you.
    • For file changes: Shows a diff (what lines will be added/removed).
    • For shell commands: Shows the exact command to be executed.
  4. Await Approval: Waits for your confirmation (y for yes, n for no), unless an auto-approval mode is active for that action type.
  5. Execute (if approved): Performs the action (applies the patch, runs the command in a sandbox).
  6. Observe & Iterate: Checks the result (e.g., command output, test results). If the task isn't complete or errors occurred, it may propose further steps, looping back to step 3.
  7. Complete: Finishes when the task is done or you end the session.

b) Approval Modes (--approval-mode or -a flag):

You control how much autonomy Codex has:

  • suggest (Default):

    • Agent May Do Without Asking: Read any file in the repository.
    • Requires Approval: ALL file writes/patches, ALL shell/Bash commands.
    • Safest mode, recommended for getting started.
  • auto-edit:

    • Agent May Do Without Asking: Read files, apply patch writes to files.
    • Requires Approval: ALL shell/Bash commands.
    • Useful for tasks primarily involving code modification, like refactoring or adding documentation.
  • full-auto:

    • Agent May Do Without Asking: Read/write files, execute shell commands.
    • Requires Approval: Nothing (within the sandbox limits).
    • Most powerful but carries the highest risk. Use only when you understand the potential actions and have safety nets like Git.

Even in full-auto, security measures (sandboxing, network restrictions) are in place.


8. Security Model: Sandboxing Explained

A key feature of Codex CLI is its focus on security, especially when executing code or shell commands. It achieves this through sandboxing, preventing the agent from affecting your system outside the intended project scope.

  • Network Restrictions: In full-auto mode, executed commands are generally network-disabled by default. This prevents unexpected calls to external services or data exfiltration (e.g., a rogue curl command will fail). Future updates may allow whitelisting specific commands for network access with safeguards.

  • Filesystem Restrictions: Commands are confined to the current working directory ($PWD) and temporary system directories ($TMPDIR). Access to other parts of your filesystem is heavily restricted.

  • Platform-Specific Sandboxing:

    • macOS (12+): Uses the built-in sandbox-exec (Apple Seatbelt) technology. The environment is primarily read-only except for explicitly allowed paths like the project directory and temp folders.
    • Linux: Recommends using Docker. Codex can automatically launch itself inside a minimal container, mounting your project directory read/write. A custom firewall (iptables/ipset) within the container blocks all outgoing network traffic except for necessary communication with the OpenAI API. This provides strong, reproducible isolation without needing root privileges on the host machine (after initial Docker setup). See run_in_container.sh in the source code for details.
    • Windows (via WSL2): Relies on the Linux sandboxing mechanisms within the WSL2 environment (typically Docker).
  • Git Safety Net: If you start Codex in auto-edit or full-auto mode in a directory not tracked by Git, it will display a warning and require confirmation, encouraging you to have version control in place as a safety rollback mechanism.

These layers provide defense-in-depth, allowing you to leverage the agent's power while minimizing risks.


9. Practical Examples & Recipes

Here are some concrete examples of how you can use Codex CLI, adapted from the provided recipes:

  1. Code Refactoring:

    • You type: codex "Refactor the Dashboard component from a class component to use React Hooks"
    • What happens: Codex reads the component file, understands React class and Hooks syntax, generates the refactored code, proposes the changes as a file patch (diff), asks for approval. If approved, it applies the patch. It might then suggest running tests (npm test or yarn test) and ask for approval to execute that command.
  2. Database Migrations:

    • You type: codex "Generate SQL migrations using Prisma for adding a 'profiles' table with 'userId' (relation to User) and 'bio' (text) fields"
    • What happens: Codex infers you're using Prisma (or asks if ambiguous), generates the necessary Prisma schema changes or migration files (prisma migrate dev --create-only), proposes the file creations/modifications, asks for approval. It might then suggest running the migration command (prisma migrate dev) and ask for approval to execute it (sandboxed if possible, depending on DB connection).
  3. Test Generation:

    • You type: codex "Write Jest unit tests for the functions in utils/date.ts, aiming for 80% coverage"
    • What happens: Codex analyzes utils/date.ts, generates Jest test cases in a corresponding test file (e.g., utils/date.test.ts), proposes the new file, asks for approval. If approved, it might suggest running the tests (jest utils/date.test.ts) and ask for approval. If tests fail, it might offer to debug and fix them, iterating the process.
  4. Bulk File Operations:

    • You type: codex "Bulk-rename all *.jpeg files in the 'assets' directory to *.jpg using git mv"
    • What happens: Codex identifies the .jpeg files, formulates the necessary git mv commands, proposes executing these commands, asks for approval. Using git mv ensures version control history is maintained.
  5. Code Explanation:

    • You type: codex "Explain what this regex does: ^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)[A-Za-z\d]{8,}$"
    • What happens: Codex analyzes the regular expression and provides a step-by-step, human-readable explanation of its components and overall purpose (e.g., "Requires at least 8 characters, including at least one uppercase letter, one lowercase letter, and one digit").
  6. High-Level Code Review:

    • You type: codex "Carefully review this repo, focusing on the 'server' directory. Propose 3 high-impact, well-scoped improvements or refactors I could implement."
    • What happens: Codex reads through the specified directory's code, analyzes patterns, potential issues, or areas for enhancement, and suggests 3 concrete improvement ideas with justifications, possibly linking to specific files or code sections. It won't make changes here, just provide suggestions.

These examples showcase the versatility of Codex CLI, from low-level code manipulation to high-level analysis and explanation.


10. Advanced Usage: CI Mode, Memory, and Flags

a) Non-interactive / CI Mode:

You can run Codex CLI headlessly, making it suitable for automation scripts or CI/CD pipelines.

  • Use the --quiet (or -q) flag to suppress the interactive UI elements.
  • Set an appropriate --approval-mode (e.g., auto-edit or full-auto depending on the task and safety requirements).
  • Alternatively, set the environment variable CODEX_QUIET_MODE=1.

Example GitHub Action Step:

- name: Update CHANGELOG via Codex
  run: |
    npm install -g @openai/codex
    export OPENAI_API_KEY="${{ secrets.OPENAI_KEY }}"
    # Run codex non-interactively, allowing auto-edits, in quiet mode
    codex -a auto-edit -q "Update the CHANGELOG.md based on recent commits for the upcoming release"
  env:
    GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Often needed for commit analysis

b) Memory & Project Context:

Codex CLI can incorporate contextual instructions from Markdown files to guide its behavior more specifically. It merges instructions in this order (later files override earlier ones):

  1. Global User Instructions: ~/.codex/instructions.md (Your personal preferences across all projects).
  2. Repository Root Instructions: codex.md at the root of your Git repository (Shared guidelines for everyone working on the project).
  3. Current Directory Instructions: codex.md in the current working directory (Specific instructions for a sub-package or particular part of the project).

This layering allows for fine-grained control over the AI's behavior. You can disable this feature using the --no-project-doc flag or by setting the environment variable CODEX_DISABLE_PROJECT_DOC=1.

c) Key CLI Flags:

  • --model / -m: Specify the OpenAI model to use (e.g., -m gpt-4, -m o4-mini). Defaults to the value in ~/.codex/config.yaml or a sensible default if not configured.
  • --approval-mode / -a: Set the approval mode (suggest, auto-edit, full-auto).
  • --quiet / -q: Enable non-interactive mode for scripting/CI.
  • --help: Display detailed help information about commands and flags.
  • completion <bash|zsh|fish>: Generate shell completion scripts for easier command-line use.

11. Troubleshooting & FAQ

  • Is this related to the OpenAI Codex model released in 2021? Yes, this tool utilizes large language models from OpenAI, which are descendants or related to the original Codex models specialized in code. The CLI tool itself is a distinct open-source project providing the terminal interface and execution environment.
  • How do I stop Codex from touching my repo? Use the default suggest approval mode (codex --approval-mode suggest ... or just codex ...). In this mode, Codex will never write files or execute commands without your explicit 'yes' confirmation for each action.
  • Does it work on Windows? Yes, via the Windows Subsystem for Linux (WSL2). Install Codex CLI within your WSL2 environment.
  • Which models are supported? It generally supports various OpenAI chat completion models (like GPT-3.5 Turbo, GPT-4, GPT-4o, O4-mini). You can specify the model using the --model flag or in the config file. Check the project's documentation or --help for the most up-to-date list.
  • Getting Help: If you encounter issues, have questions, or want to discuss ideas, the best places are the project's GitHub Discussions and Issues pages.

12. Contributing to Codex CLI

As an open-source, experimental project, Codex CLI thrives on community contributions. If you're interested in helping:

  • Report Bugs: Clearly describe issues you encounter on the GitHub Issues page.
  • Request Features: Propose new ideas or enhancements via Issues or Discussions.
  • Submit Pull Requests: Contribute code fixes or new features.
    • Follow the development workflow outlined in the project's CONTRIBUTING.md file (create topic branches, write tests, lint/format code, sign the CLA).
    • Start by discussing significant changes in an Issue first.
    • Ensure tests pass (npm test) and code adheres to style guidelines (npm run lint, npm run typecheck).
  • Sign the CLA: Contributors need to sign the Contributor License Agreement by commenting I have read the CLA Document and I hereby sign the CLA on their pull request.

The project emphasizes high-quality contributions and maintains a friendly, inclusive community following the Contributor Covenant.


13. Conclusion

The OpenAI Codex CLI presents an exciting paradigm for developers who prefer the command line: chat-driven development directly integrated into their local environment. It combines powerful AI reasoning with the practical ability to interact with codebases, execute commands securely, and respect version control workflows.

While still experimental, its potential to accelerate development tasks like refactoring, test generation, code explanation, and even automated scripting is significant. By understanding its core concepts, particularly the approval modes and security sandboxing, you can start leveraging this powerful assistant safely and effectively.

Install it, configure your API key, and start experimenting with prompts in your own projects. Happy hacking! ๐Ÿš€

Community

Your need to confirm your account before you can post a new comment.

Sign up or log in to comment