← Library

How to connect any model to Claude Code: Gemini, GPT and Grok

Connect any model to Claude Code with ANTHROPIC_BASE_URL and 9router: Gemini, Codex and Grok in the same harness, with real limits and terms of use.

by Ailton Carvalho · AI and automation · October 6, 2026 · 11 min read

The short answer

Connecting another model to Claude Code means keeping the harness (interface, tools, skills, hooks and MCP) and swapping only the brain that answers, by pointing the API endpoint at a router that translates the call. Claude Code speaks a single protocol, the Anthropic API, but accepts a different address through the ANTHROPIC_BASE_URL variable. An open source router such as 9router listens at that address, converts the request for Gemini, GPT/Codex, Grok and other providers, and returns the response in the format Claude Code expects. The harness stays, only the model changes. This is for people who already live in the terminal and want a cheaper model for reading code, or a second opinion from another vendor, without learning a new tool. It is not a path Anthropic supports, and part of the CLI's features stop applying when the model on the other side is not Claude.

1. The harness and the model are different things

People who use Claude Code every day tend to call the whole thing "Claude". In practice there are two layers. The harness is the program in the terminal: it reads and edits files, runs commands, loads skills, fires hooks, talks to MCP servers and keeps the session history. The model is what decides what to do with all of that, turn by turn, on the other side of the network.

The harness does not know who is answering. It builds a request in the Anthropic Messages format, sends it to an address and waits for streaming events in return. The official docs state that, with ANTHROPIC_BASE_URL pointed at a gateway, Claude Code "treats the gateway as the Claude API and can't tell which upstream you forward to". That blindness is what makes the swap possible.

That is why the effort you put into configuration still pays off. Your project rules, the MCP servers you already connected (if you have not connected any yet, the guide to MCP in Claude Code and Cursor covers the basics) and your validation hooks stay the same. What changes is the quality, the cost and the style of whatever does the thinking.

A note about the "any" in the title: here it means any provider the router supports. The 9router README lists more than 40 providers by API key, including OpenAI, Anthropic, Gemini and xAI. Outside that list there is no translation, and there is no magic.

2. How the router sits in the middle

The flow has three pieces:

  1. Claude Code sends the request to the address set in ANTHROPIC_BASE_URL, at the /v1/messages path, as the compatibility guide describes.
  2. The router receives it, reads the requested model ID, picks the provider and converts the body to that provider's format (Gemini, OpenAI, xAI).
  3. The response comes back converted into Anthropic-style events, and Claude Code continues the turn as if nothing had changed.

9router does this locally, on your machine or on a VPS, with a web dashboard for adding providers and generating the key Claude Code will use. According to the README, the project is MIT licensed, charges nothing and you pay each provider directly. The cost figure the dashboard shows is a comparison estimate, not an invoice.

There is an alternative that does not involve a router: Anthropic itself offers Claude through Amazon Bedrock, Google Cloud Agent Platform and Microsoft Foundry. Those are the official backends. But all of them serve Claude models. If the goal is to run Gemini or Grok inside the harness, the router is the only piece that solves it, and you take on maintaining it.

3. Install 9router

The README offers two paths. With npm, on Node.js 20 or newer:

npm install -g 9router
9router

With Docker, with the data persisted in a folder in your home directory:

docker run -d --name 9router -p 20128:20128 \
  -v "$HOME/.9router:/app/data" \
  -e DATA_DIR=/app/data decolua/9router:latest

Either way, the dashboard opens at http://localhost:20128/dashboard. The default port is 20128. If you run it on a VPS, do not expose that port to the internet: keep the router listening on localhost only and reach the dashboard through an SSH tunnel. Whoever holds the router key spends the credit of every provider registered in it.

Before moving on, check two things in the dashboard: that it opened without errors, and that there is an option to generate an access key for 9router itself. That key, not the Gemini or xAI one, is what goes into Claude Code.

4. Add the providers

In the dashboard, each provider goes in with its own credential. The safe path for all of them is an API key with usage-based billing.

  • Gemini: generate a Gemini API key in the Google console and paste it into the Gemini provider in 9router. The official pricing table has a free tier and a paid tier; for client work, use the paid one.
  • Grok: goes in with an xAI API key, billed per token. Without an xAI key there is no Grok in the router.
  • Codex and GPT: the Codex docs describe two sign-in options, "Sign in with ChatGPT for subscription access" and an API key, which OpenAI bills "at standard API rates". Use the API key.

