Key points
- Install the openai package, set base_url to https://api.gemma4api.com/v1 and use the model ID
uncensored. - Streaming, JSON mode and tool calling all use the normal OpenAI parameters.
- A 429 with the code rate_limited or concurrency means a limit was hit; retry with a pause.
- This is an independent service, not the official API of Google or any other vendor.
Install and make the first request
Everything below uses the official openai Python package (version 1.x). You do not need a special client. Install it:
pip install --upgrade openai
Then create a key. Sign up with Google or with email and password, open the API key page, and copy the key. New users can also claim $0.50 of trial credit there with one click, no card needed. Keep the key in an environment variable instead of in your source:
export GEMMA_API_KEY="paste-your-key-here"
A first request looks like this:
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.gemma4api.com/v1",
api_key=os.environ["GEMMA_API_KEY"],
)
response = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "You are a concise technical assistant."},
{"role": "user", "content": "Explain list comprehensions in two sentences."},
],
)
print(response.choices[0].message.content)
print(response.usage)
That is a complete working call. The SDK sends Authorization: Bearer <key> for you. If you prefer, you can skip the api_key argument and set OPENAI_API_KEY and OPENAI_BASE_URL in the environment, then call OpenAI() with no arguments.
What you are connecting to
One clarification, because the query names a model. This service is not the official API of Google, and it is not a router across vendors. It hosts a single open-weight model, run by an independent provider and tuned to answer without content refusals for lawful adult use. In code, that model is always uncensored. Read the uncensored Gemma explainer if you want the background on the naming.
It supports two methods: POST /v1/chat/completions and GET /v1/models. You can confirm the connection and see the model list with one call:
for model in client.models.list():
print(model.id)
If that prints uncensored, your key and base URL are correct. If you get an authentication error, check that there are no spaces around the key and that you used the key for this site.
Multi-turn chat and parameters
The API is stateless, as with any chat completions endpoint. You keep the history and send it each time:
messages = [{"role": "system", "content": "You are a helpful assistant."}]
def ask(text):
messages.append({"role": "user", "content": text})
r = client.chat.completions.create(
model="uncensored",
messages=messages,
temperature=0.7,
top_p=0.95,
max_tokens=400,
seed=42,
)
answer = r.choices[0].message.content
messages.append({"role": "assistant", "content": answer})
return answer
print(ask("Name three uses of Python generators."))
print(ask("Show a short example of the second one."))
temperature, top_p, stop, seed and the frequency and presence penalties are passed through to the model. max_tokens is optional; without it, the completion can use whatever is left of the 100,000-token window, which is shared between prompt and reply. Since you pay for input tokens on every call at $0.15 per 1M, long histories are worth trimming. A request with 3,000 input tokens and 300 output tokens costs $0.00045 plus $0.00015, which is $0.0006 in total.
Streaming
Set stream=True and iterate over the chunks. The API uses server-sent events and reports usage at the end of the stream.
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write a four-line poem about debugging."}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
print()
Always check chunk.choices before indexing. The last chunk, the one with usage, can arrive without any choices, and an unguarded chunk.choices[0] raises an IndexError. Remember also that a streamed request occupies one of your concurrency slots until the stream ends, so close or finish streams you no longer need.
JSON mode and tool calling
For structured output, use JSON mode. Tell the model in the prompt that you want JSON, and set the response format:
import json
r = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "Reply with a JSON object with keys name and tags."},
{"role": "user", "content": "Describe the Python language."},
],
response_format={"type": "json_object"},
)
data = json.loads(r.choices[0].message.content)
print(data)
Still wrap json.loads in a try block in production. JSON mode makes valid output likely, and a request cut off by max_tokens can still produce a truncated object.
Tool calling follows the OpenAI format. You describe the function, the model returns a call, you run it and send back the result with role: "tool":
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current temperature for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
messages = [{"role": "user", "content": "What is the weather in Lisbon?"}]
first = client.chat.completions.create(
model="uncensored", messages=messages, tools=tools, tool_choice="auto"
)
call = first.choices[0].message.tool_calls[0]
messages.append(first.choices[0].message)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps({"city": "Lisbon", "temp_c": 21}),
})
final = client.chat.completions.create(
model="uncensored", messages=messages, tools=tools
)
print(final.choices[0].message.content)
In real code, check that tool_calls is not empty before reading the first item, since the model may answer directly.
Async usage for parallel work
If you process many items, the async client keeps your program responsive and makes the concurrency limit easy to respect. The cap of 8 concurrent requests on a full key maps directly to a semaphore.
import asyncio
import os
from openai import AsyncOpenAI
client = AsyncOpenAI(
base_url="https://api.gemma4api.com/v1",
api_key=os.environ["GEMMA_API_KEY"],
)
gate = asyncio.Semaphore(8)
async def summarize(text):
async with gate:
r = await client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Summarize in one line: " + text}],
max_tokens=80,
)
return r.choices[0].message.content
async def main():
items = ["first document", "second document", "third document"]
results = await asyncio.gather(*(summarize(t) for t in items))
for line in results:
print(line)
asyncio.run(main())
With a trial key the concurrency limit is 2, so change the semaphore to 2 while you test. The semaphore is not a replacement for the per-minute limit. If you queue thousands of items, add a small delay or a token-bucket check so you stay under 300 requests per minute on a full key, or 60 on a trial key.
Errors, limits and common mistakes
The limits for a full key are 8 concurrent requests and 300 requests per minute. A trial key gets 2 and 60. Going over returns HTTP 429. The error code tells you which limit: rate_limited for requests per minute, concurrency for too many requests at once. On temporary overload the API also returns 429 with a Retry-After: 5 header.
The openai package already retries some failures a couple of times by default. You can raise that, and handle what remains:
import os
import time
import openai
from openai import OpenAI
client = OpenAI(
base_url="https://api.gemma4api.com/v1",
api_key=os.environ["GEMMA_API_KEY"],
max_retries=4,
timeout=120,
)
def safe_ask(messages, tries=3):
for attempt in range(tries):
try:
return client.chat.completions.create(model="uncensored", messages=messages)
except openai.RateLimitError as e:
time.sleep(5 * (attempt + 1))
raise RuntimeError("still rate limited")
If you run work in parallel, cap it at 8 workers with a ThreadPoolExecutor(max_workers=8) or an asyncio.Semaphore(8) so you never exceed the concurrency limit on your own. Each response carries X-Request-Id, which is worth logging for support. The docs page has the full parameter list.
Common mistakes
- Wrong base URL. The base URL must end in
/v1. Without it you will see 404 errors, because the SDK appends/chat/completionsto whatever you give it. - Wrong model name. Use
uncensored. Names from other providers are not valid here. - Reading a missing field. With streaming, some chunks carry no text. Check before you concatenate, and treat
Noneas an empty string. - Dropping history. If answers seem to forget earlier messages, you are probably not appending the assistant reply to your list.
- Huge prompts. The body limit is 8 MB and the window is 100,000 tokens. Count tokens or measure length before sending a large document, and split it when needed.
- Retry storms. Retrying a 429 instantly makes the situation worse. Wait at least the five seconds suggested by
Retry-After.
Requests that fail or are refused are not charged, so a failed experiment does not eat into your credit. Top-ups start at $20, and the bonus tiers are listed on the pricing page.
Going further
Once the basics work, three habits pay off. Read the balance from the X-Balance-USD header using client.chat.completions.with_raw_response.create(...) and alert yourself when it drops. Log usage.prompt_tokens and usage.completion_tokens per request and compare them with the rates on the pricing page, which are $0.15 per 1M input and $0.50 per 1M output tokens. And keep your key out of version control.
The same base URL and model ID work in any other OpenAI-compatible client, such as LangChain's OpenAI chat class or an editor plugin that lets you set a custom endpoint. Only the two settings change.
One more tip for teams: keep the base URL, key and model name in one small configuration module, so switching environments or rotating a key is a one-line change. If you generate text for many users, store each conversation's history on your side, and trim it with the same rule everywhere. A consistent rule makes costs predictable, and it keeps responses from changing character when a conversation grows long. If you later need help from the service owner, the X-Request-Id value of the failing call is the most useful thing to include.
That covers the whole Python path, from the first request to concurrent jobs. The reference for every field is in the docs, and your trial credit is waiting on the API key page if you have not claimed it yet.
More guides
Questions and answers
Do I need a special Python SDK?
No. The standard openai package works. Set base_url to https://api.gemma4api.com/v1, pass your key, and use the model ID uncensored.
Does it support async Python?
Yes, through the same package. Use AsyncOpenAI with the same base URL and key, and keep concurrent requests at or below 8.
How do I count my cost per call?
Multiply usage.prompt_tokens by 0.15 and usage.completion_tokens by 0.50, then divide by 1,000,000.
Is this the official Google Gemma API?
No. It is an independent OpenAI-compatible service running one open-weight model, and it is not run by Google or any other model vendor.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.
