Gemini CLI is one of the better terminal agents available: it reads your repo, runs shell commands, talks to MCP servers, and ships under a permissive license. The one thing it does not do out of the box is talk to a model that is not Gemini.
That becomes a problem the moment your team has standardised on an OpenAI-compatible gateway. Maybe you already have a single key that serves DeepSeek-V4 models, bought with a card or PayPal and usable from any OpenAI-compatible client. Adding a second provider, a second SDK, and a second set of quota rules just to run one CLI is friction nobody asked for.
This guide walks through what actually happens when you try, why the obvious one-line change does not work, and a working translation shim you can run locally in about sixty lines.
Why This Is Not Just a Base-URL Swap
Gemini CLI speaks the Gemini API surface, not the OpenAI one. Those are different protocols with different request bodies, different streaming envelopes, and different tool-call representations. Setting a base URL gets you a 404 or a schema error, not a working agent.
Concretely, Gemini CLI sends a POST to a path shaped like /v1beta/models/<model>:generateContent, with a body containing contents (a list of role/parts objects), an optional systemInstruction, and optional tools and safetySettings blocks. An OpenAI-compatible endpoint expects messages with a flat content string, tools in a completely different shape, and a streaming format that is not Gemini's alt=sse envelope.
So "using Gemini CLI with a custom OpenAI-compatible backend" means one of two things in practice. Either you find a build that exposes a provider switch and point it at something Gemini-shaped, or you put a small translation process between the CLI and your real backend.
First, Check What Your Build Actually Supports
Provider and base-URL configuration in Gemini CLI has moved between releases, so do not trust a blog post — including this one — over your own installation. Spend two minutes confirming before you build anything.
Run
gemini --versionand note the exact version you are on.Run
gemini --helpand look for any custom-endpoint, provider, or base-URL flag.Open
~/.gemini/settings.jsonand the project-level.gemini/settings.json, and read the keys your version actually writes.Check the configuration docs for that specific version, not the latest docs.
If your build has a documented switch for a custom Gemini-compatible endpoint, you still need something Gemini-shaped on the far end — which is where the shim below comes in regardless. If it has a documented OpenAI-compatible provider, take the easy path and stop reading here.
Step 0: Prove the Backend Works Before You Touch the CLI
Debugging two layers at once is how afternoons disappear. Confirm the OpenAI-compatible side in isolation first with the official OpenAI SDK pointed at AiCredits.
# smoke_test.py — prove the backend works before you touch the CLI
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
)
response = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[
{"role": "system", "content": "Answer in exactly one word."},
{"role": "user", "content": "Reply with: ready"},
],
)
print(response.choices[0].message.content)
Install the SDK with pip install openai, export AICREDITS_API_KEY, and run it. If this prints a word, every problem you hit afterwards is in the translation layer and nowhere else. If it fails here, stop — the CLI is not the issue.
Step 1: A Minimal Gemini-to-OpenAI Shim
This is a FastAPI service that accepts Gemini-shaped generateContent and streamGenerateContent calls and forwards them to an OpenAI-compatible endpoint. It handles the parts that matter for text conversations: system instructions, role mapping, and streaming.
# gemini_shim.py
# Run: uvicorn gemini_shim:app --host 127.0.0.1 --port 8085
import json
import os
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
)
UPSTREAM_MODEL = os.environ.get("UPSTREAM_MODEL", "deepseek-v4-flash")
app = FastAPI()
def build_messages(body: dict) -> list[dict]:
"""Flatten a Gemini request body into OpenAI chat messages."""
messages = []
system = body.get("systemInstruction")
if system:
text = "".join(part.get("text", "") for part in system.get("parts", []))
if text:
messages.append({"role": "system", "content": text})
for content in body.get("contents", []):
role = "assistant" if content.get("role") == "model" else "user"
text = "".join(part.get("text", "") for part in content.get("parts", []))
if text:
messages.append({"role": role, "content": text})
if not messages:
messages = [{"role": "user", "content": "Hello"}]
return messages
@app.post("/v1beta/models/{model}:generateContent")
async def generate_content(model: str, request: Request):
body = await request.json()
completion = client.chat.completions.create(
model=UPSTREAM_MODEL,
messages=build_messages(body),
)
text = completion.choices[0].message.content or ""
return {
"candidates": [
{
"content": {"role": "model", "parts": [{"text": text}]},
"finishReason": "STOP",
}
]
}
@app.post("/v1beta/models/{model}:streamGenerateContent")
async def stream_generate_content(model: str, request: Request):
body = await request.json()
msgs = build_messages(body)
def events():
stream = client.chat.completions.create(
model=UPSTREAM_MODEL,
messages=msgs,
stream=True,
)
for chunk in stream:
delta = chunk.choices[0].delta.content
if not delta:
continue
payload = {
"candidates": [
{"content": {"role": "model", "parts": [{"text": delta}]}}
]
}
yield f"data: {json.dumps(payload)}\n\n"
return StreamingResponse(events(), media_type="text/event-stream")
Set UPSTREAM_MODEL=deepseek-v4-pro in the environment if you want the stronger model behind the agent without editing code. The default deepseek-v4-flash is the right choice for the interactive loop — you are paying for every turn, and the agent takes many.
Step 2: Point the CLI at the Shim
# Terminal 1 — the shim
export AICREDITS_API_KEY="your-key-here"
uvicorn gemini_shim:app --host 127.0.0.1 --port 8085
# Terminal 2 — the CLI
export GEMINI_API_KEY="local-shim"
export GOOGLE_GEMINI_BASE_URL="http://127.0.0.1:8085"
gemini
The environment variable name above is the one older builds read; newer ones may expect a provider or model block in ~/.gemini/settings.json instead. This is exactly why Step 0 exists — check gemini --help against your installed version and use whichever knob it documents. The shim itself does not care what the variable is called, only that requests arrive at 127.0.0.1:8085 with a Gemini-shaped body.
Bind the shim to 127.0.0.1, never 0.0.0.0. It holds your API key and has no authentication of its own.
What Breaks First
| Gemini surface | What breaks | Practical fix |
|---|---|---|
| functionCall / functionResponse parts | The shim forwards text only, so the agent cannot run tools | Map Gemini tools to OpenAI tools, then map tool_calls back into functionCall parts |
| usageMetadata | Without it the CLI cannot track context or auto-compact cleanly | Pass the upstream usage field through as promptTokenCount and candidatesTokenCount |
| systemInstruction | Easy to drop silently, and the agent loses its whole persona | Handle it explicitly — the shim above does this before the message loop |
| :streamGenerateContent | A non-streaming-only shim returns 404 and the CLI appears to hang | Add the SSE route shown above |
| thinkingConfig / safetySettings | Gemini-specific fields with no OpenAI equivalent | Ignore them in the shim; they are advisory |
The honest summary: text conversations work immediately, tool calling is a real project. If you need the agent to actually edit files and run commands through the shim, budget a focused afternoon for the tools mapping and test it against a scratch repository before trusting it on anything you care about.
If You Would Rather Not Maintain a Shim
A shim is another process to run, another thing to update, and another place for the streaming envelope to drift. If what you actually want is a terminal agent backed by an OpenAI-compatible model rather than Gemini CLI specifically, several agents accept a base URL and a key as first-class configuration — no translation process, no maintenance.
That is the pragmatic call for most teams: keep Gemini CLI for the workflows where Gemini's own models are the point, and run a natively OpenAI-compatible agent against AiCredits for everything else. One key covers any OpenAI-compatible client you point at it, and because credits are sold internationally by card or PayPal, there is no Chinese phone number or bank account in the loop. Current rates live at aicreditsapi.com/pricing.
Picking flash or pro Behind the Agent
Use deepseek-v4-flash as the default. Agent loops fire many requests per task, and most of those turns are read-a-file, summarise, decide-next-step work that does not need the bigger model.
Switch to deepseek-v4-pro when the task is a multi-file refactor, a subtle concurrency bug, or anything where a wrong edit costs more than a slower answer.
Repeated context is your friend. Identical prefixes get served from cache, and cache hits cost less than fresh input — so keep your system prompt and repo preamble stable instead of regenerating them each run.
Off-peak requests cost less than peak. Long batch jobs and overnight test-fixing runs are the natural fit for that.
Never hardcode a model string in two places. Pass it through an environment variable like the shim does, so switching does not mean editing code.
FAQ
Not in a way you can rely on across releases. Some builds expose provider or base-URL configuration, others do not, and the keys change between versions. Run gemini --help against your installed version and read that version's configuration docs. If there is no documented OpenAI-compatible provider, the shim is the honest answer.
Only if you extend it. Text conversation works out of the box because the translation is trivial. Function calling requires mapping Gemini's tools block to OpenAI's tools array and converting tool_calls back into functionCall parts, including the round trip where the CLI sends functionResponse results back. Start with plain chat, then add tools once the basics are stable.
deepseek-v4-flash for the interactive loop, deepseek-v4-pro for the hard problems. Flash is the default because agent workflows multiply request count; pro costs more than flash but is the better trade on tasks where a wrong edit is expensive.
No. AiCredits sells DeepSeek API credits internationally with payment by card or PayPal, and issues a single key that works from any OpenAI-compatible client. See aicreditsapi.com/pricing for current rates.
It is as safe as you make it. Bind to 127.0.0.1 rather than 0.0.0.0, keep the upstream key in an environment variable rather than in source, and never expose the port through a tunnel while it is unauthenticated.
The shim is a bridge, not a destination. If you find yourself maintaining it past the first afternoon, that is the signal to switch to an agent that speaks your backend's protocol natively.