EN ▾
Get API key

Grok API Python: Call an OpenAI-Compatible API

Searching for a grok api python example usually ends at the same answer: install the openai package, point it at a different base URL and send chat requests. This tutorial does exactly that against an independent OpenAI-compatible endpoint serving the model ID uncensored, and it is not the official xAI API.

Updated

Terminal-like window with streams of light and a circuit-trace snake, representing Python API calls

Key points

  • Install openai, set base_url to https://api.grokapi.cc/v1 and use model uncensored.
  • Streaming, JSON mode and tool calling work with the standard SDK arguments.
  • On HTTP 429 read the error code: rate_limited means too many per minute, concurrency means too many at once.
  • A funded key allows 8 concurrent requests, a trial key allows 2, so size your thread pool to match.

Setup in two minutes

You need Python 3.8 or newer and an API key. Create the key on the API key page. New accounts can claim $0.50 of trial credit with one click after sign-up, which is enough for everything in this tutorial. Then install the package with pip install openai.

Keep the key out of your source. Export it as an environment variable and read it in code:

export GROKAPI_KEY="paste-your-key-here"
# quick check that the key and URL work, before writing any Python
curl https://api.grokapi.cc/v1/models -H "Authorization: Bearer $GROKAPI_KEY"
# and one tiny chat call
curl https://api.grokapi.cc/v1/chat/completions -H "Authorization: Bearer $GROKAPI_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "uncensored", "messages": [{"role": "user", "content": "ping"}], "max_tokens": 5}'

The call to /v1/models returns the model list, which should include uncensored. If it fails with 401, the key is wrong or the header is missing the word Bearer. The key troubleshooting page lists other usual causes.

Your first request

The SDK needs three things: base URL, key and model. Everything else is the regular OpenAI client interface.

import os
from openai import OpenAI

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

resp = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "You are a concise writing assistant."},
        {"role": "user", "content": "Give me three names for a ship in a space western."},
    ],
    temperature=0.9,
)

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

The last line prints token counts. At $0.15 per 1M input tokens and $0.50 per 1M output tokens, a request with 40 tokens in and 120 out costs 40 / 1,000,000 x $0.15 + 120 / 1,000,000 x $0.50 = $0.000006 + $0.00006 = $0.000066. You can follow the pricing details on the pricing page.

The max_tokens argument is optional. If you leave it out, the completion can use whatever is left of the 100,000-token window after your prompt, so set it when you want a hard cap on reply length and cost.

Streaming responses

For chat interfaces you want tokens as they arrive. Pass stream=True and iterate over the chunks. The API sends server-sent events and reports usage at the end.

import os
from openai import OpenAI

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

stream = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Write a four-line poem about a night train."}],
    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[tokens]", chunk.usage.prompt_tokens, chunk.usage.completion_tokens)

Two details matter. The last chunk can have an empty choices list, so check it before indexing. And a streamed request holds one of your concurrency slots until the stream finishes or you close it, so break out and close the stream if the user navigates away.

Multi-turn chat and sampling settings

The API is stateless. To continue a conversation you send the whole history each time, so keep a list and append to it.

import os
from openai import OpenAI

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

history = [{"role": "system", "content": "You are a dungeon master for a text adventure."}]

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

print(say("I push open the door of the abandoned lighthouse."))
print(say("I light my lantern and climb the stairs."))

The sampling arguments, including temperature, top_p, stop, seed and the penalties, are passed through to the model. A fixed seed helps when you are comparing prompts, though identical output is not something to depend on in production.

History grows input cost with every turn. A 30-turn session of about 400 tokens per turn adds up to around 198,000 input tokens in total, roughly three cents. Trim old turns once the list gets long.

JSON mode and tool calling

When you need machine-readable output, turn on JSON mode and say in the prompt that you want JSON.

import os, json
from openai import OpenAI

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

r = client.chat.completions.create(
    model="uncensored",
    response_format={"type": "json_object"},
    messages=[
        {"role": "system", "content": "Reply with a JSON object with keys title and tags (a list)."},
        {"role": "user", "content": "Describe a heist story set on a moon base."},
    ],
)
data = json.loads(r.choices[0].message.content)
print(data["title"], data["tags"])

Tool calling follows the standard loop: send the tool schema, run the function the model asks for, send the result back as a tool message.

import os, json
from openai import OpenAI

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

tools = [{
    "type": "function",
    "function": {
        "name": "roll_dice",
        "description": "Roll a number of six-sided dice",
        "parameters": {
            "type": "object",
            "properties": {"count": {"type": "integer"}},
            "required": ["count"],
        },
    },
}]

messages = [{"role": "user", "content": "Roll three dice for my attack."}]
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 = {"rolls": [4, 2, 6][: args["count"]]}  # stand-in for real code
        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 msg.tool_calls before using it, since the model may answer directly. Validate parsed arguments before running real code with them, because model output is still untrusted input.

