OpenAI API alternatives let you keep the OpenAI SDK and your request code: you change the base URL and the API key, then pick a model id the new endpoint serves. That is the short version. What the top results skip is what breaks after the two lines: a table of seven endpoints built from each vendor’s own documentation (read on 28 November 2026), a 7-check probe script you can point at any of them, a price table from OpenAI’s own page that shows the lowest-effort first move may be a smaller OpenAI model, and a payback calculator. One AI API Key publishes this post and is one of the endpoints in the table, so read our row the way you would read any vendor’s.
What are the two lines, and what is the third?
Every OpenAI-compatible endpoint accepts the same request shape at /chat/completions, so the SDK only needs to know where to send it and what key to attach. In the Python SDK those are the base_url argument and the api_key argument; the openai-python README also documents an OPENAI_BASE_URL environment variable, and the openai-node README shows the same setting as the baseURL option. Both appear in the examples below.
import os
from openai import OpenAI
# Before: client = OpenAI()
client = OpenAI(
base_url="https://api.oneaiapikey.com/v1", # line 1: where the request goes
api_key=os.environ["ONEAIAPIKEY_API_KEY"], # line 2: whose key pays for it
)
reply = client.chat.completions.create(
model="deepseek-deepseek-v4.1-flash:free", # the third string: a model id the new endpoint serves
max_tokens=200,
messages=[{"role": "user", "content": "Explain idempotency in one sentence."}],
)
print(reply.choices[0].message.content)
print(reply.usage)import OpenAI from "openai";
// Before: const client = new OpenAI();
const client = new OpenAI({
baseURL: "https://api.oneaiapikey.com/v1", // line 1
apiKey: process.env.ONEAIAPIKEY_API_KEY, // line 2
});
const reply = await client.chat.completions.create({
model: "deepseek-deepseek-v4.1-flash:free",
max_tokens: 200,
messages: [{ role: "user", content: "Explain idempotency in one sentence." }],
});
console.log(reply.choices[0].message.content);
console.log(reply.usage);The third change is the model id. OpenAI’s ids belong to OpenAI, so another endpoint needs one of its own, and the safe habit is to copy the id from that endpoint’s model list. On One AI API Key the list is the models table or GET /v1/models with your key, and the ids that end in :free are the ones you can call without adding credit. The deepseek-deepseek-v4.1-flash:free id above is one of 48 on the free lane today.
If your code creates the client with no arguments, you may not need an edit at all. Setting two environment variables is enough, and a curl against the model list tells you in one second whether the base URL is right:
# No code change at all, if your code builds the client with OpenAI() and no arguments
export OPENAI_BASE_URL="https://api.oneaiapikey.com/v1"
export OPENAI_API_KEY="paste-the-new-key-here"
# Check the endpoint before you run the app (a 200 and a JSON list means the base URL is right)
curl -s https://api.oneaiapikey.com/v1/models -H "Authorization: Bearer $OPENAI_API_KEY" | head -c 300Our docs migration page lists the same three changes and the features that differ, and the quickstart shows a first call from scratch.
What the two lines change
Which OpenAI API alternatives accept the OpenAI SDK?
Seven endpoints are in the table, plus OpenAI as the reference row. Each base URL and each gap comes from the vendor’s own page, linked in the last column. A gap that a vendor does not list is blank, because that is what the page said, and an absence on a docs page is not proof that something works.
| Endpoint | Base URL for the OpenAI SDK | Model ids | Gaps the vendor documents | Source |
|---|---|---|---|---|
| OpenAI (reference) | https://api.openai.com/v1 |
OpenAI’s own ids | Chat Completions stays supported; Responses is recommended for new projects; Assistants sunset 26 August 2026 | API reference, migration |
| Groq | https://api.groq.com/openai/v1 |
Groq’s own ids | logprobs, logit_bias, top_logprobs and messages[].name return 400; n must be 1; temperature 0 becomes 1e-8; no text completions |
Groq compatibility page |
| Google Gemini API | https://generativelanguage.googleapis.com/v1beta/openai/ |
Gemini ids | The page says library support is still in beta | Gemini compatibility page |
| DeepSeek | https://api.deepseek.com (no /v1) |
deepseek-flash in the first-call example |
Legacy ids still accepted but now served by another model | DeepSeek first call |
| Together AI | https://api.together.ai/v1 |
provider/model_name form |
Assistants, threads and runs not supported; OpenAI-shape fine-tuning and batches not supported; files partial; serverless embeddings none | Together compatibility page |
| OpenRouter | https://openrouter.ai/api/v1 |
provider/model form, such as openai/gpt-4o in its guide |
Optional attribution headers; its own routing arguments go in extra_body |
OpenRouter SDK guide |
| Ollama (your machine) | http://localhost:11434/v1/ |
Local model names | Key required but ignored; stateful Responses (previous_response_id, conversation) not supported |
Ollama compatibility page |
| One AI API Key | https://api.oneaiapikey.com/v1 | Flat ids, no vendor prefix | Assistants, Threads, Files, Batch, fine-tuning and image variations answer 501; Responses is stateless | Migration docs |
Three details in the table are the kind that cost an afternoon. DeepSeek’s documented base URL has no /v1, so a base URL copied from the pattern of the others is not the one its docs show. Gemini’s ends with a slash and a path, /v1beta/openai/, that is easy to truncate. And Together’s ids carry a provider prefix, so an id that works on one endpoint fails on another with a model-not-found error even though the request is perfectly valid.
Self-hosting is the eighth route and sits outside the table because it has no single base URL. Servers such as vLLM expose an OpenAI-compatible HTTP server, so the same two lines point the SDK at a machine you run. That removes a vendor but adds a GPU bill and an operations job; the LiteLLM alternatives guide puts numbers on the operations side.
What breaks after the two lines?
Most of what breaks is not the request body. It is everything around it. Six places account for nearly every migration problem we see described in provider docs.
1. Model ids. Covered above, and the cause of the most 404s. A subtler version is an alias that quietly points at a different model. DeepSeek’s page says its legacy ids are still accepted but their requests are now served by DeepSeek-V4.1-Flash-1017 and billed at the Flash price. That is documented and fair, but your code never saw an error, so the only way to notice is to print the model field of the reply, which the probe script below does.
2. Stored state. OpenAI’s Responses guide describes store: true for keeping state from turn to turn, and notes that responses are stored by default. Several alternatives are stateless: Ollama lists previous_response_id and conversation as unsupported, and One AI API Key does not store responses either, so you send the full history every time and set store: false. If your app fetches an old response by id, that call has no counterpart on a stateless endpoint. Our Responses API docs spell out what is and is not available.
3. Whole API surfaces. OpenAI’s Assistants migration page says the Assistants API was sunset on 26 August 2026, so that surface is gone everywhere, including at OpenAI. Files, Batch, fine-tuning and image variations are different: they still exist at OpenAI but are partly or wholly absent from the alternatives (a 501 on One AI API Key, “not supported” or “partial” in Together’s matrix). A search through your code for client.files, client.batches and client.fine_tuning takes a minute and tells you whether this applies.
4. Headers. OpenAI’s reference lists response headers such as openai-organization, openai-processing-ms, openai-version and x-request-id, plus a family of x-ratelimit-* headers. Code that logs openai-processing-ms will log nothing on another endpoint. On One AI API Key the reply carries X-Request-Id, and the x-ratelimit-* headers appear only on keys that have a requests-per-minute limit, with X-Daily-Remaining on models that have a daily cap; the headers reference has the full list. Measure latency in your own client instead of trusting a vendor header.
5. Streaming usage. On the OpenAI format a streamed reply includes token counts only when you ask: stream_options: {"include_usage": true} adds a final chunk with an empty choices list. Code that reads chunk.choices[0] on that last chunk throws an IndexError. The streaming docs show the guard, and the guide to streaming versus non-streaming responses explains why long outputs should stream at all.
6. Structured output and tools on particular models. response_format works where the provider supports it and is dropped without an error when a Claude model is called through chat completions on One AI API Key, as the structured output docs warn. That matters if your reason for leaving OpenAI is a Claude model. A forced tool call is the portable way to get JSON; the tool calling docs cover the loop, and the post on OpenAI-compatible versus Anthropic-compatible formats shows where the two shapes differ.
How do you test an alternative before it sees real traffic?
Run the same seven checks against every candidate. The script below uses only the official openai Python package. It lists models, sends a plain request, a streamed request with the usage chunk, a forced tool call, a JSON-mode request, a request with max_tokens so small that the answer must be cut, and a request for a model that does not exist, then prints one PASS or FAIL line each. A full run is about eight tiny requests.
import json
import os
import sys
from openai import OpenAI, APIStatusError
BASE = os.environ["PROBE_BASE_URL"]
KEY = os.environ["PROBE_API_KEY"]
MODEL = sys.argv[1]
client = OpenAI(base_url=BASE, api_key=KEY, max_retries=0, timeout=60)
ASK = [{"role": "user", "content": "Reply with the single word OK."}]
TOOLS = [{"type": "function", "function": {
"name": "get_weather", "description": "Current weather for a city",
"parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
}}]
rows = []
def check(name, fn):
try:
rows.append((name, "PASS", fn() or ""))
except Exception as e:
rows.append((name, "FAIL", (type(e).__name__ + ": " + str(e))[:100]))
def models_list():
ids = [m.id for m in client.models.list()]
assert MODEL in ids, "model id not in the list"
return str(len(ids)) + " ids listed"
def plain():
r = client.chat.completions.create(model=MODEL, max_tokens=200, messages=ASK)
u = r.usage
assert r.choices[0].message.content, "empty content"
assert u and u.prompt_tokens > 0 and u.completion_tokens > 0, "usage missing"
return "answered by " + r.model + ", in=" + str(u.prompt_tokens) + " out=" + str(u.completion_tokens)
def stream():
s = client.chat.completions.create(
model=MODEL, max_tokens=200, stream=True,
stream_options={"include_usage": True}, messages=ASK)
text, usage, finish = "", None, None
for c in s:
if c.usage:
usage = c.usage
if c.choices:
text += c.choices[0].delta.content or ""
finish = c.choices[0].finish_reason or finish
assert text, "no streamed text"
assert finish, "no finish_reason"
assert usage, "no usage chunk"
return "final chunk out=" + str(usage.completion_tokens)
def tool_call():
r = client.chat.completions.create(
model=MODEL, max_tokens=300, tools=TOOLS, tool_choice="required",
messages=[{"role": "user", "content": "What is the weather in Pune?"}])
call = r.choices[0].message.tool_calls[0]
assert "city" in json.loads(call.function.arguments), "no city argument"
return call.function.name
def json_mode():
r = client.chat.completions.create(
model=MODEL, max_tokens=200, response_format={"type": "json_object"},
messages=[{"role": "user", "content": "Return a JSON object with one key, ok, set to true."}])
return str(json.loads(r.choices[0].message.content))
def truncation():
r = client.chat.completions.create(
model=MODEL, max_tokens=5,
messages=[{"role": "user", "content": "Write a 200 word story about a lighthouse."}])
assert r.choices[0].finish_reason == "length", "finish_reason=" + str(r.choices[0].finish_reason)
def bad_model():
try:
client.chat.completions.create(model="no-such-model-xyz", max_tokens=5, messages=ASK)
except APIStatusError as e:
assert 400 <= e.status_code < 500, "status " + str(e.status_code)
return "status " + str(e.status_code)
raise AssertionError("an unknown model id was accepted")
for name, fn in [("model list", models_list), ("plain chat + usage", plain), ("streaming + usage chunk", stream),
("tool call", tool_call), ("JSON mode", json_mode), ("max_tokens cut-off", truncation),
("unknown model error", bad_model)]:
check(name, fn)
for name, status, note in rows:
print(status.ljust(5), name.ljust(26), note)
sys.exit(1 if any(r[1] == "FAIL" for r in rows) else 0)We ran this script against a small local mock server to check its own logic (all seven passed there), but we have not published results for any real provider, because the answer depends on the model id behind the endpoint and changes over time. Run it yourself:
export PROBE_BASE_URL="https://api.oneaiapikey.com/v1"
export PROBE_API_KEY="$ONEAIAPIKEY_API_KEY"
python probe_oa.py deepseek-deepseek-v4.1-flash:free
# Same script, other providers: only these two variables and the model id change
# PROBE_BASE_URL=https://api.groq.com/openai/v1 PROBE_API_KEY=... python probe_oa.py <a Groq model id>
# PROBE_BASE_URL=http://localhost:11434/v1/ PROBE_API_KEY=ollama python probe_oa.py <a local model name>How to read the output:
- model list FAIL usually means the id is misspelled or the endpoint does not publish a list. That is a warning, not a verdict: some providers accept ids their list omits.
- plain chat FAIL on “empty content” can mean a reasoning model spent the whole token budget thinking. Raise
max_tokensbefore blaming the endpoint. - streaming FAIL on “no usage chunk” means the endpoint ignores
stream_options. You can still bill by counting tokens yourself, but you lose a free cross-check. - tool call FAIL is common on models without tool support. Check the model’s page; on One AI API Key each model page lists capabilities.
- JSON mode FAIL on a model that does not honour
response_format. Use a forced tool call or a retry-and-validate loop. - unknown model error should be a 4xx with a readable message. On One AI API Key it is a 404 with code
model_not_found.
For the other half of the question, whether the model behind an id is the one it claims to be, use the real-model checks and the broader free gateway test protocol. The probe tests the plumbing; those tests the identity.
A five-step switch drill
What does it cost to stay, step down or switch?
The price list is where most people start, and OpenAI’s own page holds a surprise. On 28 November 2026 its pricing page lists these per-million-token output rates: $50.00 for gpt-6-astra and $40.00 for gpt-6.2-astra at the Standard tier, $10.00 for gpt-6.2-sol and gpt-6.1-sol, and $2.50 for gpt-6.1-terra and $0.25 for gpt-6-luna in the Flex table. Input rates sit in the same tables: $2.00 for the Sol models at Standard, $0.50 for Terra and $0.05 for Luna at Flex. The Standard table as loaded shows four flagship rows, which is why the smaller models appear here from the Flex table. Flex is a beta that OpenAI says it is winding down (“we won’t be adding Flex to new models”), so treat those two rows as a signal about the size ladder, not as a rate to build on.
OpenAI output price per 1M tokens, 28 November 2026
- gpt-6-astra, Standard$50.00
- gpt-6.2-astra, Standard$40.00
- gpt-6.1-sol, Standard$10.00
- gpt-6.1-terra, Flex$2.50Flex is a beta being wound down
- gpt-6-luna, Flex$0.25same note applies
Worked example. A team sends 40 million input tokens and 8 million output tokens a month to gpt-6.1-sol at Standard rates:
- Input: 40 × $2.00 = $80.00.
- Output: 8 × $10.00 = $80.00.
- Total: $160.00 a month.
The same volume at the Batch rates on the same page ($1.00 input, $5.00 output for gpt-6.1-sol) is 40 × $1.00 + 8 × $5.00 = $80.00, which is exactly half, and Batch is asynchronous, so it only suits work that can wait. At the Flex rates for gpt-6.1-terra it is 40 × $0.50 + 8 × $2.50 = $40.00. None of that needs a new endpoint. Before you move vendors, test whether a smaller model passes your own prompts; the guide to cutting LLM API costs lists that and nine other levers, and the cost calculator works the arithmetic for any token mix.
A different vendor is worth the effort when the gap is bigger than a step down or when you need something OpenAI does not offer: open-weight models, a free allowance, models from several labs behind one key, or data that stays on your machine. The calculator below turns a candidate’s price and your engineering time into a payback period. Fill in the new rates from the page you checked, never from a blog post, including this one.
Switch payback calculator
- Current bill per month
- $160.00
- Candidate bill per month
- $80.00
- Saving per month
- $80.00
- One-time switching cost
- $600.00
- Payback
- About 7.5 months
Defaults are the worked example above: OpenAI's Standard rates for gpt-6.1-sol against half of them. The hours and the hourly cost are assumptions, replace them. Nothing here is sent anywhere.
At the defaults the saving is $80.00 a month against $600.00 of switching cost, so payback is 7.5 months. Halve the hours and it is 3.8. Double the volume and it is 3.8 as well. The calculator is useful mainly for the case it rejects: a candidate whose bill is the same as yours has no payback at any engineering cost.
Which alternative fits which need?
There is no single replacement, because the reasons for leaving differ. Pick the closest need below; each answer says what to check first and does not rank the vendors.
What is the main reason you are looking beyond OpenAI?
Lower the bill on the same task
Try models without paying
Many labs behind one key
Gemini models
Claude models
Data on my own machine
Fewer outages
What should you put in config before you switch?
Switching is cheap once a model id and a base URL are values, not constants spread through the code. Two small habits cover most of it. First, keep the base URL, the key and every model id in environment variables or a config file. Second, route every request through a function that names a role (small chat model, large chat model) and looks up the id in one table:
import os
# One place that knows which model id means what on which endpoint.
# Swapping a vendor, or adding a fallback, becomes a config edit and not a code edit.
MODELS = {
"chat_small": os.environ.get("MODEL_CHAT_SMALL", "deepseek-deepseek-v4.1-flash:free"),
"chat_large": os.environ.get("MODEL_CHAT_LARGE", "MODEL_ID_FROM_YOUR_MODEL_LIST"),
}
def model(role):
return MODELS[role]With that in place, trying a second vendor is a change to three variables, and a fallback is a second entry. The longer plan, with a 30-minute drill, is in the vendor lock-in exit plan. The same idea at the other end of the stack is changing a Claude Code base URL without touching the tool. If a key leaks during the move, the first-hour checklist tells you what to rotate first.
Two more checks belong in the same pass. Put a spend limit on the new key before the first real request, so a bug in a loop cannot spend more than you decided; the per-project key guide shows how. And compare the new bill with your own token counts after the first day, which is what the token billing audit walks through.
What does One AI API Key offer, and where is it the wrong choice?
One AI API Key is an OpenAI- and Anthropic-compatible gateway, so the two lines above point your SDK at https://api.oneaiapikey.com/v1. You can test it at no cost before deciding anything:
- Sign in with Google on the sign-up page. There is no card field. The account gets a $10 sign-up credit for priced models.
- Create a key in the console, set the two variables from the code above and run the probe on a free id. The 48 ids that end in
:freeshare 100 requests and 3,000,000 tokens a day and work at a $0 balance. - If you want a priced model, the prices are published on the pricing page and the models table before you ask, and paid access is set up by hand over email at somdutt777@gmail.com. That is slower than a checkout button, a trade-off we explain in why paid access works by email.
You do not have to take our word for any of it. Status shows what the gateway measures, the transparency page says what we monitor and what we cannot see, and the rankings show real usage by model with a published minimum before a model is named. Free ids run on upstream providers we choose but do not host, and the company running a model receives the request. Prompts and answers are not stored, only counts (model, token counts, charge) are kept, and we do not train on user data; the data handling questions guide lists what to ask any gateway. The Acceptable Use policy applies to every request.
It is the wrong choice in a few cases, and we would rather say so. If you depend on stored Responses state, Files, Batch or fine-tuning, stay at OpenAI, because those routes answer 501 here. If you need a model that is not in our list, an endpoint that has it is a better fit; the comparison table and the OpenRouter comparison page show where others are broader. And if one vendor is all you use and you want the shortest path to its newest features, call that vendor directly: the gateway versus direct API post walks through when each wins. A gateway earns its place when you want several models behind one key, a free lane to test on, or a second route kept ready.
Point the SDK at a free id and run the probe
$10 sign-up credit, 48 free models sharing 100 requests and 3,000,000 tokens a day, no card.
Frequently asked questions
Can I really switch from the OpenAI API by changing two lines?
Is the OpenAI Chat Completions API going away?
Which alternative is closest to a drop-in replacement?
Does using another base URL change what my prompts cost?
usage object, so you can multiply tokens by the new rates yourself. Our billing audit guide shows how to compare reported tokens with your own count, and the calculator above turns a switch into a payback period.Will my existing OpenAI model ids work on another endpoint?
GET /v1/models on most of them) instead of editing the old string. Keep ids in configuration, as the exit plan guide recommends.How do I keep a second route ready if the new provider goes down?
X-Fallback-Models header, and the gateway tries them in order when a provider fails before it answers (routing documentation). The post on keeping an agent running when one provider is down shows a worked config.What can I try on One AI API Key without paying?
:free work straight away inside a shared daily allowance of 100 requests and 3,000,000 tokens. Paid access beyond that is set up by hand over email, and the post on why we do it that way explains the trade-off. The free ids list shows every id.