Why not use a consumer subscription

The 9router README offers OAuth sign-in for subscriptions (ChatGPT/Codex, Claude Code and others). Technically it works. Contractually it is a different story. The Google Antigravity Additional Terms say it plainly: "Using third party software, tools, or services to access the Service (e.g. using OpenClaw with Antigravity OAuth) is a breach of this Agreement", and they provide for suspension or termination of Antigravity and Gemini CLI accounts. On the OpenAI side, the Codex authentication docs list where ChatGPT sign-in is supported: the desktop app, the Codex CLI and the IDE extension. A third-party router is not on the list.

The practical takeaway: a consumer subscription plugged into a router may breach the provider's terms and cost you the account. A pay-as-you-go API key is the path without doubt, and the bill stays predictable because every token has a published price.

5. Point Claude Code at it with an isolated launcher

Do not touch your main Claude Code. Create a launcher that starts a separate instance with its own configuration directory. The official docs describe CLAUDE_CONFIG_DIR for exactly this: it replaces the default ~/.claude directory and is "Useful for running multiple accounts side by side". Login, settings, history and plugins stay separate, and neither contaminates the other.

Save it as ~/bin/claude-roteado and make it executable:

#!/usr/bin/env bash
export CLAUDE_CONFIG_DIR="$HOME/.claude-roteado"
export ANTHROPIC_BASE_URL="http://localhost:20128"
export ANTHROPIC_AUTH_TOKEN="$(cat "$HOME/.config/9router.key")"
exec claude "$@"

Three details in this file:

  • ANTHROPIC_BASE_URL points at the root of the port. Claude Code appends /v1/messages on its own, as the compatibility guide shows. The 9router README mentions the /v1 endpoint in a config.json example; if your request ends up on a duplicated path, adjust it here.
  • ANTHROPIC_AUTH_TOKEN carries the key generated in the 9router dashboard, sent in the Authorization header with a Bearer prefix. The key lives in a file readable only by your user, never written into the script or committed to version control.
  • Your subscription is out of the loop. The official docs explain that, with a gateway credential active, requests do not use the claude.ai login and the plan limits do not apply: billing goes to whoever owns the credential the gateway forwards. In your case, each registered provider.

If you keep project rules for more than one agent, the article on Rulesync with a single rules source for Claude Code, Codex and Cursor shows how to avoid duplicating instructions. The problem here is a different one: the same CLAUDE.md is now read by different models, and not all of them follow long rules with the same discipline.

6. Choose the model by variable or by alias

The model ID is what the router uses to decide on the provider. The README shows the prefixed format, such as cx/ for Codex. Copy the exact ID from the model list in the dashboard; do not make up names.

To run a whole session on a single model, pass the ID at startup. The model configuration docs list the order: /model inside the session, --model at startup, ANTHROPIC_MODEL and the model field in settings.

claude-roteado --model "<id-copiado-do-painel>"

The most comfortable approach is to remap the aliases. The variables ANTHROPIC_DEFAULT_OPUS_MODEL, ANTHROPIC_DEFAULT_SONNET_MODEL and ANTHROPIC_DEFAULT_HAIKU_MODEL set where opus, sonnet and haiku point. Add this to the launcher:

export ANTHROPIC_DEFAULT_OPUS_MODEL="<id-claude-no-painel>"
export ANTHROPIC_DEFAULT_SONNET_MODEL="<id-codex-no-painel>"
export ANTHROPIC_DEFAULT_HAIKU_MODEL="<id-gemini-flash-no-painel>"

With that, /model sonnet now calls Codex and /model haiku calls Gemini Flash. According to the docs, the haiku alias is also the model for background tasks, so session titles and internal summaries go to the cheapest model. For subagents, CLAUDE_CODE_SUBAGENT_MODEL sets the default: the main session thinks on one model and the search subagents run on another.

