Codex CLI: How to Connect a Third-Party AI Model

    Learn how to install Codex CLI, configure a third-party model provider with an OpenAI-compatible API, test connectivity, and troubleshoot common errors. This guide also covers API key security, usage costs, and data privacy checks before using the tool on real projects.

    Terminal-based AI coding tools run directly in the command line rather than inside a specific IDE. They can read project files, execute commands, and generate code changes, making them useful for tasks that span multiple files.

    This guide uses OpenAI’s open-source Codex CLI to walk through installation, configuration for a third-party model with an OpenAI-compatible API, connectivity testing, and troubleshooting. Other terminal-based coding tools follow a similar process, but configuration filenames and fields may differ. Check the official documentation for your tool.

    1. Prepare Your Environment

    Operating system

    You can use macOS or a mainstream Linux distribution directly. On Windows, installing inside WSL2 is recommended. Consult the official documentation for native PowerShell compatibility.

    Node.js

    Codex CLI is distributed through npm, so Node.js is required. Use nvm or fnm to install an LTS release, and check the official README for the minimum supported version.

    Check your current versions:

    1. node -v
    2. npm -v

    If Node.js is not installed, install and activate an LTS release with nvm:

    1. nvm install --lts
    2. nvm use --lts

    With fnm, use fnm install --lts followed by fnm use lts-latest.

    Network access

    If your network requires a proxy or custom certificates, configure those requirements in your terminal first. For example, set a proxy variable:

    1. export HTTPS_PROXY="http://your-proxy-address:port"

    In a corporate environment, also confirm that the firewall allows connections to the model provider’s domain. Otherwise, connectivity tests may repeatedly time out, making it difficult to identify the failing layer.

    2. Install Codex CLI

    Install the package globally:

    1. npm install -g @openai/codex

    Check the version and executable location:

    1. codex --version
    2. which codex

    In Windows PowerShell, use Get-Command codex instead of which codex.

    Two installation issues are especially common.

    “command not found”

    The npm global executable directory may not be in your PATH. Check the installation prefix:

    1. npm config get prefix

    On macOS and Linux, executables are located in the prefix’s bin directory. For example, a prefix of /usr/local means the executable directory is /usr/local/bin.

    Add that directory to your shell configuration file: ~/.zshrc for zsh or ~/.bashrc for bash. Then reload the corresponding file, such as with source ~/.zshrc, or open a new terminal.

    EACCES permission errors

    Avoid running global npm installs with sudo. Files installed this way belong to root, which can cause problems when upgrading or uninstalling packages.

    Using nvm to manage Node.js is a more reliable approach. If nvm is not an option, change npm’s global prefix to a directory owned by your user, then reinstall:

    1. npm config set prefix ~/.npm-global
    2. echo 'export PATH="$HOME/.npm-global/bin:$PATH"' >> ~/.zshrc
    3. source ~/.zshrc
    4. npm install -g @openai/codex

    This example assumes zsh; use the corresponding configuration file for your shell.

    Changing the prefix does not move previously installed files. Be sure to run the final installation command.

    3. Gather Your Provider Details

    In your model provider’s console, obtain the following three items:

    • Base URL: Often ends in /v1, but the exact path depends on the provider. This guide uses the placeholder https://api.example-provider.com/v1.
    • Model ID: Must exactly match the provider’s identifier, including capitalization and version suffixes. The placeholder in this guide is example-model-name. Copy the actual ID from the provider’s model list.
    • API key: Create a key in the provider’s console. Keep it on your local machine; do not commit it to a repository or share it with others.

    Pass the key through an environment variable rather than placing it in the configuration file. To avoid recording the key in shell history, use silent input:

    1. read -s MY_PROVIDER_API_KEY && export MY_PROVIDER_API_KEY

    Putting an export statement containing the key directly in ~/.zshrc introduces two risks: the file may be synchronized to cloud storage or backups, and the key may be exposed if your dotfiles are committed to a repository.

    For persistent storage, use your operating system’s keychain or your team’s secrets management service. Keep any files containing secrets out of version control.

    4. Configure Codex CLI for a Third-Party Model

    Codex CLI uses the configuration file ~/.codex/config.toml. Create the directory if it does not exist:

    1. mkdir -p ~/.codex

    Add the following configuration, replacing the placeholders with your provider’s details:

    1. model = "example-model-name"
    2. model_provider = "myprovider"
    3. [model_providers.myprovider]
    4. name = "My Provider"
    5. base_url = "https://api.example-provider.com/v1"
    6. env_key = "MY_PROVIDER_API_KEY"
    7. wire_api = "chat"

    The fields serve the following purposes:

    • model: The model ID to call. It must exactly match the provider’s identifier.
    • model_provider: The selected provider. Its value must match the identifier in the [model_providers.xxx] table.
    • name: A display name for the provider. It does not affect API requests.
    • base_url: The API base address. A missing /v1, when required by the provider, is a common cause of 404 errors.
    • env_key: The name of the environment variable containing the API key—not the key itself.
    • wire_api: The API protocol. The example uses chat for Chat Completions. Providers supporting the Responses API require the corresponding supported setting. Check the current official documentation for the values accepted by your installed version; do not assume the example value is supported in every release. A protocol mismatch can cause requests to fail without an error message that clearly identifies this field.

    Restart Codex after changing the configuration so the new settings take effect.

    5. Test Connectivity

    Test from the lower layers upward. If a step fails, investigate that layer before proceeding.

    Step 1: Confirm that the environment variable is set

    This command checks whether the variable has a nonempty value without printing the key:

    1. test -n "$MY_PROVIDER_API_KEY" && echo "API key is set" || echo "API key is not set"

    If the key is not set, the current terminal cannot access the variable. A common cause is exporting it in a different terminal window.

    Step 2: Call the provider’s API directly

    Use curl to check network access and authentication:

    1. curl -sS "https://api.example-provider.com/v1/models" \
    2. -H "Authorization: Bearer $MY_PROVIDER_API_KEY"

    A model list response indicates that the address, path, and key are generally correct.

    Some providers do not implement the model-list endpoint. In that case, a 404 response does not necessarily mean the chat endpoint is unavailable; proceed to the next test.

    Step 3: Send a simple request through Codex CLI

    Start in an empty test directory to avoid exposing important project files or allowing unintended changes:

    1. mkdir -p ~/codex-test && cd ~/codex-test
    2. codex exec "Reply only with OK"

    codex exec runs a task non-interactively. The expected result is OK or a short response containing OK.

    To confirm the selected model and provider, run codex to enter the interactive interface. The model information shown at startup should match your configuration.

    Once testing succeeds, return to your real project. Codex CLI can read files in the working directory and may execute commands. Before using it for the first time, review its approval mode and sandbox settings, and inspect every generated code change.

    6. Troubleshoot Common HTTP Errors

    The following table covers three common error categories.

    Status code Common causes What to check How to resolve it
    401 Invalid, expired, or revoked key; environment variable not exported in the current terminal; extra spaces or newlines copied with the key The curl response body and the result of the test -n command Generate a new key in the provider’s console; repeat the silent input and export in the current terminal; confirm that env_key matches the variable name
    404 Missing /v1 or an incorrect base path; incorrect model ID, capitalization, or version suffix; wire_api does not match the provider’s supported protocol The response body, provider model list, and API documentation Correct base_url; copy the exact model ID from the provider’s list; verify and update wire_api
    429 Request rate exceeds the limit, or the account has exhausted its quota The Retry-After response header and the provider’s usage dashboard Wait before retrying; avoid rapid repeated requests; reduce concurrency; check available quota and, if necessary, upgrade the plan or request a higher limit

    Read the response body first: it often identifies the specific error. For other status codes, such as 403 or 5xx, follow the same approach and compare the message with the provider’s documentation.

    When reporting an issue, share only the status code and relevant error details. Do not paste a complete request containing credentials.

    Do not try to resolve 429 errors by repeatedly retrying without a delay. Frequent requests can worsen rate limiting and may consume remaining quota. Use exponential backoff instead, increasing the wait time between failed attempts.

    7. Pre-Deployment Checklist

    API key management

    • Keep keys out of code repositories. Add files containing secrets, such as .env, to .gitignore, and inspect staged changes before committing.
    • Create separate keys for local development, testing, and production so each can be revoked independently.
    • Rotate keys regularly. If you suspect a leak, revoke the affected key immediately and update every machine that uses it.
    • Do not record request headers or API keys in logs or monitoring systems.

    Usage and costs

    • Set monthly spending limits and usage alerts in the provider’s console.
    • Before deployment, estimate the cost of representative tasks and multiply it by the expected request frequency.
    • Review usage details regularly and investigate unexpected increases.

    Data privacy and compliance

    • File content read by Codex CLI may be sent to the model provider. Before working with customer data, credentials, internal architecture, or unpublished code, confirm that sending this information to a third party is permitted.
    • Review the provider’s privacy policy, including data retention periods, whether data is used for model training, and where data is stored.
    • Complete any organizational approvals for cross-border data transfers or third-party services before connecting the provider.
    • Do not put passwords, tokens, or personal information directly into prompts.

    After completing configuration, connectivity tests, and these checks, you can begin using the third-party model from your terminal. If a problem arises, identify the failing step first, then use the troubleshooting table to narrow down the cause.