EN ▾
Get API key

LLM API Python Example With the OpenAI SDK

You can call this API from Python with the standard openai package. Change the base URL and the key, set the model to uncensored, and the rest of your code stays the same.

Updated

Isometric illustration of data flowing through a pipe into a server cube, representing a Python API call

Key points

  • Install openai, set base_url to https://api.gemininsfw.cc/v1 and use the model ID uncensored.
  • Streaming, tool calling and JSON mode work through the same SDK calls you already know.
  • Retry on HTTP 429 and read the Retry-After header; a stream holds a concurrency slot until it ends.
  • Cost per call is easy to compute: $0.15 per 1M input tokens, $0.50 per 1M output tokens.

The short answer: a working Python call

If you searched for an llm api python example, here is the whole thing. Install the SDK, export your key, and run the script. The endpoint speaks the OpenAI chat completions format, so no special client is needed.

pip install openai
export API_KEY="your-key-here"
import os
from openai import OpenAI

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

resp = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "You are a concise assistant."},
        {"role": "user", "content": "Explain what a context window is in two sentences."},
    ],
    temperature=0.7,
)

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

The model ID is uncensored. Auth is a standard Authorization: Bearer header, which the SDK builds from api_key. If you do not have a key yet, the API key page walks you through sign-up and the trial credit.

Check the connection first

Before writing application code, confirm that the key and URL are right. The API exposes GET /v1/models, and the SDK wraps it:

for m in client.models.list():
    print(m.id)

You should see uncensored in the output. The same check with curl:

curl https://api.gemininsfw.cc/v1/models \
  -H "Authorization: Bearer $API_KEY"

A 401 means the key is wrong or missing. A connection error usually means the base URL is missing the /v1 suffix or has a typo. These two problems cover most first-run failures.

Every response carries headers worth logging: X-Request-Id for support questions, X-Balance-USD for your remaining credit, and the two X-RateLimit-Limit-* headers for your limits. With the SDK, use with_raw_response to see them:

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

Streaming replies

For chat interfaces you want tokens as they arrive. Set stream=True and iterate. The server sends 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 servers."}],
    stream=True,
)

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

One detail matters for concurrency: a streamed request occupies its slot until the stream ends. If you open a stream and stop reading it, the slot stays busy. Always consume the stream or close it in a finally block.

JSON mode and tool calling

Two features make the API useful for backends rather than just chat boxes.

JSON mode

Pass response_format={"type": "json_object"} and say in the prompt that you want JSON. Then parse the result:

import json

resp = 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 me a character with keys name, age, trait."},
    ],
)
data = json.loads(resp.choices[0].message.content)
print(data)

Still wrap json.loads in a try block. A long answer cut off by a low max_tokens can produce invalid JSON.

Tool calling

Define tools with the usual schema, check tool_calls on the reply, run your function, and send the result back as a message with role: "tool".

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get the current weather for a city",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    },
}]

messages = [{"role": "user", "content": "Weather in Lisbon?"}]
first = client.chat.completions.create(
    model="uncensored", messages=messages, tools=tools, tool_choice="auto"
)
msg = first.choices[0].message

if msg.tool_calls:
    call = msg.tool_calls[0]
    messages.append(msg)
    messages.append({
        "role": "tool",
        "tool_call_id": call.id,
        "content": '{"temp_c": 21, "sky": "clear"}',
    })
    final = client.chat.completions.create(
        model="uncensored", messages=messages, tools=tools
    )
    print(final.choices[0].message.content)

Handling 429 errors and retries

A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 concurrent and 60 per minute. Past either limit you get HTTP 429, and the error code tells you which one: rate_limited means too many requests per minute, concurrency means too many at once. On temporary overload the API also answers 429 with Retry-After: 5.

The OpenAI SDK retries a couple of times on its own. For batch jobs, add your own limit on parallel work so you stay under the concurrency cap:

import time
from concurrent.futures import ThreadPoolExecutor
from openai import RateLimitError

def ask(prompt):
    for attempt in range(5):
        try:
            r = client.chat.completions.create(
                model="uncensored",
                messages=[{"role": "user", "content": prompt}],
            )
            return r.choices[0].message.content
        except RateLimitError as e:
            wait = int(e.response.headers.get("Retry-After", 5))
            time.sleep(wait * (attempt + 1))
    raise RuntimeError("still rate limited")

prompts = [f"Summarize topic {i} in one line." for i in range(40)]
with ThreadPoolExecutor(max_workers=6) as pool:
    results = list(pool.map(ask, prompts))

Six workers sit under the limit of 8 with room for other traffic. The body limit is 8 MB, which only matters if you paste very large documents; the context window is 100,000 tokens for prompt plus completion.

What a call costs

Billing is per token from prepaid credit: $0.15 per 1M input tokens and $0.50 per 1M output tokens. Read resp.usage and compute the cost in your own code:

def cost_usd(usage):
    return usage.prompt_tokens * 0.15 / 1_000_000 + usage.completion_tokens * 0.50 / 1_000_000

print(round(cost_usd(resp.usage), 6))

A worked example: a call with 2,000 input tokens and 500 output tokens costs 2,000 x $0.15 / 1M = $0.0003 for input, plus 500 x $0.50 / 1M = $0.00025 for output, so $0.00055 in total. Failed or refused requests are not charged. The pricing page has the top-up amounts and bonuses, and credit does not expire.

Keeping conversation history

The API is stateless: it does not remember earlier calls. To hold a conversation, keep a list of messages and send the whole list each time. Append the assistant reply after every turn.

history = [{"role": "system", "content": "You are a helpful storyteller."}]

def say(text):
    history.append({"role": "user", "content": text})
    r = client.chat.completions.create(model="uncensored", messages=history)
    reply = r.choices[0].message.content
    history.append({"role": "assistant", "content": reply})
    return reply

print(say("Start a story about a clockmaker."))
print(say("Continue, and add a stranger at the door."))

Input tokens grow with every turn, because the full history is billed as input each time. The window is 100,000 tokens for prompt plus completion, which is a lot, but long chats also cost more per call. A simple fix is to keep the system prompt and the last N turns, or to ask the model to summarize older turns into one short message. The seed parameter, together with a fixed temperature, helps when you want repeatable outputs while testing.

Where to go next

Once the basic call works, put the key in an environment variable or a secrets manager and keep it out of your repository. The docs cover the request format in more detail. If you are comparing models behind other OpenAI-style endpoints, the GLM API guide shows how a similar setup looks there. Remember that this service is text only: no images, audio, embeddings or fine-tuning.

Questions and answers

Do I need a special Python library?

No. The official openai package works. Set base_url to https://api.gemininsfw.cc/v1 and the model to uncensored.

Can I use the async client?

Yes. AsyncOpenAI takes the same base_url and api_key arguments. Keep your number of simultaneous tasks under the concurrency limit of your key.

Why do I get a 429 even though I send few requests?

Check the error code. If it is concurrency, you have too many requests open at once, and unfinished streams count. If the response has Retry-After: 5, the service is briefly overloaded and a retry after five seconds is the right move.

Can I try it before paying?

New users can claim $0.50 of trial credit with one click on the API key page after sign-up. It is valid for 7 days and limited to 2 concurrent requests and 60 per minute.

Your key is one form away

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

Get API keyRead the docs