EN ▾
Get API key

Grokunfiltered API in Python: Working Examples

Using the grokunfiltered api python style of access takes about ten lines: install the official openai package, point it at our base URL, and set the model to uncensored. This page walks from the first request to streaming, tools, JSON mode and rate limit handling.

Updated

Key points

  • Install openai, set base_url to https://api.grokunfiltered.cc/v1 and use the model ID uncensored.
  • Streaming, tool calling and JSON mode work through the standard SDK arguments.
  • Handle HTTP 429 with the Retry-After header and cap yourself at 8 concurrent requests.
  • This is an independent API for a single open-weight model, not the official xAI Grok API.
Stream of data cubes flowing from a terminal into a server, illustrating a Python API call

What you need before the first call

The grokunfiltered api python workflow needs three things: Python 3.8 or newer, the openai package, and an API key. The API follows the OpenAI chat format, so there is no separate client library to learn. If you already have code written for the OpenAI SDK, you change the base URL, the key and the model name, and the rest stays as it is.

A quick note on naming. This service is an independent provider that runs one open-weight model tuned to answer without content refusals for lawful adult use. It is not the official API of xAI or of any other vendor, and it does not route between vendors. There is a single model ID, uncensored, and two endpoints: POST /v1/chat/completions and GET /v1/models. If you are coming from another provider, the quickstart in the docs covers the migration checklist.

To get a key, sign up with Google or with email and password, then open the API key page. New accounts can claim $0.50 of trial credit with one click, valid for 7 days and needs no payment. The steps are on the API key page. Install the SDK:

python -m venv .venv
source .venv/bin/activate
pip install openai

Keep the key out of your source files. Export it as an environment variable and read it with os.environ:

export GROKUNFILTERED_API_KEY="paste-your-key-here"

A first chat completion

This is the smallest useful script. It sends one question and prints the answer plus the token counts the API reports back.

import os
from openai import OpenAI

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

resp = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "You are a direct, 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.prompt_tokens, resp.usage.completion_tokens)

Two things to check if it fails. A 401 means the key is wrong or the header is missing; the SDK sends it as Authorization: Bearer for you. A 404 usually means the base URL lost its /v1 suffix. You can confirm both at once by listing models:

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

You should see uncensored in the output. Sampling arguments such as temperature, top_p, stop, seed and the frequency and presence penalties are passed through to the model, so you can use the values you already tuned elsewhere.

Streaming tokens as they arrive

For chat interfaces and long answers, stream the response. Set stream=True and iterate over the chunks. The service sends server-sent events, and the SDK turns them into Python objects.

import os
from openai import OpenAI

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

stream = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Write a 150-word scene opening for a noir story."}],
    stream=True,
)

usage = None
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):
        usage = chunk.usage

print()
if usage:
    print("tokens in/out:", usage.prompt_tokens, usage.completion_tokens)

Usage numbers arrive at the end of the stream, so keep the last chunk that carries them instead of reading usage from the first chunk. The guard on chunk.choices matters because the final usage chunk may have an empty choices list.

One operational detail: a streamed request holds its concurrency slot until the stream finishes. If you open a stream and walk away without reading it to the end, that slot stays busy. Close streams you abandon, for example with a with block or by calling stream.close().

Tool calling and JSON mode

Tool calling follows the OpenAI shape: you describe functions in tools, the model may answer with tool_calls, you run the function and send the result back as a message with role: "tool". Here is a full round trip with a stubbed function.

import json, os
from openai import OpenAI

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

tools = [{
    "type": "function",
    "function": {
        "name": "get_order_status",
        "description": "Look up the status of an order by its numeric ID.",
        "parameters": {
            "type": "object",
            "properties": {"order_id": {"type": "integer"}},
            "required": ["order_id"],
        },
    },
}]

messages = [{"role": "user", "content": "Where is order 4812?"}]
first = client.chat.completions.create(
    model="uncensored", messages=messages, tools=tools, tool_choice="auto"
)

msg = first.choices[0].message
if msg.tool_calls:
    messages.append(msg)
    for call in msg.tool_calls:
        args = json.loads(call.function.arguments)
        result = {"order_id": args["order_id"], "status": "shipped"}  # your real lookup here
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": json.dumps(result),
        })
    final = client.chat.completions.create(
        model="uncensored", messages=messages, tools=tools
    )
    print(final.choices[0].message.content)
else:
    print(msg.content)

Always parse arguments defensively. It arrives as a JSON string, and a model can occasionally produce something that fails to parse. Wrap json.loads in a try block and, on failure, send an error message back as the tool result so the model can retry.

For structured output without tools, use JSON mode:

resp = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "Reply with a JSON object with keys title and tags (a list)."},
        {"role": "user", "content": "Summarize: a lighthouse keeper finds a message in a bottle."},
    ],
    response_format={"type": "json_object"},
)
data = json.loads(resp.choices[0].message.content)
print(data)

Say the word JSON in your prompt and name the keys you expect. JSON mode keeps the output syntactically valid; it does not guarantee your exact schema, so validate the fields you depend on.

Rate limits, 429s and retries

