API ключ для Codex: подключение за 5 минутAPI key for Codex: set up in 5 minutes

Для Codex CLI в терминале и Codex в VS Code настройка одна: файл конфига и ключ в переменной окружения. Вставь ключ в поле ниже — команды соберутся под тебя.Codex CLI in the terminal and Codex in VS Code share one setup: a config file and your key in an environment variable. Paste your key below and the commands will be built for you.

Base URL
API KeyAPI Key

Ключ не отправляется с этой страницы: команды собираются локально в браузере. Без галочки выше ключ исчезнет после закрытия страницы. Ключ — как пароль: не показывай его на скриншотах, не отправляй в чаты и не добавляй в Git. Нет ключа — зарегистрируйся: личный ключ выпустится сам. Кнопки скачивания готовых файлов (settings.json, codex-setup.bat) — на странице «Подключение» — генератор конфигураций.Your key never leaves this page: commands are assembled locally in your browser. Without the checkbox above, the key disappears when you close the page. Treat the key like a password: never show it in screenshots, chats, or Git. No key yet? Register — a personal key is issued automatically. Download buttons for ready-made files are on the full connection page.

Как подключить

Какая у тебя система?Your operating system?

API ключ для CodexAPI key for Codex

Ключ из поля выше автоматически подставляется в команды и конфиги.Your key from the field above is inserted into the commands and configs automatically.

1

Установи Codex

Уже стоит — переходи к шагу 2.

  1. Поставь Node.js (бесплатно, скачивается с nodejs.org).
  2. В терминале выполни: npm install -g @openai/codex
2

Создай файл конфига

Один файл — работает и терминал, и VS Code.

Windows. Нажми Win+R, вставь notepad %USERPROFILE%\.codex\config.toml и нажми Enter — Блокнот предложит создать файл, соглашайся.

macOS / Linux. Создай файл ~/.codex/config.toml в любом текстовом редакторе (папки .codex нет — создай её).

Вставь блок (адрес API уже подставлен) и сохрани:

Строка preferred_auth_method = "apikey" приказывает Codex работать с ключом, а не с аккаунтом ChatGPT. Без неё Codex может молча игнорировать твой конфиг — это самая частая проблема подключения.

3

Ключ — в переменную окружения

Выбери систему и вставь команду целиком.

Windows. Открой PowerShell (Пуск → набери powershell), вставь команду и нажми Enter:

macOS / Linux. Открой Terminal, вставь блок целиком и нажми Enter:

4

Выйди из аккаунта ChatGPT и перезапусти

Обязательный шаг, если ты когда-либо входил в Codex под аккаунтом.

  1. В терминале выполни: codex logout (если напишет, что ты не входил — просто иди дальше).
  2. Полностью закрой все окна терминала и VS Code, открой заново.
  3. Запусти codex и задай вопрос — пришёл ответ, всё работает.

Codex в VS Code отдельной настройки не требует: расширение читает тот же config.toml и ту же переменную. После шагов выше просто полностью перезапусти VS Code.

Windows, не любишь команды: на странице «Подключение» есть установщик одним кликом — скачанный .bat сам создаст конфиг и пропишет ключ.

1

Install Codex

