Learn more:https://treerouter.com
Abstract
Codex CLI is OpenAI’s open‑source command‑line coding‑agent framework, which enables developers to run AI‑driven code modification, test execution and repository analysis entirely inside local terminal environments. Instead of relying fully on web‑hosted Codex services, local‑mode deployment grants teams greater authority over model selection, data privacy and billing patterns. This article systematically covers prerequisites, two installation approaches, core config.toml configuration semantics, distinctions between API‑key authentication and OAuth flows, connection procedures for third‑party OpenAI‑compatible endpoints, and end‑to‑end integration with Ollama for fully‑offline inference. It also introduces the extension pattern using a model‑gateway layer, and compares three major deployment pathways alongside practical troubleshooting for frequent runtime failures. All configuration snippets and operational steps reflect real‑world verified workflows for 2026‑era Codex CLI releases.
1. Background: Why Run Codex CLI Locally
Many developers first encounter Codex as a built‑in web feature within ChatGPT, which can read repository contents, edit source files, run unit tests and generate pull‑request suggestions. That web‑based product represents only one delivery form. Underlying it sits a reusable agent framework that OpenAI has open‑sourced as Codex CLI, a cross‑platform terminal executable.
Functionally, local Codex CLI carries out identical core work as its cloud counterpart: parsing natural‑language instructions, scanning local directory trees, invoking large‑model back‑ends, producing code‑change proposals, and executing shell commands or file writes after explicit user approval. The fundamental divergence lies in data routing. Cloud‑hosted Codex keeps both model inference and code‑processing logic on remote servers. In local‑CLI mode, all file‑system scanning and agent‑loop logic execute on your own hardware, while model inference can be routed to official cloud APIs, third‑party compatible providers, or fully‑local Ollama‑hosted models.
Local deployment solves three pain‑points that cloud‑only offerings struggle to address.
First is source‑code privacy protection. Proprietary repositories may embed API credentials, client business logic, or unreleased product implementations. Sending large volumes of private code snippets to public web UIs creates audit and leakage risks. Local execution keeps file scanning on‑premises. When paired with local Ollama inference, code context never leaves the host machine, strengthening data control for security‑conscious projects.
Second is model‑selection flexibility. The web‑hosted Codex product restricts users to OpenAI‑curated model options. By modifying configuration files in the CLI edition, developers can point requests to DeepSeek, Moonshot, Zhipu and other OpenAI‑compatible services, or swap among open‑weight local models according to task difficulty, latency targets and budget constraints. Different subtasks can even map to distinct model variants within one project workflow.
Third is cost and workflow adaptability. Web‑interface subscriptions operate on fixed monthly billing cycles. Local Codex CLI consumes resources purely according to token volume, making it economical for intermittent usage or bulk offline code‑audit jobs. As a native command‑line program, it can be chained with Git hooks, CI pipelines and shell scripts — integration points that browser‑based tools cannot easily expose.
Before installation, evaluate which deployment path matches your project requirements.
| Deployment Path | Model Source | Code Context Leaves Local Machine | Cost Model | Suitable Scenarios |
|---|---|---|---|---|
| Official OpenAI API | OpenAI GPT‑5‑Codex | Yes, prompts and repository context transmitted | Per‑token metering | Maximal coding‑agent reasoning capability |
| Third‑party compatible API | DeepSeek, Zhipu, Moonshot etc. | Yes, context sent to external vendor | Lower per‑token pricing | Cost‑sensitive work, access to niche model variants |
| Local‑model mode | Ollama‑served open‑weights models (Qwen, DeepSeek‑distilled) | No | Hardware power consumption only | Privacy‑critical workflows, fully‑offline testing |
Select your target path first. Official‑API users prepare valid API credentials. Third‑party‑API users obtain keys from corresponding service platforms. Teams targeting fully‑offline operation must validate that local RAM and VRAM satisfy the selected open‑model’s hardware prerequisites.
2. Installation Steps and Critical Node.js Version Pitfall
Codex CLI is implemented in Node.js. Two primary installation routes exist: global installation via npm, or direct execution of pre‑compiled binary artifacts distributed by OpenAI. The npm route is recommended, as future version upgrades require only one shell command.
A frequently‑encountered gotcha relates to Node.js runtime versions. Official documentation specifies minimum support at Node.js 20.x. Practical hands‑on testing demonstrates best stability with Node.js 22.x. Legacy releases such as 16.x or 18.x will not necessarily throw obvious installation errors. Instead, symptoms include missing‑command failures (codex: not found), broken dependency resolution, or corrupted TUI rendering once the Codex terminal interface launches. These confusing malfunctions waste significant debugging hours.
Verify local runtime versions before proceeding:
node --version
npm --versionIf your environment falls below the supported baseline, upgrade Node.js via system package managers or nvm version‑management tooling.
Option A: npm global install (Recommended)
npm install -g @openai/codexValidate successful installation:
codex --versionOption B: Pre‑built binary packages
Download platform‑specific compiled binaries from OpenAI’s release repository. This path suits servers where modifying global npm environments is prohibited. After downloading, place the binary within system PATH so the codex shell command becomes globally accessible.
> Note for Windows users: PowerShell execution‑policy restrictions may block binary invocation. Adjust execution policies according to local security rules before running the executable.
3. Core Configuration: Understanding config.toml
Codex CLI reads runtime settings primarily from ~/.codex/config.toml under the user’s home directory. Project‑specific configuration can also be placed inside .codex/config.toml within individual repositories. Important behavioural detail: project‑level configuration will only load when that repository is marked as trusted, and takes higher precedence over the global user‑scope file. Always create a backup copy before editing configuration files.
Several essential configuration keys govern fundamental agent behaviour:
model_provider: Selects target model backend (openai, ollama, litellm or custom compatible endpoints).model: Defines logical model identifier invoked for agent tasks.approval_policy: Controls whether file‑write and shell operations require interactive user confirmation. Typical values:on‑request,always‑allow.env_key: Points to the name of environment variables holding API secrets; raw secret strings should never be hard‑coded inside TOML files.
Minimal example for official OpenAI‑API mode:
model_provider = "openai"
model = "gpt‑5‑codex"
approval_policy = "on‑request"Set your API key within shell environment variables instead of embedding secrets inside configuration:
export OPENAI_API_KEY="sk‑xxxxxx"Two authentication mechanisms are supported: API‑key mode and OAuth login mode. API‑key mode is better suited for scripted, server‑side and CI‑automation usage. OAuth is primarily intended for interactive human‑user sessions synchronised with ChatGPT accounts. For local automated workflows, API‑key authentication is preferred.
4. Connecting to Third‑Party OpenAI‑Compatible Endpoints
Many developers want Codex CLI to work with alternative model vendors that implement the OpenAI‑compatible REST schema. You define additional providers under the [model_providers.*] TOML section. Each entry supplies display name, base_url pointing at the vendor’s /v1 endpoint, and the environment‑variable name storing credentials.
Sample configuration fragment for DeepSeek‑compatible access:
model_provider = "deepseek"
model = "deepseek‑coder‑v3"
[model_providers.deepseek]
name = "DeepSeek API"
base_url = "https://api.deepseek.com/v1"
env_key = "DEEPSEEK_API_KEY"
wire_api = "responses"> Critical detail: Codex CLI defaults to the Responses API (/v1/responses) rather than classic chat completions. Third‑party gateways must support this interface; otherwise you will observe request failures even when standard chat‑completion calls work via curl.
For teams operating multi‑model workloads, a dedicated intermediary can abstract heterogeneous provider endpoints, centralising routing, quota tracking and error‑handling logic.
5. Full Off‑line Workflow: Integrating Codex CLI with Ollama
Ollama simplifies local deployment of open‑weight coding‑specialised large‑models such as Qwen‑Coder and DeepSeek‑Coder. Combined with Codex CLI, this stack delivers fully offline AI‑assisted coding capability, with zero source‑code context transmitted to external network services.
Step 1: Install Ollama
On Linux:
curl -fsSL https://ollama.com/install.sh | sh
ollama --versionWindows and macOS users download GUI installers directly from ollama.com. Confirm the Ollama background service is active, listening by default on http://127.0.0.1:11434.
Step 2: Pull your selected coding‑optimised model
ollama pull qwen3‑coder:14b‑instructChoose model parameter magnitude matching your available VRAM; larger variants deliver superior complex‑refactoring performance but consume substantially more graphics memory.
Step 3: Configure Codex CLI for Ollama backend
Edit ~/.codex/config.toml:
model_provider = "ollama"
model = "qwen3‑coder:14b‑instruct"
approval_policy = "on‑request"
[model_providers.ollama]
name = "Local Ollama"
base_url = "http://localhost:11434/v1"
env_key = "OLLAMA_API_KEY"
wire_api = "responses"Local Ollama deployments frequently leave OLLAMA_API_KEY environment variable blank.
Step 4: Launch Codex CLI with local‑model profile
codexYou may also start directly with the oss flag for rapid ad‑hoc testing:
codex --oss -m qwen3‑coder:14b‑instructValidation test: inside the Codex TUI, submit a simple task such as “generate a small sample Python utility function”. Confirm that network traffic does not leave your local host by inspecting Ollama service logs.
Important caveats for Ollama mode:
- Not every open‑weight model implements tool‑call capabilities well. Prefer variants explicitly fine‑tuned for agent and function‑call scenarios.
- Context‑window size limits apply. Models with insufficient context capacity will fail on multi‑file repository‑scale analysis.
- Even when inference runs locally, Codex CLI itself may emit anonymised usage telemetry. Review telemetry‑suppression settings if you require strict privacy.
6. Extending Workflows with LiteLLM Proxy Layer
When you frequently switch between OpenAI official APIs, multiple third‑party vendors and local Ollama instances, manual rewriting of config.toml entries becomes error‑prone. LiteLLM acts as a local model‑abstraction proxy. You configure all upstream providers once inside litellm_config.yaml. Codex CLI then points solely toward LiteLLM’s unified local base_url. Model‑name mapping, rate‑limiting, fail‑over and token‑consumption logging are handled within the proxy layer.
High‑level architecture:
> Codex CLI → LiteLLM local proxy → Multiple upstream model back‑ends (OpenAI / DeepSeek / Ollama / others)
Relevant fragment of Codex config.toml pointing to local LiteLLM:
model_provider = "litellm"
model = "qwen3‑coder:14b‑instruct"
[model_providers.litellm]
name = "LiteLLM Proxy"
base_url = "http://127.0.0.1:4000/v1"
env_key = "LITELLM_API_KEY"
wire_api = "responses"This pattern decouples your Codex‑agent configuration from upstream‑provider credential churn. When you need to swap or add new model services, you only modify the LiteLLM proxy configuration without touching Codex settings.
7. Common Troubleshooting Checklist
7.1 Command codex cannot be found
- Verify Node.js/npm global binary path is present inside system
PATH. - Re‑run
npm install -g @openai/codex. - Confirm you are not using unsupported old Node.js releases.
7.2 Model API request returns 404 / endpoint‑not‑found
- Check whether upstream gateway implements the
/v1/responsesResponses‑API schema, not only classic chat completions. Many third‑party services only implement chat completions and cannot work out‑of‑the‑box with default Codex CLI. - Double‑check
base_urltrailing‑slash formatting.
7.3 Ollama model loads, but agent produces incomplete tool‑call outputs
- Select agent‑optimised model variants; generic chat‑oriented open models often perform poorly for tool‑use workflows.
- Increase context‑window parameters within Ollama model configuration.
7.4 Project‑level .codex/config.toml has no effect
- Confirm the current working‑directory repository is marked as trusted by Codex CLI. Untrusted directories skip project‑scope configuration loading for security reasons.
8. Conclusion
Local‑mode Codex CLI shifts control of AI coding‑agent workflows onto developer‑managed infrastructure. Three distinct deployment pathways — official cloud APIs, third‑party compatible providers, and fully‑offline Ollama‑backed open‑models — serve different combinations of performance requirements, privacy constraints and budget limits.
Successful operation hinges on several easily‑missed technical details: meeting minimum Node.js runtime version requirements, understanding the Responses‑API dependency, separating secrets from static TOML configuration files, and realising that project‑level configuration only activates for trusted repositories. Adding a proxy abstraction layer such as LiteLLM further simplifies multi‑provider switching, centralising quota management and request logging.
When planning adoption, weigh trade‑offs: official OpenAI APIs deliver top‑tier reasoning quality at token‑metered cost; third‑party services offer cost‑saving opportunities; local Ollama deployment maximises data privacy while imposing hardware‑resource burdens. Teams should perform validation testing with their own repository code before rolling local Codex‑agent workflows into production CI or daily development loops.