Handling 429 errors and limits

Rate limits are the most common surprise. A funded key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 concurrent and 60 per minute. Over the limit you get HTTP 429, and the error code tells you which limit you hit: rate_limited for requests per minute, concurrency for too many at once. Temporary overload also returns 429, with a Retry-After: 5 header.

The SDK retries some errors on its own, and you can raise the count when you create the client. For control over what happens next, catch the exception:

import os, time
from openai import OpenAI, RateLimitError

client = OpenAI(
    base_url="https://api.grokapi.cc/v1",
    api_key=os.environ["GROKAPI_KEY"],
    max_retries=0,  # we handle retries ourselves below
)

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

print(ask("Name one famous lighthouse."))

Using with_raw_response also gives you the response headers: X-Balance-USD for your remaining balance, X-Request-Id to quote to support, and X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency for the limits on your key. Failed or refused requests are not charged, so retrying costs nothing until one succeeds.

Running requests in parallel

To process a list of prompts faster, use threads, but cap them at your key's concurrency. Eight workers is the ceiling on a funded key, and two on a trial key.

import os
from concurrent.futures import ThreadPoolExecutor
from openai import OpenAI

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

def summarize(text):
    r = client.chat.completions.create(
        model="uncensored",
        messages=[{"role": "user", "content": "Summarize in one sentence: " + text}],
        max_tokens=80,
    )
    return r.choices[0].message.content

docs = ["First document text...", "Second document text...", "Third document text..."]

with ThreadPoolExecutor(max_workers=8) as pool:  # use 2 on a trial key
    for out in pool.map(summarize, docs):
        print(out)

The same limit applies to the async client. If you use AsyncOpenAI, wrap calls in an asyncio.Semaphore(8). For a sense of what a batch costs, 5,000 documents at 3,000 tokens in and 300 out come to $2.25 for input plus $0.75 for output, $3.00 in total.

The request body is capped at 8 MB, which is far above any prompt that fits the 100,000-token window, but worth knowing if you embed large files as text. For other settings see the docs.

Common errors and cost logging

Most failures in a first Python integration come from a short list of causes. Work through it in order before you suspect the service.

  • 401 Unauthorized. The key is missing, truncated or sent without Bearer. Print the first six characters of os.environ["GROKAPI_KEY"] to confirm the variable is set in the shell that runs Python, since an IDE often starts with a different environment.
  • 404 or a connection error. The base URL is wrong. It must end in /v1 and must not include /chat/completions, because the SDK adds that path itself.
  • Model not found. You left a model name from another provider in the code. The only ID here is uncensored.
  • Timeouts on long replies. A reply that runs for thousands of tokens takes real time. Raise the client timeout, for example OpenAI(..., timeout=120), or stream the answer so the first token shows up quickly.
  • Body-size error. The request body is limited to 8 MB. Trim the payload or split the job.
  • Empty or cut-off reply. Check finish_reason. A value of length means the completion hit your max_tokens cap or the end of the window.

When you open a support request, include the X-Request-Id value from the failed response. It lets the operator find that exact call. The support page has the contact details.

Keeping a cost log in your own code

Because each response reports its token counts, a few lines of Python give you a per-call cost record. That is more useful than checking the balance by hand, and it catches runaway prompts early.

import os
from openai import OpenAI

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

IN_RATE = 0.15 / 1_000_000   # dollars per input token
OUT_RATE = 0.50 / 1_000_000  # dollars per output token

def cost(usage):
    return usage.prompt_tokens * IN_RATE + usage.completion_tokens * OUT_RATE

r = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Explain what a context window is in two sentences."}],
)
print(f"${cost(r.usage):.6f}")

For a request with 1,500 tokens in and 400 out, this prints 1,500 x 0.15 / 1,000,000 + 400 x 0.50 / 1,000,000 = $0.000225 + $0.0002 = $0.000425. Store the number with a user ID or a feature name and you can see which part of your app spends the most. Top-ups and the bonus tiers are explained on the pricing page linked above, and since credit never expires there is no rush to fund more than you need.

One last habit: keep the model ID and base URL in a single config module. If you later route some traffic to a different provider, the change is one file, not a search across the project.

Questions and answers

Which Python package should I use?

The official openai package. Create the client with base_url set to https://api.grokapi.cc/v1 and your key, then use model uncensored.

Does it work with requests or httpx instead of the SDK?

Yes. Send a POST to /v1/chat/completions with an Authorization Bearer header and a JSON body containing model and messages.

Why do I get a 429 error?

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

How do I see how many tokens a request used?

Read resp.usage on a normal response, or ask for usage in the final chunk of a stream. The X-Balance-USD header shows your remaining balance.

Is the model the same as xAI's Grok?

No. It is an independent open-weight model served through an OpenAI-compatible API and is not an xAI product.

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.