Already installed? Skip to step 2.

  1. Install Node.js (it's free, downloaded from nodejs.org).
  2. In the terminal, run: npm install -g @openai/codex
2

Create the config file

One file — works for both the terminal and VS Code.

Windows. Press Win+R, paste notepad %USERPROFILE%\.codex\config.toml and hit Enter — Notepad will offer to create the file, accept.

macOS / Linux. Create the file ~/.codex/config.toml in any text editor (there is no .codex folder yet — create it).

Paste the block (the API address is already filled in) and save:

The line preferred_auth_method = "apikey" tells Codex to work with the key, not with a ChatGPT account. Without it Codex may silently ignore your config — this is the most common setup problem.

3

Put the key into an environment variable

Pick your system and paste the whole command.

Windows. Open PowerShell (Start → type powershell), paste the command and hit Enter:

macOS / Linux. Open Terminal, paste the whole block and hit Enter:

4

Sign out of the ChatGPT account and restart

A required step if you have ever signed in to Codex with an account.

  1. In the terminal, run: codex logout (if it says you were not signed in — just move on).
  2. Close all terminal windows and VS Code completely, then open them again.
  3. Run codex and ask something — an answer came back, everything works.

Codex in VS Code needs no extra setup: the extension reads the same config.toml and the same variable. After the steps above, simply restart VS Code completely.

Windows, don't like commands? The full connection page has a one-click installer — the downloaded .bat creates the config and writes the key itself.

Частые ошибки

Ошибка 401, и в тексте упоминается api.openai.com
Codex работает под твоим аккаунтом ChatGPT и игнорирует твой ключ — запросы уходят мимо. Лечится так: codex logout, в config.toml должна быть строка preferred_auth_method = "apikey", затем полный перезапуск терминала. Ключ при этом рабочий — проверить можно на странице «Баланс и логи».
401 Unauthorized: Missing bearer or basic authentication
Ключ не подобрался из переменной окружения. Проверь: Windows — в PowerShell выполни [Environment]::GetEnvironmentVariable("CUSTOM_API_KEY","User"); macOS/Linux — echo $CUSTOM_API_KEY. Пусто — задай ключ ещё раз и полностью перезапусти терминал.
«Лимит использования исчерпан» после долгой работы
Скорее всего это не поломка: либо исчерпан баланс ключа (посмотри на странице баланса), либо агент гоняет дорогую модель. Для длинных задач поставь model = "gpt-5.6-terra" — та же работа обходится в разы дешевле.
Ключ не принимается, проверка падает
Base URL должен заканчиваться на /v1, ключ — начинаться с sk- и быть скопирован целиком, без пробелов в начале и конце.
Error 401, and the message mentions api.openai.com
Codex is running under your ChatGPT account and ignores your key — requests go the wrong way. The fix: run codex logout, make sure config.toml has the line preferred_auth_method = "apikey", then fully restart the terminal. The key itself is fine — you can check it on the Balance and logs page.
401 Unauthorized: Missing bearer or basic authentication
The key was not picked up from the environment variable. Check: Windows — in PowerShell run [Environment]::GetEnvironmentVariable("CUSTOM_API_KEY","User"); macOS/Linux — echo $CUSTOM_API_KEY. Empty? Set the key again and fully restart the terminal.
A “usage limit” error after working for a while
Most likely nothing is broken: either the key's balance has run out (check the balance page), or the agent is running an expensive model. For long tasks set model = "gpt-5.6-terra" — the same work costs several times less.
The key is not accepted, verification fails
The Base URL must end with /v1, the key must start with sk- and be copied in full, with no spaces at the start or end.

Ограничения и совместимость

Сервер поддерживает оба транспорта Codex: обычные запросы (Responses API) и потоковый WebSocket.

Установщик .bat одним кликом есть только для Windows; на macOS и Linux настройка — два шага руками, они описаны выше.

Codex активно обновляется: в новых версиях могут отличаться названия пунктов и настройки входа (например, preferred_auth_method в свежем справочнике фигурирует как forced_login_method = "api"). Если одна строка не сработала — попробуй вторую и сверься с официальной документацией Codex.

Не храни ключ в скриншотах, чатах и репозиториях — это доступ к твоему балансу.

The server supports both Codex transports: regular requests (Responses API) and the streaming WebSocket.

The one-click .bat installer is Windows-only; on macOS and Linux the setup is the two manual steps described above.

Codex updates often: newer versions may rename menu items and sign-in settings (for example, preferred_auth_method appears as forced_login_method = "api" in recent documentation). If one line doesn't work, try the other and check the official Codex documentation.

Never keep the key in screenshots, chats, or repositories — it gives access to your balance.

Вопросы и ответы

Где находится config.toml?
Windows: %USERPROFILE%\.codex\config.toml, macOS и Linux: ~/.codex/config.toml. Если папки нет — создай её.
Нужно ли отдельно настраивать Codex в VS Code?
Нет. Расширение Codex читает тот же файл config.toml и ту же переменную окружения. После настройки полностью перезапусти VS Code.
Почему Codex обращается на api.openai.com вместо моего Base URL?
Потому что внутри Codex активен вход под аккаунтом ChatGPT — он перебивает кастомный провайдер. Выполни codex logout, добавь preferred_auth_method = "apikey" в config.toml и полностью перезапусти терминал.
Какую модель выбрать для Codex?
Для агентных задач — gpt-5.6-terra: баланс цены, скорости и качества. Максимум качества — gpt-5.6-sol, но расход заметно выше. Полный список — в таблице моделей.
Where is config.toml located?
Windows: %USERPROFILE%\.codex\config.toml; macOS and Linux: ~/.codex/config.toml. If the folder doesn't exist — create it.
Does Codex in VS Code need separate setup?
No. The Codex extension reads the same config.toml file and the same environment variable. After setup, restart VS Code completely.
Why does Codex hit api.openai.com instead of my Base URL?
Because signing in with a ChatGPT account is active inside Codex — it overrides the custom provider. Run codex logout, add preferred_auth_method = "apikey" to config.toml and fully restart the terminal.
Which model should I pick for Codex?
For agent tasks — gpt-5.6-terra: the best balance of price, speed and quality. Maximum quality — gpt-5.6-sol, but it burns tokens noticeably faster. Full list — in the model table.