langchain-ai/deepagents · error · ModelConfigError

Failed to initialize Codex model '{provider}:{model_name}':

Error message

Failed to initialize Codex model '{provider}:{model_name}': {exc}

What it means

Catch-all translation: any exception from `_codex.build_chat_model` that is not a missing token (FileNotFoundError) or expired auth (CodexAuthExpiredError) is wrapped in ModelConfigError as `Failed to initialize Codex model '<provider>:<model>'`. The original exception is chained, so the root cause is in the traceback.

Source

Thrown at libs/code/deepagents_code/config.py:5915

            msg = (
                "Not signed in to ChatGPT. Run `/auth` and select "
                "openai_codex to sign in with your ChatGPT account."
            )
            raise MissingCredentialsError(msg, provider=provider, env_var=None) from exc
        except _codex.CodexAuthExpiredError as exc:
            # A token exists but its refresh token is dead. Route through the
            # same `MissingCredentialsError` recovery path as a missing token
            # (which the retry flow re-attempts after `/auth`) instead of the
            # generic `ModelConfigError` below, which would not offer sign-in.
            msg = (
                "ChatGPT session expired. Run `/auth` and select openai_codex "
                "to sign in again."
            )
            raise MissingCredentialsError(msg, provider=provider, env_var=None) from exc
        except Exception as exc:
            spec = f"{provider}:{model_name}"
            msg = f"Failed to initialize Codex model '{spec}': {exc}"
            raise ModelConfigError(msg) from exc
    elif class_path:
        model = _create_model_from_class(class_path, model_name, provider, kwargs)
    else:
        model = _create_model_via_init(model_name, provider, kwargs)

    resolved_provider = provider or getattr(model, "_model_provider", provider)
    from deepagents_code.cost_tracking import _set_configured_model_metadata

    _set_configured_model_metadata(model, model_name, resolved_provider)

    # Apply profile overrides from config.toml (e.g., max_input_tokens)
    if provider:
        config_profile_overrides = config.get_profile_overrides(
            provider, model_name=model_name
        )
        if config_profile_overrides:
            _apply_profile_overrides(
                model,

View on GitHub (pinned to a1af029e6e)

Solutions

  1. Read the chained traceback (`from exc`) for the root cause and fix that directly.
  2. Delete the Codex auth file and re-run `/auth` to regenerate a clean one.
  3. Ensure the `codex` CLI is installed and current (`codex --version`, upgrade as needed).
  4. Check network/proxy access to ChatGPT auth endpoints.

Example fix

// before
$ dcode -m openai_codex:gpt-5-codex
// ModelConfigError: Failed to initialize Codex model ... (JSONDecodeError)
// after
$ rm ~/.codex/auth.json   # remove corrupted auth file
# inside dcode: /auth -> openai_codex -> sign in
Defensive patterns

Strategy: try-catch

Validate before calling

import json
from pathlib import Path

auth_path = Path.home() / ".codex" / "auth.json"
if auth_path.exists():
    try:
        json.loads(auth_path.read_text())
    except json.JSONDecodeError:
        auth_path.unlink()  # corrupted; force a clean /auth
        print("Codex auth file corrupted; run /auth to sign in again.")

Try / catch

try:
    model = build_model("openai_codex", model_name)
except ModelConfigError as exc:
    logger.error("Codex init failed: %s", exc.__cause__)  # inspect root cause
    reset_codex_auth()      # delete auth file + ensure codex CLI present
    run_auth_flow("openai_codex")
    model = build_model("openai_codex", model_name)

Prevention

When it happens

Trigger: Constructing the Codex chat model when build_chat_model fails for other reasons: malformed or corrupted auth file (present but unparseable JSON), missing `codex` CLI binary the integration shells out to, network failure during token refresh that isn't classified as auth-expired, or an unsupported model name.

Common situations: Hand-editing or truncating the Codex auth file; upgrading/downgrading the codex CLI out of sync with dcode; a partially written auth file after a killed sign-in; firewall/proxy blocking the token endpoint without producing the specific expired-auth error.

Related errors


AI-assisted analysis of langchain-ai/deepagents@a1af029e6e (2026-08-29). Data as JSON: /api/errors/33bf4a8a4abc6e10. Report an issue: GitHub.