EN ▾
Get API key

NSFW Grok API in Python: Setup With the OpenAI SDK

Isometric terminal sending data streams through a pipe to an API server cube

The quickest nsfw grok api python setup is the official OpenAI SDK pointed at an independent, uncensored endpoint. You change two values and keep the rest of your code.

Updated

Key points

Mistral models include built-in content filters that may block lawful adult content, requiring workarounds.

Token costs for long-context Mistral usage can exceed those of flat-rate uncensored alternatives.

A single API key works across all Mistral endpoints, debunking the need for separate NSFW keys.

For pure text generation without refusals, a dedicated uncensored API often provides better value and reliability.

On this page

What you are connecting to

This is an independent API for one open-weight model that is tuned to answer without content refusals for lawful adult use. It is not xAI's Grok and it is not the official API of any vendor. The name people search for, nsfw grok, describes the behaviour they want, not the product behind it. If you need the official Grok models, use xAI's API.

The endpoint speaks the OpenAI chat completions protocol. Two methods exist: POST /v1/chat/completions and GET /v1/models. Authentication is a bearer token in the Authorization header. The model ID is uncensored, the context window is 100,000 tokens for prompt and completion together, and the service is text only. Because it follows the OpenAI shape, any client that lets you set a base URL will work, and Python's openai package is the usual choice.

You need a key first. Sign up with Google or with email and password, then open the API key page. A one-click $0.50 trial credit is available there, valid for 7 days, one per person and with no payment details required. It is plenty for everything in this article.

Install and send your first request

Create a virtual environment and install the SDK.

python -m venv .venv
source .venv/bin/activate
pip install openai
export NSFWGROK_KEY="paste-your-key-here"
curl -s https://api.nsfwgrok.top/v1/models -H "Authorization: Bearer $NSFWGROK_KEY"

That last command calls GET /v1/models and should list uncensored. If you get a 401, the key is wrong or missing. Now the Python call:

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.nsfwgrok.top/v1",
    api_key=os.environ["NSFWGROK_KEY"],
)

resp = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "You are a blunt, concise writing assistant."},
        {"role": "user", "content": "Give me three opening lines for a noir short story."},
    ],
    temperature=0.9,
    max_tokens=300,
)
print(resp.choices[0].message.content)

Keep the key in an environment variable, never in a repository. max_tokens is optional; leave it out and the completion can use whatever is left of the 100,000-token window. Setting it is still a good habit because it caps your worst-case bill on a runaway reply.

Stream the reply

For anything interactive, stream. Set stream=True and iterate over the chunks; the server sends them as server-sent events. The usage figures arrive at the end of the stream.

import os
from openai import OpenAI

client = OpenAI(base_url="https://api.nsfwgrok.top/v1", api_key=os.environ["NSFWGROK_KEY"])

stream = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Write a 120-word scene set in a rain-soaked port town."}],
    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)

One detail catches people out. A streamed request holds its concurrency slot until the stream ends. If your code opens a stream and abandons it without reading to the end or closing it, that slot stays busy and later calls can fail with a concurrency error. Always consume the stream or close it in a finally block.

Tool calling

Tool calling uses the standard tools and tool_choice parameters. When the model wants a tool, the reply has tool_calls; you run the function and send the result back as a message with role: "tool".

import json, os
from openai import OpenAI

client = OpenAI(base_url="https://api.nsfwgrok.top/v1", api_key=os.environ["NSFWGROK_KEY"])

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

messages = [{"role": "user", "content": "Roll 3 six-sided dice for my character."}]
first = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
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 = {"rolls": [4, 2, 6][: args["n"]]}  # replace with real logic
        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 check that msg.tool_calls exists, because the model may answer directly. Validate arguments before using them, since they are model output and can be malformed. Tool calls also work with streaming, where the call arrives in pieces you need to assemble.

JSON mode for structured output

When you need machine-readable output, pass response_format={"type": "json_object"}. Also tell the model in the prompt that you want JSON and describe the keys, because the mode constrains the format but not your schema.

import json, os
from openai import OpenAI

