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.

  • pip install openai
  • No key required
  • Streaming SSE
  • Retry on 429/503

APIOpenAIFreeKey editorial team · Updated 2026-11-16

Terminal window running a short Python script that streams a chat reply token by token
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.

Crossed-out key icon: no API key is needed
No key: nothing to create, store or rotate
Plug connector icon for OpenAI-compatible clients
OpenAI-compatible: the same openai package, a new base_url
Browser window icon calling the API directly
Works in the browser: open CORS for front-end tests
Globe icon with letters from several languages
Many languages: prompts and replies beyond English
Lightning bolt over a speedometer for fast replies
Fast: 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.

Numbered steps from one to three
Only base_url, api_key and model differ between this endpoint and OpenAI's.
  1. Install the package

    Run pip install openai in a virtual environment. Recent versions of the library all support a custom base_url.

  2. 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.

  3. Send one message

    Call client.chat.completions.create(model="free-ai", messages=[...]) and print resp.choices[0].message.content.

  4. Turn on streaming

    Add stream=True and loop over the chunks, printing each delta.content with end="" and flush=True.

  5. 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.

Connected nodes forming an automated workflow
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
Code editor with a Python script using the OpenAI client
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.

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
  • prompt < 1K tokens0
  • prompt 1K–4K0
  • prompt 4K–16K0
  • prompt 16K+0
  • since you opened · 1 Dec
zoom 100% · nodes 0 · links 0 · signals 0
02

Request log

no prompt textLOADING
$ tail -f requests.log
    03

    Request lifecycle

    one sampled request · real timingLOADING
    1. request receivedok
    2. per-IP limitok
    3. safety checkpass
    4. routed to modelfree-ai
    5. generating
    6. answer returned
    04

    24 hours

    answers per hour, UTCLOADING
    5,149peak hour 03:00 UTC
    0006121824
    05

    Day by day

    answers per dayLOADING
    509,307answers since 10 Nov
    11-1012-01
    06

    Speed

    output tokens per second, streamed repliesLOADING
    median
    22 tok/s
    fastest 10%
    34+ tok/s
    needle
    sampled requests
    07

    Answer time

    full reply, all requestsLOADING
    3.0 smedian
    02 s6 s15 s30 s+
    08

    Plug in

    OpenAI-compatible · no keyLOADING
    curl https://api.apiopenaifreekey.com/v1/chat/completions -H "Content-Type: application/json" -d '{"model":"free-ai","messages":[{"role":"user","content":"Hi"}]}'
    • Base URLhttps://api.apiopenaifreekey.com/v1
    • Modelfree-ai, open-weight, about 35B
    • Keynot needed
    • Limitsper IP

    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.

    Window with a JSON response from the API
    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.

    Chat bubbles between a person and an assistant
    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"}]}'

    Window with a JSON response from the API including the generated text
    A response in Chat Completions format

    Retry logic for 429 and 503 responses

    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.

    Illustration of a document with a pen writing text
    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
    Code editor with a JavaScript fetch call to the API
    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
    Bar chart of the per-second, parallel and daily limits of the API
    The limits at a glance
    Ring gauge showing how much of the daily request allowance is left
    Daily allowance resets at 00:00 UTC
    Diagram of a 429 error followed by retries with growing waits
    Orderly 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.

    Illustration of code brackets and a developer tools panel
    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.

    Diagram from your app to the gateway, the GPU model and the answer
    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 APIfree-ai on APIOpenAIFreeKeyWho wins
    Setup in PythonAccount, project, billing, secret keypip install openai and a base_urlfree-ai for a first script
    PriceMetered per token, see pricing pageFree inside per-IP daily limitsfree-ai
    Answer qualityLarge GPT modelsAbout 35B open-weight modelOpenAI
    Complex reasoning and long codeStrong, dedicated reasoning modelsBasic, optional reasoning flagOpenAI
    Images, audio, embeddingsSupported on several modelsText onlyOpenAI
    Streaming in the SDKSupportedSupported, ends with [DONE]Tie
    Secrets to protectA key that can spend moneyNothing secretfree-ai
    Throughput and guaranteesTiered limits, published terms, supportPer-IP limits, no SLAOpenAI
    Chart comparing a free service with paid plans
    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.

    Chart comparing a free service with paid plans
    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.

    Text tokens arriving one by one as the model writes
    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.

    Shield icon for good practice with a public service
    Good practice with a public service

    Guides and answers about free AI API usage

    Articles →