A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 concurrent and 60 per minute. When you go over, the API answers HTTP 429. The error code tells you which limit you hit: rate_limited for requests per minute, concurrency for too many requests at once. A temporary overload also returns 429, with a Retry-After: 5 header.

The OpenAI SDK retries a couple of times on its own, but explicit handling gives you control. This wrapper reads the header, waits, and also exposes the response headers so you can watch your balance:

import os, time
from openai import OpenAI, RateLimitError

client = OpenAI(
    base_url="https://api.grokunfiltered.cc/v1",
    api_key=os.environ["GROKUNFILTERED_API_KEY"],
    max_retries=0,
)

def ask(prompt, tries=5):
    for attempt in range(tries):
        try:
            raw = client.chat.completions.with_raw_response.create(
                model="uncensored",
                messages=[{"role": "user", "content": prompt}],
            )
            print("balance USD:", raw.headers.get("X-Balance-USD"))
            return raw.parse().choices[0].message.content
        except RateLimitError as e:
            wait = float(e.response.headers.get("Retry-After", 2 ** attempt))
            time.sleep(wait)
    raise RuntimeError("still rate limited after retries")

print(ask("Give me three names for a fantasy tavern."))

Responses also carry X-Request-Id, X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency. Log the request ID with every failure; it is the first thing support will ask for on the support page.

Keeping conversation state and trimming history

The API is stateless. It does not remember earlier requests, so a chat is just a list of messages that you grow and resend. In Python that means a plain list. Append the user message, call the API, append the assistant reply, repeat.

import os
from openai import OpenAI

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

history = [{"role": "system", "content": "You are a patient writing coach."}]

def say(text, keep_last=20):
    history.append({"role": "user", "content": text})
    # keep the system message plus the most recent turns
    window = [history[0]] + history[1:][-keep_last:]
    r = client.chat.completions.create(model="uncensored", messages=window)
    reply = r.choices[0].message.content
    history.append({"role": "assistant", "content": reply})
    return reply

print(say("Give me a writing prompt about a ferry at night."))
print(say("Now make it stranger."))

The window slice is a blunt but effective tool. Input tokens are billed on every call, so a chat that sends its whole history each time gets more expensive with each turn, even when the new message is one line. Cutting to the last 20 messages keeps both cost and latency steady. If the early part of the conversation matters, replace it with a short summary stored in the system message instead of dropping it.

Token counts from the usage block make trimming smarter. Instead of a fixed number of messages, you can keep adding turns until the last reported prompt_tokens passes a budget you choose, say 30,000, and only then start dropping the oldest ones. That keeps short chats whole and long chats affordable, and it leaves plenty of room under the 100,000-token window for the reply.

The same list works for the streaming example earlier: collect the streamed pieces into one string, then append it as the assistant message when the loop ends.

Running many requests in parallel

If you process a batch, do not fire everything at once. Eight concurrent requests is the ceiling, so cap your own concurrency a little below it and let a semaphore do the queuing. This avoids concurrency errors entirely.

import asyncio, os
from openai import AsyncOpenAI

client = AsyncOpenAI(
    base_url="https://api.grokunfiltered.cc/v1",
    api_key=os.environ["GROKUNFILTERED_API_KEY"],
)
sem = asyncio.Semaphore(6)

async def one(prompt):
    async with sem:
        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())

Six workers with a typical two-second answer stay well under 300 requests per minute. If your calls are shorter, the per-minute limit becomes the one to watch, so add a small sleep or a token bucket.

Keep the budget in mind too. The price is $0.15 per 1M input tokens and $0.50 per 1M output tokens, billed from prepaid credit, and failed or refused requests are not charged. The pricing page has the details, and a batch of 30 short calls like the one above costs a small fraction of a cent.

Pitfalls worth checking first

  • Context size. Prompt plus completion must fit in 100,000 tokens. Long chat histories grow quietly; trim old turns or summarize them before you hit the limit.
  • Body size. The maximum request body is 8 MB. Large pasted documents can exceed it before they exceed the token window.
  • Text only. There is no image, audio or video generation, no embeddings and no fine-tuning. Do not point an embeddings call at this base URL.
  • Content rule. The model is tuned to skip refusals for lawful adult use, but sexual content involving minors is a hard limit and is never allowed.
  • Privacy. Prompts are not used for training. The privacy page describes what is kept.

Once the basics work, move the client construction into one module, read the key from the environment, and reuse that client across your app. That is all the integration this API needs.

Questions and answers

Do I need a special Python library?

No. The official openai package works. Set base_url to https://api.grokunfiltered.cc/v1, pass your key, and use the model ID uncensored.

Is this the official xAI Grok API?

No. It is an independent API that runs one open-weight model tuned to answer without content refusals for lawful adult use. It is not operated by xAI or any other model vendor.

Does streaming work with the Python SDK?

Yes. Pass stream=True and iterate over the chunks. Usage counts are sent at the end of the stream, and the request holds a concurrency slot until the stream finishes.

How do I pay for usage?

You top up prepaid credit with crypto (USDT on TRC20 or USDC on Base), from $20 to $500. New users can first try the $0.50 trial credit, which is valid for 7 days.

Your key is one form away

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

Start with trial credit

Email and password, key on screen right away.