base_url, streamed tokens and retries: a keyless Python setup
You do not need a new library to try an LLM in Python. The official openai package talks to any compatible server, so this page shows a working client against a free, keyless endpoint, with streaming and retry code you can keep when you move to a paid provider.
APIOpenAIFreeKey editorial team · Updated 2026-11-16
A Python client created with a custom base_url prints the free-ai reply as it streams in.
People who look for a free OpenAI API key are often in the middle of a Python tutorial. The notebook says client = OpenAI(), the script fails with an authentication error, and the next step is a billing page. Before reaching for a key list on some forum, it helps to know that the openai package is only an HTTP client, and that it can be pointed at a different server with one argument.
This page walks through that route. It covers what OpenAI itself offers to new developers, then a keyless OpenAI-compatible API that serves an open-weight model called free-ai. That model is not GPT. You get complete Python snippets for plain calls, token streaming, timeouts and retries, plus a short list of the cases where a real OpenAI key is the better answer.
Python and OpenAI key questions
What does base_url do in the OpenAI Python client?
It sets the server the client sends requests to. By default the openai package calls OpenAI's own address. If you pass base_url="https://api.apiopenaifreekey.com/v1" when creating OpenAI(...), every method, including chat.completions.create, goes to that server instead. The request and response objects stay the same, so the rest of your code does not change.
Is this endpoint free, and what does OpenAI's API cost?
This endpoint is free within per-IP daily limits, with no card and no account. OpenAI's API is billed per token, and any trial credit or free usage they offer depends on account, region and time. Check OpenAI's current pricing page for real numbers rather than relying on blog posts or forum summaries, which go stale quickly.
How do I get a genuine OpenAI API key for Python?
Create an account on OpenAI's developer platform, open a project, go to the API keys page and generate a secret key. Add billing if requests are refused. Then export it as OPENAI_API_KEY in your shell; the Python client reads that variable automatically, so the key never needs to appear in your source files.
Does the Python client need an api_key value here?
The client raises an error if no key is set at all, so pass any placeholder string, for example api_key="free". The server ignores it. Because nothing secret is involved, you can commit the placeholder to a public repository or share the notebook without worrying about leaking credentials.
Is free-ai the same as GPT-4o or another OpenAI model?
No. free-ai is an independent open-weight model of about 35B parameters, fine-tuned to refuse far less than commercial assistants. It only shares the request format with OpenAI. GPT models are clearly better at hard reasoning, long programs and image or audio input. free-ai is suited to learning the SDK, prototypes, chat and text tasks.
How does streaming work with this API in Python?
Pass stream=True to chat.completions.create and iterate over the result. Each chunk carries a small piece of text in choices[0].delta.content, which may be None on the first and last chunks. Under the hood the server sends server-sent events and closes the stream with data: [DONE].
What rate limits will my Python script hit?
Per IP: one request per second with bursts of three, two parallel requests, and 10,000 requests or 10,000,000 tokens a day, reset at 00:00 UTC. Context holds 32,000 tokens and a reply can reach 16,000. Over the limit you receive 429 with a Retry-After header; a busy server returns 503, which deserves a retry after two to five seconds.
Can I use a free key someone posted online instead?
Please do not. Shared keys in pastes and repositories are usually exposed by mistake or taken from compromised accounts. They are revoked quickly, someone else is billed for your calls, and your script breaks without warning. Tools that claim to generate keys do not work, because only OpenAI's servers issue valid ones.
What is logged when my code calls this API?
Each request leaves a technical record: time, IP, User-Agent, country, endpoint, status, latency, request and response sizes, and token counts. The IP enforces limits. There are no accounts, and the API keeps no conversation history between calls. Keep passwords, secrets and personal data out of prompts, as you would with any third-party service.
Independent service. APIOpenAIFreeKey is not affiliated with OpenAI and does not hand out, resell or generate OpenAI keys. The free-ai model here is not GPT or any other OpenAI model; it only accepts the same request format, so the official Python SDK can call it.
No key: nothing to create, store or rotateOpenAI-compatible: the same openai package, a new base_urlWorks in the browser: open CORS for front-end testsMany languages: prompts and replies beyond EnglishFast: 100+ tokens per second when streaming
Five steps to a working Python client
These steps assume Python 3.8 or newer and a terminal. Nothing needs to be registered, and the same script will later run against OpenAI with two changed values.
Only base_url, api_key and model differ between this endpoint and OpenAI's.
Install the package
Run pip install openai in a virtual environment. Recent versions of the library all support a custom base_url.
Create the client
Write client = OpenAI(base_url="https://api.apiopenaifreekey.com/v1", api_key="free"). The key is a placeholder that keeps the library happy.
Send one message
Call client.chat.completions.create(model="free-ai", messages=[...]) and print resp.choices[0].message.content.
Turn on streaming
Add stream=True and loop over the chunks, printing each delta.content with end="" and flush=True.
Wrap it in retries
Catch RateLimitError and server errors, sleep for Retry-After or a few seconds, and try again a limited number of times.
Why the Python tutorial stops at an authentication error
Most OpenAI examples start with from openai import OpenAI and client = OpenAI(). That constructor looks for an environment variable named OPENAI_API_KEY. If it is missing you get an error before any request is sent; if it is present but the project has no billing or credit, the first request comes back with an authentication or quota error. Either way, the tutorial stalls at the point where you wanted to see a model answer.
The tempting next move is to search for a key someone else has posted. That is exactly the wrong fix. What the error really tells you is that the default server wants an account with billing attached. You have two honest choices: set up that account on OpenAI's platform, or give the same client a different server that does not need a key at all.
Reading the error message
An error raised while building the client means no key was found. A 401 means the key is wrong or revoked. A 429 with a quota message means the key is valid but the project has nothing to spend.
The client is just HTTP
The openai package formats JSON, sends it over HTTPS and parses the reply. Any server speaking the same format can sit on the other end.
A missing or unfunded key is the usual reason a first Python call fails.
What OpenAI offers new developers on its own platform
OpenAI's developer platform is the only legitimate source of OpenAI keys. Over the years it has offered different entry points: trial credit for some new accounts, small and inexpensive models, batch processing at reduced rates, and credit programmes for startups. None of these is guaranteed to exist for you today, and the amounts and conditions change. The reliable approach is to read the pricing and rate limit pages on the platform itself before you plan a budget.
If you do create a key, treat it like a password from the first minute. Put it in an environment variable or a secrets manager, never in a notebook cell you might share, and set a monthly usage limit in the billing settings so a runaway loop cannot surprise you.
Generate keys per project so test and production spending stay apart
Export the key as OPENAI_API_KEY instead of hard-coding it
Set a usage cap and alerts before running loops or batch jobs
Check the rate limit page for your organisation's current tier
Revoke any key that ends up in a commit, log or screenshot
A real key comes from the platform console and lives in the environment, not the code.
Test the model before writing code
Type a prompt and see how free-ai answers. This box uses the same API and the same per-IP limits as your Python script.
apiopenaifreekey engine8 live panels
Every request, live. One real day of the free-ai API, 1 Dec, replayed second by second.
panels0/8ready
answers55,5101 Dec
model1free-ai
REPLAY · --:--:-- UTC · 1 Dec
Answers so far55,510of 55,510 on 1 Dec
Tokens read489Mprompts + history
Tokens written46.0Mmodel replies
Answer time3.0 smedian · p90 15.6 s
Speed22 tok/smedian · p90 34
Since 10 Nov509Kanswers · peak 61.0K
01
Live requests
one node = one real request · grouped by prompt sizeLOADING
55,510 answers on 1 Dec489M tokens read46.0M tokens writtenanswer time 3.0 s median22 tok/s median509,307 answers since 10 Novone model: free-aiOpenAI-compatible api.apiopenaifreekey.com/v1no key, no account: test it in the box above first55,510 answers on 1 Dec489M tokens read46.0M tokens writtenanswer time 3.0 s median22 tok/s median509,307 answers since 10 Novone model: free-aiOpenAI-compatible api.apiopenaifreekey.com/v1no key, no account: test it in the box above first
Data: the request log of the free-ai API that serves this site and the other sites of the same service, all together, for 1 Dec 2026 (UTC): successful answers only, automated bot traffic excluded. The log keeps counts, token sizes and timings; this panel shows no prompt text, no sites and no visitors. The live panels replay that day at real speed: one node or log line is one request made that day at this time of day.
Pointing the client at a keyless OpenAI-compatible server
This site runs an API that accepts OpenAI-style requests and answers them with free-ai, an independent open-weight model of roughly 35B parameters. It is tuned to refuse much less than commercial assistants, while keeping two hard limits: no sexual content involving minors and no operational instructions for mass-casualty weapons. There is no sign-up, no key and no bill.
In Python the change is a single constructor call. Pass base_url="https://api.apiopenaifreekey.com/v1" and a placeholder api_key, then use model="free-ai" in your requests. Everything else in the tutorial you were following, from the messages list to reading choices[0].message.content, works unchanged. The service is stateless, so your code keeps the conversation and sends it with each call.
Environment variables instead of arguments
The client also reads OPENAI_BASE_URL. Set it together with a dummy OPENAI_API_KEY and even OpenAI() with no arguments will use this endpoint.
Checking the model list
Call client.models.list() to confirm the connection. It returns free-ai, which is the only model name accepted here.
One constructor argument moves every request to the keyless server.
Streaming tokens from Python as they are generated
Waiting for a whole answer makes a chat feel slow, especially for long replies. With stream=True the server sends the text as a series of server-sent events, and the Python client turns them into an iterator of chunk objects. You print or forward each piece the moment it arrives. With free-ai that is usually more than 100 tokens per second, so the reply appears to type itself.
A typical loop reads chunk.choices[0].delta.content, skips empty values and writes the rest with print(text, end="", flush=True). The stream ends when the server sends data: [DONE], which the library handles for you. If you need the full text afterwards, append each piece to a list and join it at the end.
Async streaming
Use AsyncOpenAI with the same base_url and async for over the stream. This suits web frameworks such as FastAPI that forward tokens to a browser.
Stopping early
Breaking out of the loop closes the connection. That is a cheap way to cap output in an interactive tool when the user has seen enough.
Reasoning output
Passing extra_body={"reasoning": True} asks the model to think first. Raise max_tokens to 2000 or more so the answer is not cut off.
Streamed chunks let a Python script display the reply while it is still being written.
Python, JavaScript and curl examples
Every tab sends the same question to https://api.apiopenaifreekey.com/v1 using the model free-ai. The key is a dummy value the server ignores.
curl https://api.apiopenaifreekey.com/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model":"free-ai","messages":[{"role":"user","content":"Show a Python loop that retries a request three times"}]}'
from openai import OpenAI
client = OpenAI(base_url="https://api.apiopenaifreekey.com/v1", api_key="free")
# Your question
r = client.chat.completions.create(
model="free-ai",
messages=[{"role": "user", "content": "Show a Python loop that retries a request three times"}],
)
print(r.choices[0].message.content)
const r = await fetch("https://api.apiopenaifreekey.com/v1/chat/completions", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({
model: "free-ai",
// Your question
messages: [{role: "user", content: "Show a Python loop that retries a request three times"}]
})
});
const data = await r.json();
console.log(data.choices[0].message.content);
A free endpoint shares its capacity, so your code should expect two kinds of temporary refusal. A 429 means your IP has gone over a limit: more than one request per second beyond a short burst of three, more than two requests at once, or the daily ceiling. The response includes a Retry-After header with the number of seconds to wait. A 503 means the model is busy with other users, and a retry after two to five seconds normally succeeds.
The Python client has a built-in max_retries setting, which is a good start. For finer control, catch openai.RateLimitError and openai.APIStatusError, read the header from err.response.headers, sleep, and try again up to a fixed number of attempts. Add a little random jitter so several workers do not retry in lockstep.
Timeouts
Set timeout=60 or similar on the client. Long replies take time, but a request that hangs for minutes should fail and be retried.
Concurrency
If you use threads or asyncio, cap parallel calls at two with a semaphore. More only produces extra 429 responses.
Honour Retry-After on 429 and back off for a few seconds on 503.
Python tasks that run well on a 35B model
Knowing the size of the model saves frustration. A model of about 35B parameters is quick and capable for everyday text work, and much weaker than OpenAI's large models on long chains of reasoning. In Python projects it fits well wherever you need language handling inside a script rather than deep expertise.
Good examples include turning messy notes into clean paragraphs, classifying support messages into a few labels, pulling fields such as dates or names into JSON, translating short strings, writing docstrings, and generating test data. For structured output, describe the exact JSON shape in the prompt, then validate it with json.loads or a schema library and retry once if parsing fails.
Summaries and rewrites of text up to the 32,000-token context
Labelling and routing short messages
Field extraction into JSON you validate in Python
Simple code explanations, docstrings and small snippets
Chat bots and command-line assistants for personal use
Ask for a precise JSON shape and validate it in your Python code.
Rate limits your script should respect
Per IP: 1 request per second with bursts of 3, at most 2 requests in parallel, 10,000 requests or 10,000,000 tokens per day, reset at 00:00 UTC. Context 32,000 tokens, replies up to 16,000. 429 carries Retry-After; 503 means retry in 2-5 seconds. Text only.
requests per second
1
parallel requests
2
context, tokens
32,000
answer, tokens
16,000
requests per day
10,000
tokens per day
10,000,000
The limits at a glanceDaily allowance resets at 00:00 UTCOrderly retry after a 429
Keeping one codebase for free tests and paid production
The cleanest pattern is to make the provider a configuration choice. Read OPENAI_BASE_URL, OPENAI_API_KEY and a model name from the environment, and build the client from them. In development the variables point at this endpoint with free-ai; in production they point at OpenAI with your real key and the GPT model you chose.
This keeps the switch away from your logic and makes comparisons easy. Run the same test prompts against both, store the outputs, and decide whether the quality gap matters for your use. Remember that prompts tuned on a small model usually work on a larger one, but output formats can drift, so keep the JSON validation step in both setups.
A .env file per environment
Keep a local file for the free endpoint and inject production secrets from your hosting platform. Never commit the production file.
Feature flags for model choice
Some teams send cheap background jobs to a small model and user-facing requests to a larger one. A config value per task makes that easy to change.
The same Python application can target different OpenAI-compatible servers by configuration.
Other ways to call the endpoint besides the Python SDK
The SDK is convenient, but not required. Since the API speaks plain HTTP, the requests or httpx libraries can post JSON to /v1/chat/completions directly. That is useful in small scripts where you would rather avoid another dependency, or when you want to see the exact bytes on the wire.
For a quick check from a shell, GET /ask?q= returns a plain text answer, or JSON when you add &format=json. GET /health reports whether the service is up, which is handy in a startup check before a long batch job. Many editor plugins and agent frameworks also accept a custom OpenAI base URL and work with the same settings.
Legacy completions
Older code using client.completions.create with a single prompt string also works, through POST /v1/completions.
Help from a coding assistant
Copy prompt.txt with the button on this page and paste it into your assistant. It describes the endpoint, so generated Python code uses the right URL and model.
Plain HTTP and the /ask shortcut work without any SDK installed.
OpenAI's API and this endpoint from a Python developer's view
A plain comparison for people writing Python clients. Confirm details about OpenAI's API on their own documentation and pricing pages, since they change.
OpenAI API
free-ai on APIOpenAIFreeKey
Who wins
Setup in Python
Account, project, billing, secret key
pip install openai and a base_url
free-ai for a first script
Price
Metered per token, see pricing page
Free inside per-IP daily limits
free-ai
Answer quality
Large GPT models
About 35B open-weight model
OpenAI
Complex reasoning and long code
Strong, dedicated reasoning models
Basic, optional reasoning flag
OpenAI
Images, audio, embeddings
Supported on several models
Text only
OpenAI
Streaming in the SDK
Supported
Supported, ends with [DONE]
Tie
Secrets to protect
A key that can spend money
Nothing secret
free-ai
Throughput and guarantees
Tiered limits, published terms, support
Per-IP limits, no SLA
OpenAI
Learn and prototype for free; switch the base_url to a paid provider when quality or guarantees count.
Key lists, generators and session hacks to avoid
Search results around free OpenAI keys are crowded with shortcuts. Some repositories publish keys scraped from other people's code. Some tools claim to generate keys. Others log into a consumer chat app with your browser session and expose it as a local API. All of these break, and some put you at real risk.
No generator can create a working key, since keys are issued by OpenAI's servers and checked against its records. Posted keys belong to someone else, are usually revoked within hours, and running traffic on them can be treated as abuse. Session-based wrappers rely on undocumented web traffic, can change or stop working at any time, and may violate the terms of the account they use. A keyless endpoint that openly runs a different model avoids every one of these problems.
If your own key was exposed
Revoke it on the platform console, create a new one, look at recent usage for unfamiliar spikes, and lower your spend limit until you are sure.
Third-party gateways
Some routers are legitimate businesses. Prices far below the provider's own, invite-only offers and vague model claims are good reasons to look elsewhere.
Keep real keys out of code; use a keyless endpoint when you have none.
Signs your Python project has outgrown the free endpoint
This service has no SLA, no support contract and no accounts, and its limits are counted per IP. That is fine for learning, side projects and internal tools, but it is not a promise anyone should build a business on. If your script runs on a shared server, every user behind it shares one daily budget.
Move to a paid provider when quality, modalities or guarantees start to matter: users notice weak answers on difficult questions, you need image input, audio or embeddings, regular 429s slow your batch jobs, or a customer asks about uptime and data handling terms. With configuration in environment variables the move is quick. Create a key on OpenAI's platform, change three values and rerun your tests.
Keep the free endpoint for CI
Unit tests that only need some plausible text can keep using the keyless server, so test runs never touch the paid budget.
Measure before switching
Log token counts from resp.usage during development. They give a realistic basis for estimating what the same workload will cost on a paid model.
Start free, measure usage, then decide whether a paid model is worth it.
What the server records about your calls
For each request the service writes a technical log line: time, IP address, User-Agent, country, endpoint, status code, latency, request and response sizes, and token counts. The IP address is what the per-IP limits are counted against. Since there are no accounts, requests are not linked to a name or email unless your prompt contains one.
Nothing is kept between calls: the API is stateless, and your Python code decides which messages to send each time. Treat it like any external service and keep passwords, keys, customer records and confidential documents out of prompts. If your project needs written data guarantees, choose a provider that offers them in a contract.
Learn how to distinguish legitimate OpenAI billing notifications from phishing scams targeting API key users. Verify sender domains, inspect URLs, and check.
Diagnose latency spikes in OpenAI-compatible deployments. Learn how region selection, server load, and rate limits affect your production response times.
Learn how browser extensions intercept, inject, and automate API calls in web interfaces. Explore tools, security risks, and practical use cases for developers.
Learn to construct a unified OpenAI-compatible endpoint that routes code generation tasks to optimized models like GPT-5 and cheaper alternatives, reducing.
Compare stability, rate limits, and cost-efficiency of free third-party endpoints against official paid tiers for long-term projects. Learn when to switch.
Diagnose why image generation features are missing in third-party clients. Learn to fix endpoint compatibility and configuration issues for APIOpenAIFreeKey.
Learn to direct complex queries to high-end reasoning models and simple requests to cheaper alternatives, optimizing both cost and speed without changing your code.
Compare hardware costs, maintenance effort, and latency between running your own LLM server and using a relay API service. Find the right fit for your team.