EN ▾

Uncensored API for your scripts

Get API key

https://api.nsfwgemini.cc/v1

How to Call a Gemini-Style API in Python (OpenAI SDK)

This is how to call a Gemini-style chat API in Python when the service speaks the OpenAI format: install the openai package, point it at a new base URL, and use the model ID uncensored. The service here is not Google's Gemini, so Google's own SDK is not needed.

Updated

Glowing coiled snake of circuit lines passing through a gateway toward a server tower, representing Python API calls

The shortest working example

People who ask how to call gemini api in python often have Google's own library in mind. That library has its own client, its own key and its own request shape. This page covers a different route. The endpoint at https://api.nsfwgemini.cc/v1 copies the OpenAI chat completions format, runs a single open-weight model, and is not operated by Google. Because the format is the common one, the standard openai package works unchanged.

pip install openai
from openai import OpenAI

client = OpenAI(
    base_url="https://api.nsfwgemini.cc/v1",
    api_key="YOUR_KEY",
)

resp = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "You are a concise writing assistant."},
        {"role": "user", "content": "Give me three opening lines for a noir story."},
    ],
)

print(resp.choices[0].message.content)
print(resp.usage)

Three things changed from a stock OpenAI script: the base_url, the key, and the model name. Everything after that line is ordinary SDK usage. Get a key from the API key page. New accounts can claim $0.50 of trial credit with one click, valid for 7 days, no payment details needed.

Keep the key out of your code

Hard-coding a key works for a ten-second test and becomes a problem the moment the file reaches a repository. Read it from the environment instead:

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.nsfwgemini.cc/v1",
    api_key=os.environ["NSFWGEMINI_API_KEY"],
)

Export the variable in your shell (export NSFWGEMINI_API_KEY=...) or put it in a .env file that your tooling loads and your version control ignores. The auth header the SDK sends is Authorization: Bearer <key>, which is the form this API expects, so there is nothing else to configure.

If the call returns a 401, the usual causes are a copy error, a stray newline from a shell command, or a key from a different site. Print len(key) to spot hidden whitespace without printing the key itself.

Multi-turn chat and sampling options

The API is stateless. It does not remember earlier requests, so you resend the conversation each time. Keep a list and append to it:

history = [{"role": "system", "content": "You are a dry, witty co-writer."}]

def ask(text):
    history.append({"role": "user", "content": text})
    r = client.chat.completions.create(
        model="uncensored",
        messages=history,
        temperature=0.9,
        top_p=0.95,
        max_tokens=400,
    )
    answer = r.choices[0].message.content
    history.append({"role": "assistant", "content": answer})
    return answer

print(ask("Start a scene in a lighthouse."))
print(ask("Now add a visitor nobody expected."))

temperature, top_p, stop, seed and the frequency and presence penalties are passed through to the model. max_tokens is optional. If you leave it out, the reply may use whatever remains of the 100,000-token window, prompt included. Setting it is still sensible, because a runaway reply is billed as output at $0.50 per 1M tokens.

Since each call resends the full history, input cost grows with conversation length. Trim old turns or summarise them once the list gets long.

A simple trimming rule works well for chat apps: keep the system message, keep the last ten or so turns, and replace everything older with a short summary that you generate once with a separate call. That keeps the prompt small and the bill predictable, and it keeps the character voice stable because the system message never leaves the list. Remember the window is 100,000 tokens in total, so even a very long chat will fit, but fitting is not the same as being cheap.

Streaming replies

For anything a person watches, stream. The server sends server-sent events, and the SDK turns them into an iterator:

stream = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Describe a market at dawn in 120 words."}],
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if chunk.usage:
        print("\n", chunk.usage)

Usage arrives at the end of the stream, so you can log token counts even when you never saw a non-streamed response. One rule to remember: a streamed request keeps its concurrency slot until the stream ends. If you start a stream and abandon it without closing it, that slot stays busy. Iterate to the end, or close the stream in a finally block.

JSON mode and tool calls

When another program consumes the output, ask for JSON:

import json

r = client.chat.completions.create(
    model="uncensored",
    response_format={"type": "json_object"},
    messages=[
        {"role": "system", "content": "Reply only with a JSON object."},
        {"role": "user", "content": "Give a title and three tags for a short story about a ferry."},
    ],
)
data = json.loads(r.choices[0].message.content)
print(data)

Mention the word JSON in your instructions, as above, and wrap json.loads in a try block anyway. A reply cut off by a small max_tokens will not parse.

Tool calling uses the same fields as the OpenAI API: tools, tool_choice, tool calls in the reply, and your results sent back as messages with role: "tool".

tools = [{
    "type": "function",
    "function": {
        "name": "roll_dice",
        "description": "Roll a die with the given number of sides",
        "parameters": {
            "type": "object",
            "properties": {"sides": {"type": "integer"}},
            "required": ["sides"],
        },
    },
}]

msgs = [{"role": "user", "content": "Roll a twenty-sided die for me."}]
r = client.chat.completions.create(model="uncensored", messages=msgs, tools=tools)
call = r.choices[0].message.tool_calls[0]

