How to Connect Claude Code to Domestic Alternative LLM APIs: A Practical Guide
Many developers have experienced long tasks being cut off mid-run: the server drops the connection before output completes, and both the tokens already consumed and the waiting time are lost. Some developers therefore try pointing Claude Code at alternative LLM providers, hoping for more stable connections or lower per-task costs. This guide explains when such a swap is feasible, how to configure environment variables and switch between models, how to make settings persistent with a rollback plan, and how to validate, troubleshoot, and manage API keys and costs.
Whether this works depends on three things: whether the tool can point to a different model service endpoint, whether the target service is compatible with the API protocol Claude Code uses, and whether your task types and quota strategy suit a swap. This article assumes you can already run Claude Code in your terminal and have an account and API key with an alternative model provider.
The short version: if the provider does not offer an endpoint compatible with the Anthropic Messages API, Claude Code cannot directly switch models. In that case you can route requests through a protocol conversion gateway, or keep using the official model.
1. First, Determine Whether Your Setup Qualifies
Claude Code is a command-line assistant that starts quickly, with context drawn mainly from the current directory and session. It sends requests in the Anthropic Messages API format and relies on structured results from tool calls (reading and writing files, executing commands). Swapping in another model therefore requires two prerequisites.
First, the provider must offer an Anthropic-compatible endpoint that supports streaming output and tool calls. Second, the provider’s models must handle tool calls reliably. An endpoint that only supports plain-text Q&A may connect fine but fail when editing files or running commands.
The way to check is to read the provider’s documentation on Claude Code or Anthropic-compatible endpoints. For endpoint URLs, authentication methods, and model names, defer to the provider’s official pages—this article does not list specific addresses, because these details change frequently.
| Check | Passing condition | If it fails |
|---|---|---|
| API protocol | Anthropic-compatible endpoint is provided | Use a protocol conversion gateway, or keep the official model |
| Tool calls | File edits and command execution return correctly | Restrict usage to Q&A and code explanation |
| Streaming output | Long replies stream continuously | Check network and proxy settings, or switch providers |
| Authentication | Bearer token or x-api-key is clearly specified | Adjust environment variables per the documentation |
A proxy or gateway adds an extra network hop and a potential point of failure. More importantly, the gateway will see your code and keys, so evaluate its security and data retention policies before using it.
2. Environment Variables and Multi-Model Switching
Claude Code reads the service endpoint, key, and model name from environment variables. The commonly used ones are:
- ANTHROPIC_BASE_URL: the service endpoint, pointing to the provider’s Anthropic-compatible entry point.
- ANTHROPIC_AUTH_TOKEN: the key sent as a Bearer token. Some providers require ANTHROPIC_API_KEY instead, which is sent via x-api-key—follow the provider’s documentation. Do not set both at once, to avoid authentication conflicts.
- ANTHROPIC_MODEL: the default model name.
- ANTHROPIC_DEFAULT_HAIKU_MODEL, ANTHROPIC_DEFAULT_SONNET_MODEL, ANTHROPIC_DEFAULT_OPUS_MODEL: model names mapped to each tier.
- API_TIMEOUT_MS: per-request timeout in milliseconds. Increase it for long tasks, e.g., 600000.
Variable names and defaults may change between versions, so confirm with claude --help or the official documentation before setting them.
Do not write keys directly into commands. The following example reads the key from a local file with 600 permissions:
# Create the key file and restrict permissions; the file contains only one line: the keymkdir -p ~/.config/llmprintf '%s' '<your provider API key>' > ~/.config/llm/domestic.keychmod 600 ~/.config/llm/domestic.key# Load it in the shell without putting the key into command history or code reposexport DOMESTIC_KEY="$(cat ~/.config/llm/domestic.key)"export DOMESTIC_BASE_URL="https://<provider's Anthropic-compatible endpoint>"export DOMESTIC_MODEL="<provider's model name>"
To start a one-off session with the alternative model, use the following. The variables apply only to that process and disappear when the terminal closes:
ANTHROPIC_BASE_URL="$DOMESTIC_BASE_URL" \ANTHROPIC_AUTH_TOKEN="$DOMESTIC_KEY" \ANTHROPIC_MODEL="$DOMESTIC_MODEL" \claude
If you need to switch between the official model and the alternative on the same machine, define two shell functions. Switching then only changes the launch command, with no global configuration changes:
# Official model: launch after removing the custom variablescc-official() {env -u ANTHROPIC_BASE_URL -u ANTHROPIC_AUTH_TOKEN -u ANTHROPIC_MODEL claude "$@"}# Alternative model: launch after injecting the endpoint, key, and model namecc-domestic() {ANTHROPIC_BASE_URL="$DOMESTIC_BASE_URL" \ANTHROPIC_AUTH_TOKEN="$DOMESTIC_KEY" \ANTHROPIC_MODEL="$DOMESTIC_MODEL" \claude "$@"}
If the official model depends on ANTHROPIC_API_KEY, handle it accordingly in cc-official. If the env field in ~/.claude/settings.json sets the same variables, it may override the shell values and break switching. If that happens, remove the corresponding fields from settings.json first, then retest.
After switching, confirm requests actually reach the target service. The simplest check: send a short prompt, then look for the request in the provider’s console usage logs.
3. Persistent Configuration and Rollback
There are three places to make settings persistent, each with a different scope:
- Shell config file (
~/.zshrcor~/.bashrc): applies to all new terminals. Store only function definitions and key-file loading logic here—never plaintext keys. - The
envfield in~/.claude/settings.json: applies to all Claude Code sessions for the current user. Suitable for non-sensitive settings such as the endpoint URL, model name, and timeout. .claude/settings.local.jsonin the project directory: applies only to that project. Add this file to.gitignoreto keep it out of the repository.
{"env": {"ANTHROPIC_BASE_URL": "https://<provider's Anthropic-compatible endpoint>","ANTHROPIC_MODEL": "<provider's model name>","API_TIMEOUT_MS": "600000"}}
Back up before editing; if a file does not exist, the corresponding command will error out—just skip it.
cp ~/.zshrc ~/.zshrc.bak.$(date +%Y%m%d)cp ~/.claude/settings.json ~/.claude/settings.json.bak.$(date +%Y%m%d)
After writing changes, run source ~/.zshrc to apply them. When checking variables, verify only the model name and endpoint—do not print the key itself:
echo "Model: ${DOMESTIC_MODEL:-not set}"echo "Endpoint: ${DOMESTIC_BASE_URL:-not set}"
Rollback steps:
- Restore the shell config from backup:
cp ~/.zshrc.bak.<date> ~/.zshrc, or manually delete the added lines. - Restore settings.json:
cp ~/.claude/settings.json.bak.<date> ~/.claude/settings.json. If the file did not originally exist, simply delete it. - Delete the project’s
.claude/settings.local.json, or remove its env field. - Run
source ~/.zshrcor open a new terminal, then runcc-officialorclaudeto confirm you are back on the official model. If prompted to log in again, follow the prompts. - If you no longer use the alternative service, revoke or delete the corresponding key in the provider’s console.
Rollback only restores configuration; it does not reverse charges already incurred. Calls that already happened will still be billed—verify in the console.
4. Validation, Troubleshooting, and Acceptance Criteria
Validate by comparing the two models on the same batch of tasks; do not draw conclusions from one or two experiences. The pass criteria below are suggested values—adjust them to your project.
| Test | Method | Pass criteria |
|---|---|---|
| Connectivity | Send a minimal request with curl | 3 consecutive HTTP 200 responses |
| Timeout | Run the same summarization task on a long file 10 times | At least 9 of 10 completions, with acceptable median duration |
| Long context | Provide material near the model’s context limit; ask about content at both the beginning and end | No truncation errors; both ends are quoted correctly |
| Rate limiting | Send requests with 5 concurrent connections for 2 minutes | 429 rate stays acceptable; retries succeed |
| Tool calls | Have the model create a file, modify a function, and run tests | Changes are correct and tests pass across 3 runs |
| Stream interruption | Observe long replies while streaming | No mid-stream disconnects across 10 runs |
| Cost | Read token usage for the same batch from the console | Per-task cost is below your budget cap |
You can test connectivity directly with the following command. The auth header and path must match the provider’s documentation—some providers use the Authorization header, and whether the URL includes /v1 varies by service.
code=$(curl -sS -o /tmp/resp.json -w "%{http_code}" \"$DOMESTIC_BASE_URL/v1/messages" \-H "x-api-key: $DOMESTIC_KEY" \-H "anthropic-version: 2023-06-01" \-H "content-type: application/json" \-d "{\"model\":\"$DOMESTIC_MODEL\",\"max_tokens\":32,\"messages\":[{\"role\":\"user\",\"content\":\"ping\"}]}")echo "HTTP $code"
After testing, delete the temporary response file: rm -f /tmp/resp.json.
Use a consistent cost accounting method. Tokens consumed by failed calls and retries also count toward cost—otherwise you will underestimate the true cost of the swap.
Per-task cost = total input and output token cost of all tasks ÷ number of successfully completed tasks
If the alternative model is cheaper only for some task types, break the statistics down by task type rather than hiding the difference behind an average.
Common errors and how to troubleshoot:
- 401 or 403: the key is wrong, expired, or the auth method does not match. First check whether you should use ANTHROPIC_AUTH_TOKEN or ANTHROPIC_API_KEY. When reading the key from a file, trailing newlines and spaces can also cause auth failures—check the length with
printf '%s' "$DOMESTIC_KEY" | wc -c. - 404: wrong endpoint path or model name. Common causes are an extra or missing path segment in the URL, or mismatched model name casing.
- 400 or tool call format errors: the provider’s tool call support may be incomplete. Try disabling some tools, or confirm the model supports tool calls.
- Stream interruptions or timeouts: increase API_TIMEOUT_MS, check proxies and firewalls, and split long tasks into smaller ones.
- 429 or quota exhaustion: check quotas and rate limits in the console, reduce concurrency, and set budget alerts.
- No response for a long time: first hit the endpoint directly with curl. If curl also hangs, the problem is in the network or the server side; if curl works, the problem is in the local client or configuration.
5. Key and Cost Security Checklist
After connecting to a third-party service, keys and costs need ongoing management. Go through each item below:
- Key storage: keep keys only in local files with 600 permissions, the system keychain, or your team’s secret management service. Never write them into project code, committed config files, or chat windows.
- Least privilege: create a dedicated key for Claude Code and grant only the model permissions it needs. Use different keys for different projects so they can be revoked independently.
- Version control: confirm
.claude/settings.local.jsonis in.gitignore, and rungit statusbefore committing to check that no key-related files are staged. - Log sanitization: remove keys, internal URLs, and customer data before sharing terminal output or screenshots.
- Data boundaries: read the provider’s data retention and usage policies. If the work involves proprietary code or personal information, get authorization from your organization first.
- Budget alerts: set a monthly spending cap in the provider’s console and configure usage alerts, e.g., notify at 50% and 80%.
- Regular rotation: rotate keys on a fixed schedule, e.g., every 90 days. If you suspect a leak, revoke the old key and generate a new one in the console immediately.
- Cost accounting: track per-task cost using the formula above, review it monthly, and compare against the official model’s figures for the same workloads.
Whether to switch ultimately depends on your own test data. Adopt the alternative model for daily work only if the pass rate, duration, and per-task cost all meet your pre-set criteria. Otherwise, keep using the official model, or use the alternative only for task types that pass validation. This article makes no guarantee about any service’s availability; the provider’s terms, pricing, and API details take precedence as published on its official pages.
