How to Connect AI Coding CLI Tools to a Unified API Gateway with Two Environment Variables
Switching between multiple AI models and coding tools often means juggling separate accounts, keys, and billing. This guide shows how to point any CLI-based AI coding tool at a unified API gateway using just two environment variables—one for the gateway URL and one for authentication—covering configuration persistence, common pitfalls like 404 and 401 errors, and how to verify model routing actually works.
Why Bother
In real-world development, many teams and individuals use several AI coding tools together, backed by multiple model providers. The problems that come with this are obvious:
- Fragmented accounts: Each provider has its own account system, keys are managed in scattered places, and rotation or revocation is costly;
- Inconsistent protocols: Provider APIs differ, so each tool needs separate adaptation;
- Complex billing and reconciliation: Topping up and reconciling across multiple channels makes unified usage tracking difficult;
- Tedious model switching: Comparing coding performance across models means editing configurations in every tool individually.
The solution is a common industry pattern: an aggregation gateway. All tools point to a single gateway address and share one API Key, while the gateway handles forwarding, authentication, and consolidated billing. This article focuses on the most common scenario—connecting CLI-based AI coding tools (which typically control their request target via environment variables) to such a gateway. The whole process only requires setting two environment variables.
Prerequisites
Before getting started, confirm two things:
1. You have a working gateway service. This can be a self-hosted model proxy layer, or a model access service from a cloud provider (often listed under categories like “model gateway” or “LLM platform”). Create an API Key in the relevant console and store it safely. It’s a good idea to validate the setup with a small quota first before moving to production use.
2. The AI coding CLI tool is installed locally. These tools generally depend on a Node.js runtime—install an LTS version, then install the tool globally via a package manager, for example:
npm install -g <tool-package-name>
If you can launch the tool’s command and enter its interactive interface, the installation succeeded. Skip this step if it’s already installed.
Step 1: Point the Tool at the Gateway via an Environment Variable
These CLI tools usually default to the official API endpoint, and which service receives the requests is almost always determined by an environment variable of the BASE_URL form. Point it at your gateway:
export BASE_URL="https://your-gateway-domain/api"
Here’s a high-frequency pitfall: the path suffix must strictly follow the gateway’s documentation. Many gateways automatically append version paths internally (such as /v1/messages). If you manually add the version segment at the end of the URL, the final request becomes something like /v1/v1/messages, which returns a 404. When you hit a 404, the first thing to check is whether the URL has an extra path segment.
To make the configuration persistent, there are two options:
- Add it to your shell config file: Add the export statement to
~/.zshrc(or~/.bashrcfor bash users), then runsourceor open a new terminal window to apply it; - Add it to the tool’s global config file: Most such tools support an
envfield in asettings.json(or similar JSON config) in your user directory. This works for both the command line and background subprocesses, and is more reliable:
{"env": {"BASE_URL": "https://your-gateway-domain/api","AUTH_TOKEN": "your-gateway-api-key"}}
Security reminder: Config files containing keys should only live in your home directory—never in a project directory committed to a repository. If a same-named config file exists inside a project, make sure it’s listed in .gitignore.
Step 2: Configure the Authentication Token
The second environment variable carries the API Key:
export AUTH_TOKEN="the-gateway-api-key-you-created"
This step looks simple but hides the most pitfalls. Let’s go through them:
1. Don’t set both types of auth variables. These tools typically have two auth variables: one for gateway/proxy scenarios (the one used here) and one for direct official connections. They map to different request headers, and if both exist, the tool will report an auth conflict warning with unpredictable behavior. If you’ve set the other one before, clean it up first:
unset ANTHROPIC_API_KEY 2>/dev/null
To audit your environment, run env | grep -i key to check for leftover variables.
2. Use straight quotes. When copying commands from web pages or chat windows, it’s easy to pick up curly quotes (" "). These become part of the key, adding invisible characters to the auth string and resulting in a 401. Type the quotes manually, or verify hidden characters with cat -A or similar after pasting.
3. Clear stale login state. If you previously logged into the tool with an official account, cached credentials in the session may interfere with gateway authentication. Run the logout command first (usually a logout subcommand), then restart the terminal to ensure all requests use the new token.
4. Manage the key’s lifecycle. Never hardcode keys into scripts or commit them to Git. If a key leaks, revoke it immediately in the gateway console and issue a new one. A stricter approach is injecting environment variables through a secrets management tool (such as the system keychain or a dedicated secrets manager) to avoid plaintext on disk.
Switching and Verifying Models
One of the core benefits of a gateway is model switchability. Most gateways determine the actual forwarded model via request parameters or key-level routing rules. Two practical tips:
- Don’t hard-bind a key to a specific model. Some gateways let you lock a model to a key. Once locked, requests are silently routed to a fixed model with no visible difference in the tool’s UI—you think you’re comparing models, but you’ve been testing the same one all along, and your conclusions will be completely skewed. Always make sure the routing rules are explicit and observable before running comparisons.
- Run a minimal verification. After switching, have the tool perform a simple task and check the gateway’s request logs to confirm the actual model hit, token usage, and response latency match expectations before putting it into real use.
Troubleshooting Quick Reference
| Symptom | Likely Cause | Fix |
|---|---|---|
| 404 | Extra version path segment appended to URL | Correct BASE_URL per the gateway documentation |
| 401 | Curly quotes in the key, expired key, or leftover auth variables | Re-type the command, unset old variables |
| Auth conflict warning | Both types of auth variables set | Keep only the gateway auth variable |
| Requests still hitting the official endpoint | Environment variables not taking effect | Check shell config and source it, or write to the tool’s global config |
| Model switching has no effect | Key locked to a model, or gateway routing rules overriding request parameters | Confirm routing configuration with the gateway provider |
Wrapping Up
The entire integration boils down to two things: redirect the request target with a BASE_URL-style variable, and replace credentials with the auth variable. Combined with config persistence and a minimal verification routine, the switch takes only a few minutes—after that, multiple tools share one account and one bill, and comparing models takes a single parameter change. This “decoupling tools from the access layer” approach isn’t just useful for individual developers; for teams that need centralized control over model usage and cost, consolidating a fragmented access layer into a gateway frees up attention for the actual coding work.