msgs.append(r.choices[0].message)
msgs.append({"role": "tool", "tool_call_id": call.id, "content": "17"})

final = client.chat.completions.create(model="uncensored", messages=msgs, tools=tools)
print(final.choices[0].message.content)

In production, check that tool_calls exists before indexing it, since the model may choose to answer directly.

Rate limits, retries and your balance

A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60. When you pass a limit, the API answers HTTP 429. The error code is rate_limited for requests per minute and concurrency for too many at once. On a brief overload you also get a 429, with a Retry-After: 5 header.

import time
from openai import OpenAI, RateLimitError

client = OpenAI(base_url="https://api.nsfwgemini.cc/v1", api_key="YOUR_KEY", max_retries=0)

def call_with_retry(messages, tries=4):
    for attempt in range(tries):
        try:
            return client.chat.completions.create(model="uncensored", messages=messages)
        except RateLimitError:
            time.sleep(5 * (attempt + 1))
    raise RuntimeError("still rate limited after retries")

The SDK retries a couple of times by default; setting max_retries=0 here makes your own loop the only one, which is easier to reason about. If you fan out work with threads, cap the pool at 8 workers, or at 2 on a trial key.

To read response headers, use the raw-response wrapper:

raw = client.chat.completions.with_raw_response.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Say hello."}],
)
print(raw.headers.get("X-Request-Id"))
print(raw.headers.get("X-Balance-USD"))
print(raw.headers.get("X-RateLimit-Limit-Requests"))
completion = raw.parse()

X-Balance-USD shows what is left of your credit, which is handy for a script that should stop before it runs dry. Keep X-Request-Id when you contact support.

Async code and batches

For scripts that process many items, such as a folder of text files or a list of story prompts, the async client keeps the code short. The important part is to cap how many calls run together. A semaphore does that in a few lines:

import asyncio
from openai import AsyncOpenAI

client = AsyncOpenAI(base_url="https://api.nsfwgemini.cc/v1", api_key="YOUR_KEY")
gate = asyncio.Semaphore(6)

async def one(prompt):
    async with gate:
        r = await client.chat.completions.create(
            model="uncensored",
            messages=[{"role": "user", "content": prompt}],
            max_tokens=200,
        )
        return r.choices[0].message.content

async def main():
    prompts = [f"Write a one-line tagline for product number {i}." for i in range(30)]
    results = await asyncio.gather(*(one(p) for p in prompts))
    for text in results:
        print(text)

asyncio.run(main())

The semaphore is set to 6, which stays under the 8-request ceiling of a full key and leaves room for a second script. On a trial key, set it to 2. Without the gate, asyncio.gather would fire all 30 calls at once and most would come back as 429 errors with the code concurrency. Those failed calls are not charged, but they waste time and make the logs noisy.

Also watch the per-minute ceiling. A tight loop of short requests can pass 300 per minute on a full key (60 on a trial key) long before it hits the concurrency cap. If you see rate_limited errors, add a short sleep between batches instead of retrying harder.

Mistakes that waste an afternoon

  • Using Google's package name. Installing a Gemini library and pointing it at this URL fails, because the request format is different. Install openai.
  • A base URL without /v1. The SDK appends /chat/completions to whatever you give it. Leave the URL exactly as https://api.nsfwgemini.cc/v1.
  • Passing an old model name. Code copied from a tutorial often carries a model such as gpt-4o-mini or a Gemini name. This API has one model ID, uncensored.
  • Forgetting that history is resent. A chat that feels cheap on turn 3 costs far more on turn 80, because every call carries all earlier turns.
  • Parsing JSON without a guard. A truncated or malformed reply raises an exception. Catch it and retry once.
  • Expecting other modalities. The API is text only. There is no image generation, audio, embeddings or fine-tuning, so code that calls those endpoints will not work here.

A final habit: print resp.usage during development. The prompt and completion token counts show you what each call really costs, and they usually surprise people who guessed.

What it costs from Python

Billing counts tokens: $0.15 per 1M input and $0.50 per 1M output. A request with 2,000 tokens in and 500 out costs 2,000 x $0.15 / 1,000,000 = $0.0003 for input plus 500 x $0.50 / 1,000,000 = $0.00025 for output, so $0.00055 in total. The $0.50 trial credit covers about 909 such calls. A $20 top-up covers about 36,000.

Failed and refused requests are not charged, and credit does not expire. The full price table and bonus tiers (+5% from $50, +10% from $100, +15% from $200) are on the pricing page, and the docs list every supported parameter. Use the service for lawful adult use only; sexual content involving minors is blocked without exception.

Questions and answers

Do I need Google's SDK to use this?

No. This endpoint copies the OpenAI chat format, so the openai Python package is enough. You only change base_url, the key and the model name.

Which model name do I pass?

Pass uncensored as the model. GET /v1/models lists it if you want to confirm from code.

How do I handle a 429 error in Python?

Catch RateLimitError, wait a few seconds and retry. The error code tells you whether you passed requests per minute or concurrent requests.

Can I use async code?

Yes. Use AsyncOpenAI with the same base_url and key. Keep concurrent tasks at or below 8 on a full key, or 2 on a trial key.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.

Get API key