One detail about the picker: the gateway's automatic model discovery only keeps IDs that contain "claude" or "anthropic". A Gemini or Grok ID will not show up in /model on its own. To put one of them in the menu, use ANTHROPIC_CUSTOM_MODEL_OPTION with the ID and ANTHROPIC_CUSTOM_MODEL_OPTION_NAME with a readable name.

7. When each model pays off

The split that makes sense is by type of work, not by brand loyalty:

  • Gemini Flash for cheap reading. Scanning a repository, summarizing a module, finding where a function is called, explaining a long log. It is work with lots of input tokens and few decisions, and Flash has the lowest input price in the table below.
  • Codex for scripts and a second opinion. A migration script, a missing test, or reviewing a diff Claude wrote. Another vendor makes different mistakes, and that catches bugs the same model would let through.
  • Grok as a general reasoning alternative, when you want to compare answers on an open-ended problem.
  • Claude for writing and heavy refactoring. Changes across many files, refactoring with tests, long tool-heavy work. The harness was designed around it, and it is the only case where effort, adaptive thinking and caching work as the docs describe.

Price per 1 million tokens, according to the official pages read on 2026-10-07:

Model Input (US$) Output (US$) Source
Gemini 3.8 Flash (paid tier, until 2026-12-31) 0.75 3.75 Gemini API pricing
Gemini 3.1 Pro Preview (prompt up to 200k tokens) 2.00 12.00 Gemini API pricing
grok-4.7 (prompt below 200k tokens) 2.00 6.00 xAI Docs, Models
grok-4.7 (prompt of 200k tokens or more) 4.00 12.00 xAI Docs, Models
Codex with an API key standard OpenAI API rate standard OpenAI API rate OpenAI Codex Docs

Google's own page already announces a Flash price change starting January 1, 2027. Check each vendor's pricing page before you lock in a budget; tables in articles age quickly.

8. The real limits

The first limit is support. The official docs are blunt: Anthropic "doesn't endorse, maintain, or audit third-party gateway products, and doesn't support routing Claude Code to non-Claude models through any gateway". If it breaks, the problem is yours and the router project's.

Then there is what changes in behavior, according to the compatibility guide and the environment variables page:

  • Effort and thinking do not apply to another vendor. Effort levels are listed only for Claude models. For an ID it does not recognize, Claude Code sends adaptive reasoning and effort anyway, and the upstream may reject them. When effort is rejected, the CLI retries the request without it. In practice, /effort becomes decoration.
  • Prompt caching depends on the router. If cache_control does not arrive intact, there is no error: every turn is billed as uncached input. Watch usage in the provider's dashboard during the first few days.
  • Assumed context window. For an unknown ID, Claude Code assumes 200K tokens. If the model has a different window, set it with CLAUDE_CODE_MAX_CONTEXT_TOKENS, or compaction will happen at the wrong time.
  • Features turned off. With ANTHROPIC_BASE_URL outside Anthropic, MCP tool search is off by default and Remote Control is disabled since v2.1.196. With many MCP servers, all tools load at once and the context fills up faster.
  • Features that depend on the official model. The auto permission mode classifier, fast mode (whose check goes straight to api.anthropic.com) and long chains of tool use were designed for Claude. With another model they may fail or behave differently. Use manual permissions on the routed instance.
  • Instruction following is uneven. Hooks and skills still run, but the decision to call the right skill, respect CLAUDE.md and stop at the right moment belongs to the model. Start with small, reviewable tasks.

Finally, the terms of use, already covered in section 4. A router with a pay-as-you-go API key stays within each provider's contract. A router with a consumer subscription login may not.

A ready-made prompt for your agent

Paste the text below into the Claude Code you already use. It installs 9router, creates the isolated launcher from this article without touching your main installation and stops at the steps that are yours, such as adding each provider's key in the dashboard. Replace the fields between < > or answer when it asks.

You will connect other models to Claude Code through a local router, following this script in order.
My data: install method <MODE> (npm or docker); providers <PROVIDERS> (gemini, xai, openai);
IDs copied from the dashboard model list: <OPUS_ID>, <SONNET_ID>, <HAIKU_ID>.

Rules:
- Never print, read out, paste into the chat or write into a script the 9router key or any
  provider key. The router key lives only in ~/.config/9router.key, readable only by me.
