EN ▾
Get API key
https://api.grokuncensored.top/v1uncensored

Grok Uncensored API in Python with the OpenAI SDK

This is a working grok uncensored api python setup using the standard OpenAI SDK. You change the base URL and the key, set the model to uncensored, and the rest of your code stays the same.

Updated

Glowing data-stream snake flowing from a terminal to a server, illustrating a Python API client

Setup in four steps

You need Python 3.9 or newer, an API key, and about five minutes. Get a key from the key page; new accounts can claim $0.50 of trial credit with one click and no payment details.

  1. Install the SDK: pip install openai
  2. Export your key: export API_KEY="your-key"
  3. Create a client with the base URL https://api.grokuncensored.top/v1
  4. Send a chat request with the model ID uncensored

First, to be clear about what you are calling: this service is an independent API running one open-weight model, tuned to answer without content refusals for lawful adult use. It is not the official API of xAI or any other vendor, and the name on this page is a search phrase, not a model name. The model ID is uncensored.

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.grokuncensored.top/v1",
    api_key=os.environ["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)

The usage object holds prompt and completion token counts, which you can multiply by the prices to track spend.

What to expect from the model

The SDK is only the transport. The behaviour you get comes from one open-weight model that is tuned to answer without content refusals for lawful adult use. In practice that means a request for dark fiction, a villain's monologue, or a companion character who stays in character will be answered instead of declined. It does not mean the model is more accurate than others. Treat facts it states with the same suspicion you would apply to any language model, and verify anything that matters.

Prompting works the way it does elsewhere. A clear system message sets the tone, the user message carries the task, and a lower temperature (around 0.2) suits extraction while a higher one (0.8 to 1.0) suits creative writing. The parameters temperature, top_p, stop, seed and the frequency and presence penalties are passed through to the model, so a fixed seed with a low temperature gives you much more repeatable output for tests.

Keep conversation state on your side. The API is stateless: each request must include the messages you want the model to see. A simple list that you append to after each turn is enough, and trimming the oldest turns when the list grows keeps both cost and latency under control. With a 100,000-token window you have a great deal of room, but the bill grows with every token you resend.

The body limit is 8 MB, and the context window is 100,000 tokens for prompt plus completion together. The service is text only: no images, audio, video, embeddings or fine-tuning. Parameters such as temperature, top_p, stop, seed and the penalties are passed through to the model. Prompts are not used for training.

The model is tuned to answer without content refusals for lawful adult use, which suits fiction tools, roleplay and companion apps for adults. It will not produce sexual content involving minors, and no setting changes that. Where your app serves the public, put your own age checks and moderation in front of it. The full parameter reference is in the API docs.

Streaming responses

For chat interfaces you want tokens as they arrive. Set stream=True and iterate over the chunks. The service sends Server-Sent Events and includes 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)
    if getattr(chunk, "usage", None):
        print("\n", chunk.usage)

Two details are easy to miss. The last chunk may carry usage and an empty choices list, which is why the loop checks chunk.choices before indexing it. And a streamed request holds its concurrency slot until the stream ends, so a client that opens a stream and never reads it will block one of your eight slots (two on a trial key). Always consume the stream or close it.

Common errors and what they mean

Most problems in a first Python session fall into a few groups. Reading the error class from the SDK usually tells you which.

  • Authentication error. The key is missing, mistyped or sent without the Bearer scheme. The SDK adds the scheme for you, so the usual cause is an empty environment variable. Print bool(os.environ.get("API_KEY")) to check.
  • Connection error or timeout. The base URL is wrong, often because it lacks /v1 or has a trailing path. Compare it with https://api.grokuncensored.top/v1 character by character.
  • Not found for the model. You used a model string other than uncensored. Call client.models.list() and copy the ID.
  • 429 errors. You hit the per-minute limit or the concurrency limit. The error code tells you which; the earlier section shows how to cap parallelism.
  • Request too large. The body limit is 8 MB, and the context window is 100,000 tokens. Large pasted documents can exceed the second long before the first, so count or estimate tokens before you send.

When you contact support, include the X-Request-Id value from the failing response and the approximate time. That is the quickest way to find a single request among many. The pricing page and the documentation both link to the support page for contact details.

One more habit pays off: log the usage object of every call during development. If a prompt costs ten times what you expected, you will see it in the first test run rather than on a balance check a week later.

Responses carry headers you can read through the SDK's raw-response wrapper: X-Request-Id (quote it to support), X-Balance-USD, X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency.

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

To estimate cost from usage, use $0.15 per 1M input tokens and $0.50 per 1M output tokens. A call with 1,200 prompt tokens and 400 completion tokens costs 1,200 x 0.15 / 1,000,000 = $0.00018 for input plus 400 x 0.50 / 1,000,000 = $0.0002 for output, so $0.00038 in total. Failed or refused requests are not charged. The pricing page explains top-ups, which are crypto only on this site.

