How to Connect a Domestic LLM API to Your AI Coding Tool
This guide explains how to connect a domestic (China-based) large language model API to an AI coding tool. It covers why a replaceable model backend matters, how protocol-compatible endpoints work through environment variables, a three-step setup process, the limits of environment variables when running multiple models, and how a local routing layer centralizes credentials, switching, and observability. It also includes model selection criteria, common troubleshooting checks, and security and compliance notes.
1. Why Connect an LLM API to an AI Coding Tool
AI coding tools (the terminal- or editor-based coding agents that read and write code and run commands) do not ship with a built-in model. They act more like a shell: parsing requests, assembling context, and calling the tool chain, while the actual reasoning comes from a backend LLM API. This shell-plus-model layering has one immediate benefit: the model is replaceable.
For developers, replaceable means three things:
- Cost control: Models from different vendors and different parameter sizes vary widely in price. Low- and mid-complexity work such as everyday completion, unit test generation, and log analysis can go to a model with better price-performance.
- Supply elasticity: When a single provider hits rate limits, queues, or an outage, you can switch to a backup channel quickly instead of stalling the whole development chain.
- Capability fit: Long-context understanding, complex refactoring, and quick Q&A place different demands on a model. Routing by scenario is usually more economical than expecting one model to do everything.
Over the past two years, a batch of domestic (China-based) LLMs has kept improving on general coding tasks, and some have stayed near the top of public usage-volume rankings for a long time. That is the practical basis for “acceptable efficiency at lower cost,” and it has turned swapping models inside an AI coding tool from a hobbyist trick into a routine engineering choice.
2. The General Mechanism: A Protocol-Compatible Layer
Most AI coding tools let you set a custom backend address. Under the hood, the vendor exposes an endpoint that is compatible with the protocol used by mainstream coding tools. You only need to tell the tool three things: where to send requests (the address), what identity to use (the key), and which model to use (the model identifier).
These three are usually injected through environment variables:
# Generic shape (replace the address and model identifier with the values in your service's official documentation)export ANTHROPIC_BASE_URL="https://<your-service-endpoint>"export ANTHROPIC_AUTH_TOKEN="<your-API-key>"export ANTHROPIC_MODEL="<primary-model-identifier>"# Some tools assign models per tier; you can point all tiers at the same modelexport ANTHROPIC_DEFAULT_HAIKU_MODEL="<primary-model-identifier>"export ANTHROPIC_DEFAULT_SONNET_MODEL="<primary-model-identifier>"export ANTHROPIC_DEFAULT_OPUS_MODEL="<primary-model-identifier>"
Note that tools typically have internal model tiers: a fast tier, a standard tier, and a high-capability tier. The fast tier handles lightweight work such as short replies and file summaries, the standard tier carries the main coding workload, and the high-capability tier handles complex reasoning. If your backend exposes only one model, point all three tiers at it. If it offers several sizes, you can configure each tier differently to cut cost further.
3. Setup in Three Steps
Step 1: Get a key. Create an access key in the console of the model service you want to use, and check its model identifiers and endpoint in the same place. A key is a sensitive credential: do not hardcode it into project files or commit it to a repository.
Step 2: Set the environment variables. Add the export lines above to your shell profile (~/.zshrc or ~/.bashrc) and run source to apply them. Writing them to a profile rather than exporting them ad hoc avoids resetting them every time you open a new terminal.
Step 3: Start and verify. Launch the AI coding tool and validate the chain with a minimal task:
Read the README file in the current directory and summarize the project's purpose in three sentences.
If the response comes back and matches the file, the address, key, and model identifier are all correct.
4. Running Multiple Models: Where Environment Variables Break Down
Environment variables are fine for a single model, but problems appear as soon as you need to switch between backends:
- Environment variables are process-level, so a change requires reopening the terminal or running
sourceagain. - Tool instances already running in the same terminal do not pick up the change.
- If different projects need different models, they easily contaminate each other, which is painful to debug.
- Keys scattered across multiple profiles are expensive to rotate and revoke.
One low-cost mitigation is to wrap the configuration in a shell function or alias so a command replaces manual editing:
use_model() {export ANTHROPIC_BASE_URL="$1"export ANTHROPIC_AUTH_TOKEN="$2"export ANTHROPIC_MODEL="$3"export ANTHROPIC_DEFAULT_HAIKU_MODEL="$3"export ANTHROPIC_DEFAULT_SONNET_MODEL="$3"export ANTHROPIC_DEFAULT_OPUS_MODEL="$3"}# Usage: use_model <address> <key> <model-identifier>
This fixes the “editing is annoying” part, but not the “must reopen the terminal” part or centralized key management.
5. A More Engineering-Driven Approach: Add a Local Routing Layer
Once switching becomes a frequent action, the more sensible direction is to take model selection out of environment variables and hand it to a local request routing layer. The basic structure looks like this:
AI coding tool ──► local routing service (fixed port) ──► backend A (a model service)│ ──► backend B (another model service)└── reads routing config (model alias → address/key/model identifier)
This yields four benefits:
- Switching does not touch environment variables: The tool always points at the local router; switching only changes the routing config and takes effect with one command, with no terminal restart.
- Centralized key custody: Credentials live only in the routing config, and the tool side never handles the real key.
- Room for policies: The routing layer is a natural enforcement point for retries, timeout circuit breaking, task-type routing, and usage counting.
- Observability: With all requests passing through one entry point, logging and cost accounting become straightforward.
A minimal routing config might look like this (illustrative, not tied to a specific implementation):
{"current": "general","profiles": {"general": {"baseURL": "https://<service-address>","apiKey": "<key>","model": "<model-identifier>"},"backup": {"baseURL": "https://<backup-service-address>","apiKey": "<key>","model": "<model-identifier>"}}}
On the tool side, you only point at the local address:
export ANTHROPIC_BASE_URL="http://127.0.0.1:<port>"export ANTHROPIC_AUTH_TOKEN="local"
Switching then reduces to editing the current field or running a wrapped switch command. If your model service’s official documentation provides a configuration script, prefer it to reduce manual maintenance.
6. Do Not Choose a Model by Rankings Alone
Usage-volume rankings reflect overall popularity, which is not the same as whether a model suits your tasks. Run a small head-to-head comparison on your own real codebase, measuring:
- Instruction following: Does it respect constraints strictly and leave unrelated files untouched?
- Long-context stability: Does it drop key constraints when given a larger repository context?
- Tool-call reliability: Are the arguments for reading and writing files and running commands correct?
- Runnability of generated code: First-pass success, not code that merely looks right.
- Latency and rate limits: Is queueing during peak hours acceptable?
- Cost per task: Compare the cost of completing a typical task, not the unit price.
Make the evaluation reproducible: fix 10–20 representative tasks, fix the prompt and parameters such as temperature, record pass rate and elapsed time, and build your own baseline table.
7. Troubleshooting Common Issues
- 401/403: The key is invalid, not applied, or overridden by another configuration. Run
env | grep ANTHROPICto confirm the effective values. - 404 or path errors: Check whether the endpoint is missing a path suffix the service requires.
- Model not found: The model identifier is misspelled or the version has been retired; defer to the service’s documentation.
- Config changes not taking effect: Environment variables are read at process start, so restart the tool. If you use a routing layer, check whether the config hot-reloads.
- Truncated responses: Adjust the tool’s maximum output length setting, or switch to a tier with more context headroom.
- Unexpected cost: Check whether every tier is pointing at the high-capability model.
8. Security and Compliance
Keep keys out of repositories, logs, and screenshots. For team settings, prefer a key policy that supports rotation, spending limits, and auditing. Feed call logs and cost dashboards into your regular monitoring and alerting, with budget threshold reminders. If internal corporate code is involved, confirm that the service’s data handling terms meet internal compliance requirements, and consider a private deployment option if necessary.
9. Summary
The core of the setup is three steps: get a key, inject the three key environment variables, and verify at startup. The real engineering value shows up after step two: when switching becomes routine, replace manual environment variable edits with a local routing layer that consolidates credentials, policies, and observability in one place. As for which model to pick, let