- Use pay-as-you-go API keys. Do not connect consumer subscription OAuth logins to the router.
- Do not touch ~/.claude or the main claude command. Show each command before running it.

1. Prerequisites: claude --version. For npm, node -v must be 20 or newer; for docker, check
   docker --version.
2. npm install: npm install -g 9router and then 9router.
   docker install: docker run -d --name 9router -p 20128:20128
   -v "$HOME/.9router:/app/data" -e DATA_DIR=/app/data decolua/9router:latest
3. Network: on a VPS, do not expose port 20128 to the internet; keep it on localhost and
   explain how I open the dashboard through an SSH tunnel.
4. Dashboard: ask me to open http://localhost:20128/dashboard, add each provider with its API
   key and generate the 9router's own access key.
5. Router key: create an empty ~/.config/9router.key with permission 600 and ask me to paste
   the key into it with an editor. Only check that the file is not empty (test -s), without
   reading the content.
6. Launcher: create ~/bin/claude-roteado, executable, with these lines:
   #!/usr/bin/env bash
   export CLAUDE_CONFIG_DIR="$HOME/.claude-roteado"
   export ANTHROPIC_BASE_URL="http://localhost:20128"
   export ANTHROPIC_AUTH_TOKEN="$(cat "$HOME/.config/9router.key")"
   export ANTHROPIC_DEFAULT_OPUS_MODEL="<OPUS_ID>"
   export ANTHROPIC_DEFAULT_SONNET_MODEL="<SONNET_ID>"
   export ANTHROPIC_DEFAULT_HAIKU_MODEL="<HAIKU_ID>"
   exec claude "$@"
   If requests land on a duplicated /v1 path, adjust ANTHROPIC_BASE_URL.
7. Tweaks: if a model has a context window other than 200K, add CLAUDE_CODE_MAX_CONTEXT_TOKENS.
   To make an ID without "claude" in its name show up in /model, use
   ANTHROPIC_CUSTOM_MODEL_OPTION and ANTHROPIC_CUSTOM_MODEL_OPTION_NAME.
8. Remind me: on the routed instance, use manual permissions; effort, fast mode and Remote
   Control do not apply there; watch usage in each provider's dashboard for the first days.

Final validation: ask me to run claude-roteado --model "<SONNET_ID>" and send a short question.
Confirm with me that the answer came back, that the request shows up in the 9router dashboard
and that /model sonnet and /model haiku point to the IDs I chose. Then run ls ~/.claude-roteado
to prove the configuration is separate, and claude --version on the main command.
Only say you are done when all three points are confirmed.

Frequently asked questions

Can I use Claude Code with Gemini?

Yes, through a router that translates the Anthropic Messages format to the Gemini API, such as 9router. Claude Code points at the router through ANTHROPIC_BASE_URL, and the router calls Gemini with your API key. Anthropic does not support this setup.

What is ANTHROPIC_BASE_URL?

It is the environment variable that changes the API endpoint Claude Code uses. The official docs describe it for routing requests through a proxy or gateway. Without a gateway credential alongside it, a saved claude.ai login remains the active credential.

Do I need to pay for the Gemini, OpenAI and xAI APIs?

Yes, if you follow the safe path. 9router is free software and charges nothing; you pay each provider for what you use. Gemini has a free tier on its pricing page, but for client code the paid tier is the recommended one.

Can I use my ChatGPT or Gemini subscription in the router?

The router accepts it, but the provider's contract may not. The Google Antigravity terms call access through third-party software with their OAuth a breach, with a risk of suspension. OpenAI documents ChatGPT sign-in for its own Codex clients. Use an API key.

Do effort and thinking still work with another model?

Not the way they do with Claude. The docs list effort levels only for Claude models, and another vendor's upstream may reject those fields. Claude Code retries without effort when it gets the rejection.

Will this break my main Claude Code installation?

No, if you use a launcher with its own CLAUDE_CONFIG_DIR. Login, settings, history and plugins live in another directory, and the main instance keeps talking directly to Anthropic.

Conclusion