JSON mode for structured output

When you need machine-readable output, ask for a JSON object with response_format. Also tell the model in the prompt that you want JSON and describe the keys; the flag enforces valid syntax, but your prompt decides the shape.

import json

resp = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "Reply with a JSON object with keys title and tags (a list of strings)."},
        {"role": "user", "content": "Suggest a title and tags for a post about home espresso."},
    ],
    response_format={"type": "json_object"},
    temperature=0.2,
)

data = json.loads(resp.choices[0].message.content)
print(data["title"], data["tags"])

Still wrap json.loads in a try block in production. If a completion is cut off by max_tokens, the JSON will be incomplete. Leaving max_tokens unset lets the completion use the rest of the 100,000-token window, which avoids truncation at the cost of letting a runaway answer run long.

Tool calling

Tool calling uses the same schema as the OpenAI API: declare functions in tools, optionally force a choice with tool_choice, run the function yourself, then send the result back as a message with role: "tool".

import json

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"
)

msg = first.choices[0].message
if msg.tool_calls:
    call = msg.tool_calls[0]
    args = json.loads(call.function.arguments)
    result = {"city": args["city"], "temp_c": 19}  # your real lookup goes here
    messages.append(msg)
    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)

The weather value above is a stand-in for your own code. Validate the arguments the model produces before you act on them, especially when a tool can write data or spend money. Streamed requests also return tool_calls, delivered in pieces, so accumulate the argument fragments by index before parsing.

Rate limits, retries and concurrency

A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60. Past a limit you get HTTP 429 with the error code rate_limited (too many requests per minute) or concurrency (too many at once). On temporary overload the API also returns 429 with a Retry-After: 5 header. The SDK has built-in retries, which you can tune:

client = OpenAI(
    base_url="https://api.grokuncensored.top/v1",
    api_key=os.environ["API_KEY"],
    max_retries=4,
    timeout=120,
)

For batch jobs, cap parallelism at your key's concurrency instead of relying on retries. A semaphore does it cleanly:

import asyncio
from openai import AsyncOpenAI

aclient = AsyncOpenAI(base_url="https://api.grokuncensored.top/v1", api_key=os.environ["API_KEY"])
sem = asyncio.Semaphore(8)  # use 2 on a trial key

async def ask(prompt):
    async with sem:
        r = await aclient.chat.completions.create(
            model="uncensored",
            messages=[{"role": "user", "content": prompt}],
        )
        return r.choices[0].message.content

async def main():
    prompts = [f"Give one fact about the number {i}." for i in range(20)]
    answers = await asyncio.gather(*(ask(p) for p in prompts))
    for a in answers:
        print(a)

asyncio.run(main())

If you see concurrency errors with a pool that looks correctly sized, check for streams you have not finished reading, since each one still holds a slot.

A minimal chat loop to build from

Putting it together, here is a small terminal chat that streams answers, keeps history, and trims it when it gets long. It is a starting point for a bot, a writing tool or a character app.

import os
from openai import OpenAI

client = OpenAI(base_url="https://api.grokuncensored.top/v1", api_key=os.environ["API_KEY"])
history = [{"role": "system", "content": "You are a vivid storyteller. Keep replies under 150 words."}]

while True:
    user = input("you> ").strip()
    if not user:
        break
    history.append({"role": "user", "content": user})
    stream = client.chat.completions.create(
        model="uncensored", messages=history, stream=True, temperature=0.9
    )
    parts = []
    for chunk in stream:
        if chunk.choices and chunk.choices[0].delta.content:
            piece = chunk.choices[0].delta.content
            parts.append(piece)
            print(piece, end="", flush=True)
    print()
    history.append({"role": "assistant", "content": "".join(parts)})
    if len(history) > 41:
        history = history[:1] + history[-40:]

The trim keeps the system message and the last 40 turns. For a longer memory, summarise the dropped turns into one message instead of dropping them. If you later add a web front end, keep the API key on your server and never ship it to the browser. For a first read-through of the available fields, the documentation is short, and the integration notes on common mistakes cover problems that show up after the first working request.

Questions and answers

Do I need a special SDK?

No. The standard openai Python package works. Set base_url to the endpoint, use your key, and set the model to uncensored.

Does streaming work from Python?

Yes. Pass stream=True and iterate over the chunks. Usage is included at the end of the stream.

Is this the official Grok API?

No. It is an independent service running one open-weight model, and it is not the official API of xAI or any other vendor.

How do I avoid 429 errors?

Keep parallel requests at or below 8 on a full key or 2 on a trial key, finish reading every stream, and retry with a short delay when you receive Retry-After.

Your key is one form away

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

Get API key