client = OpenAI(base_url="https://api.nsfwgrok.top/v1", api_key=os.environ["NSFWGROK_KEY"])

resp = client.chat.completions.create(
    model="uncensored",
    response_format={"type": "json_object"},
    messages=[
        {"role": "system", "content": "Reply only with JSON: {\"name\": str, \"traits\": [str], \"hook\": str}"},
        {"role": "user", "content": "Invent a tavern keeper for a fantasy campaign."},
    ],
    temperature=0.7,
)
data = json.loads(resp.choices[0].message.content)
print(data["name"], data["traits"])

Wrap json.loads in a try block anyway. If the output is cut off by max_tokens, the JSON will be incomplete, so give structured replies enough room. For repeatable outputs while you debug, pass seed along with a low temperature; sampling parameters such as temperature, top_p, stop, seed and the penalties are passed through to the model.

Rate limits, 429 errors and retries

A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60. Go over either and the API returns HTTP 429. The error code tells you which limit you hit: rate_limited means too many requests per minute, and concurrency means too many at once. On temporary overload you also get a 429, with a Retry-After: 5 header. Each response carries X-Request-Id, X-Balance-USD, X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency; quote the request ID if you contact support.

import asyncio, os
from openai import AsyncOpenAI, RateLimitError

client = AsyncOpenAI(base_url="https://api.nsfwgrok.top/v1", api_key=os.environ["NSFWGROK_KEY"], max_retries=0)
gate = asyncio.Semaphore(8)  # use 2 on a trial key

async def ask(prompt, tries=4):
    async with gate:
        for attempt in range(tries):
            try:
                r = await client.chat.completions.create(
                    model="uncensored",
                    messages=[{"role": "user", "content": prompt}],
                )
                return r.choices[0].message.content
            except RateLimitError as e:
                wait = float(e.response.headers.get("retry-after", 5))
                await asyncio.sleep(wait * (attempt + 1))
    raise RuntimeError("gave up after retries")

async def main():
    out = await asyncio.gather(*(ask(f"Give me idea number {i} for a short story.") for i in range(20)))
    print(len(out), "done")

asyncio.run(main())

The semaphore keeps you under the concurrency cap, and the retry honours Retry-After. Failed or refused requests are not charged, so retries do not cost you twice. Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens; the pricing page has worked costs, and the API docs cover every parameter.

Prompts are not used for training. The one hard content rule is that sexual content involving minors is never allowed, and requests like that will not be served.

Common errors and how to fix them

Most first-day problems come from a short list of causes. Work through it in order before assuming the service is down.

Log what you need to debug later

Keep the X-Request-Id from each response in your logs. The SDK exposes headers through with_raw_response, which returns the HTTP response next to the parsed object. That is also the easiest way to read X-Balance-USD after each call and warn yourself before credit runs out.

import os
from openai import OpenAI

client = OpenAI(base_url="https://api.nsfwgrok.top/v1", api_key=os.environ["NSFWGROK_KEY"])

raw = client.chat.completions.with_raw_response.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Say hello in five words."}],
)
print("request id:", raw.headers.get("x-request-id"))
print("balance usd:", raw.headers.get("x-balance-usd"))
print(raw.parse().choices[0].message.content)

With the request ID, balance and usage in one log line per call, you can answer almost any question about a failed or expensive request without guessing.

Questions and answers

Is this the official Grok API?

No. It is an independent OpenAI-compatible API for an open-weight model, not the official API of xAI or any other vendor. Use model ID uncensored.

Which Python package should I use?

The official openai package works. Set base_url to https://api.nsfwgrok.top/v1 and pass your key as api_key.

Does it support streaming and tool calling?

Yes. Streaming runs over SSE with stream=True, and tool calling follows the OpenAI tools format, with results sent back as role tool messages.

Why do I get a 429 error?

You hit a limit. The code rate_limited means too many requests per minute, concurrency means too many at once, and a Retry-After header of 5 means temporary overload.

Do I need to pay to test it?

No. New users can claim $0.50 of trial credit with one click after sign-up. It lasts 7 days, and the trial key allows 2 concurrent requests and 60 requests per minute.

Your key is one form away

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