Claude Code is worth it for the harness, and the harness does not know who is answering. With ANTHROPIC_BASE_URL, a router such as 9router and an isolated launcher, Gemini, Codex and Grok join the same workflow of skills, hooks and MCP. The price is taking on maintenance of the router, losing effort, certainty about caching and a few features, and staying within the terms by using API keys. If what you need is an agent reading your ERP, your store or your bank, that is custom integration work (MCP, webhooks, queues) with AI agents and terminal automation. Describe the system and what you want to automate at oailton.dev/contato.

Sources

  1. 19router installs with npm install -g 9router or through the Docker image decolua/9router, listens on port 20128 with a dashboard at /dashboard, requires Node.js 20+, is MIT licensed, talks to more than 40 providers by API key (OpenAI, Anthropic, Gemini, xAI and others) and uses a provider prefix in the model ID, such as cx/ for Codex (read on 2026-10-07) GitHub decolua/9router (README)
  2. 2Anthropic 'doesn't endorse, maintain, or audit third-party gateway products, and doesn't support routing Claude Code to non-Claude models through any gateway'; with a gateway credential active, the claude.ai subscription is not used and traffic is billed to whoever owns the credential (read on 2026-10-07) Claude Code Docs: Other LLM gateways
  3. 3The Anthropic Messages format is selected by ANTHROPIC_BASE_URL and uses /v1/messages; for an unrecognized model ID, Claude Code sends adaptive reasoning, effort and context management, which the upstream may reject; it assumes a 200K window; broken prompt caching raises no error and bills uncached input; model discovery only keeps IDs containing 'claude' or 'anthropic'; the official cloud providers are Amazon Bedrock, Google Cloud Agent Platform and Microsoft Foundry (read on 2026-10-07) Claude Code Docs: Gateway compatibility guide
  4. 4ANTHROPIC_BASE_URL swaps the endpoint; with a non-Anthropic host, MCP tool search is off by default and Remote Control is disabled since v2.1.196; ANTHROPIC_AUTH_TOKEN goes in the Authorization header with a Bearer prefix; CLAUDE_CONFIG_DIR changes the configuration directory (default ~/.claude) and is 'Useful for running multiple accounts side by side' (read on 2026-10-07) Claude Code Docs: Environment variables
  5. 5The model is chosen with /model, --model, ANTHROPIC_MODEL or the model field; ANTHROPIC_DEFAULT_OPUS_MODEL, ANTHROPIC_DEFAULT_SONNET_MODEL and ANTHROPIC_DEFAULT_HAIKU_MODEL set where the aliases point; CLAUDE_CODE_SUBAGENT_MODEL sets the subagent model; ANTHROPIC_CUSTOM_MODEL_OPTION adds a custom ID to the picker; effort levels are listed only for Claude models; CLAUDE_CODE_MAX_CONTEXT_TOKENS corrects the window behind a gateway (read on 2026-10-07) Claude Code Docs: Model configuration
  6. 6Gemini 3.8 Flash on the paid tier costs US$0.75 per 1M input tokens and US$3.75 output until 2026-12-31; Gemini 3.1 Pro Preview costs US$2.00 input and US$12.00 output for prompts up to 200k tokens; page updated on 2026-10-07 (read on 2026-10-07) Google AI for Developers: Gemini API pricing
  7. 7grok-4.7 costs US$2.00 per 1M input tokens and US$6.00 output below 200k prompt tokens, and US$4.00 and US$12.00 above that (read on 2026-10-07) xAI Docs: Models and pricing
  8. 8'Using third party software, tools, or services to access the Service (e.g. using OpenClaw with Antigravity OAuth) is a breach of this Agreement', which may lead to suspension or termination of Antigravity and Gemini CLI accounts (read on 2026-10-07) Google Antigravity Additional Terms of Service
  9. 9Codex has two sign-in options: 'Sign in with ChatGPT for subscription access' and an API key for usage-based billing; ChatGPT sign-in is documented for the desktop app, the Codex CLI and the IDE extension; 'OpenAI bills API key usage through your OpenAI Platform account at standard API rates' (read on 2026-10-07) OpenAI Codex Docs: Authentication

Ailton Carvalho

I build custom web systems, internal tools, integrations and stores that sell on mobile. You get working code and someone accountable after launch.

Talk on WhatsApp

Next step: Custom web systems

Related