Skip to content
Gustavo Peixoto

Dec 6, 202617 min read

Without an API key from the xAI Console, "Grok CLI", a terminal client that talks to xAI's API, does nothing.

As of 6 Dec 2026, the install line and the key's variable name both come from xAI's docs, not from this article, much as anyone wiring that key into an Activepieces flow would copy the variable name from the provider's own documentation.

Grok CLI setup is the process of installing xAI's terminal client, creating an API key in the xAI Console, and configuring it so the client can send requests to xAI's API, where per-token pricing, tier-based rate limits and error responses determine how it behaves in use.

Grok CLI Install and API Key Setup

What the CLI is, and which tool the name refers to

More than one tool goes by this name. xAI documents its own command-line tooling, and open-source projects also call themselves a Grok CLI.

They have different publishers, different install sources and different config files. A command copied from a blog post can install the wrong one without a single error.

Before you run anything, confirm the publisher on the page you got the command from. If it isn't xAI's docs or xAI's own repository, treat it as third-party code that will hold your key.

A command copied from a blog post can install the wrong one without a single error.

Install on macOS, Linux and Windows

I'm not reproducing install lines from memory, because a stale one is worse than none. Open xAI's CLI documentation and copy the command for your platform. Windows and Unix shells often get different instructions there.

Pin the version while you're at it. Any registry install is defined by two facts:

  • a name
  • a version

If you leave the version unpinned, your CI run next month may not match your laptop today.

  1. Sign in to the xAI Console and open its API keys page.
  2. Create a new key and copy it immediately. Consoles generally show a secret once, so assume it can't be retrieved later.
  3. Give the key its own name per machine or pipeline, so you can revoke one without breaking the rest.
  4. Export it as XAI_API_KEY and launch the CLI.

On macOS and Linux:

export XAI_API_KEY="your-key"

In Windows PowerShell:

$env:XAI_API_KEY = "your-key"

When the first request comes back 401, it usually has one of three causes. A stale shell never saw the export, the pasted key has a stray quote or trailing space, or the key was revoked in the Console. Check those before you reinstall anything.

A key with a tiny speck on its tooth beside a clean key on a hook

Grok CLI config file and XAI_API_KEY variable

Rely on XAI_API_KEY; it is the one variable to count on. Anything beyond it, such as a default model, an alternate base URL or a settings file location, depends on which tool you installed, so read that tool's own docs for its exact names.

Keep the key out of the config file, since config files get committed and environment variables don't.

In a scheduled job or CI, store the key in the platform's secret store and inject it at run time. A key pasted into a repo needs revoking, not deleting.

This takes minutes, not a project: automate it in Activepieces free.

Grok Model Pricing and Rate Limits by Tier

Until you revoke it, a leaked key bills at these rates, per xAI's pricing docs.

Grok 4.7 costs $2 per million input tokens and $6 to $12 per million output.

Grok models, endpoints and context window sizes

Not every model holds the same prompt. According to AI Business Weekly, Grok 4.3 and Grok 4.20 take 1000K tokens, Grok 4.7 takes 500K and Code Fast 1 takes 256K. The newest flagship therefore holds half the context of the older models.

Context window size by Grok model

A whole-repo prompt may need trimming before it fits in the 500K window of Grok 4.7. Pick the model by the largest prompt you send, not by the version number.

Grok API price per million tokens

Where the docs give a full set of figures, the table shows the pricing for three models. The output column reads short prompt to long prompt, and the takeaway is that output cost doubles on long prompts for every row.

Model Input $/M Cached input $/M Output $/M (short to long prompt)
grok-4.7 2 0.5 6 to 12
grok-4.6 2 0.5 6 to 12
grok-4.3 1.25 0.2 2.5 to 5

Cached input is 4 to 6 times cheaper than standard input here, so a CLI session that resends the same context each turn should be mostly cache hits, and your bill depends on that ratio.

Pricing table with shorter bars for cached input

Standard and cached input prices by Grok model

Take a session of 400K input tokens, 300K of them cached, plus 20K output tokens, all under short-prompt pricing.

On Grok 4.3, 100K × $1.25 + 300K × $0.20 + 20K × $2.50 comes to about $0.24, and on Grok 4.7, 100K × $2 + 300K × $0.50 + 20K × $6 comes to about $0.47, meaning per-query costs roughly double for this token distribution.

So 4.7 costs roughly double for the same traffic. Push the prompt into long-prompt territory and the output share doubles again. Tool-call surcharges are billed on top, and I have no figure for them, so read that page before you budget.

Grok output prices on short and long prompts

xAI API rate limits by tier

When a CI job fans out parallel calls, a script that works at Tier 0 on a single laptop can start returning 429 errors. Requests-per-minute and tokens-per-minute caps depend on your tier, and they differ per model.

I'm not quoting them here because they are shown per account in the xAI console, and a copied number goes stale. Retry with backoff, and treat the tier ceiling as a design input rather than a surprise.

You can't work out the tier thresholds from here: only xAI sets them and how to move up, and both change.

Open the pricing and limits pages on the day you build, check your own tier against the model you chose, and only then size your concurrency.

First Grok API Request and Everyday Commands

Send one request by hand before you script anything. A POST to https://api.x.ai/v1/chat/completions with a bearer key and a model id returns a completion plus a usage block, and that block is what you bill against.

Grok API curl request for a completion

curl https://api.x.ai/v1/chat/completions \
 -H "Content-Type: application/json" \
 -H "Authorization: Bearer $XAI_API_KEY" \
 -d '{
 "model": "'"$GROK_MODEL"'",
 "messages": [{"role": "user", "content": "Reply with the word ok."}]
 }'

Set GROK_MODEL to the exact id on xAI's models page for Grok 4.7. Don't guess the string from the marketing name.

A wrong id comes back as an HTTP error with a JSON body naming the model, and a missing or bad key comes back as an authentication error.

Read the status code and body before you blame the network. Both are cheaper to find here than inside a retry loop.

Then read the usage object in the response. It reports prompt tokens, completion tokens and a total.

Multiply those by the per-token prices on the pricing page and you have the real cost of that call, which a one-line prompt will understate. Log it from the first day.

If you already have an OpenAI SDK client, you can point it at the xAI base URL, because xAI documents the API as compatible with that SDK:

import os
from openai import OpenAI

client = OpenAI(
 api_key=os.environ,
 base_url="https://api.x.ai/v1",
)

resp = client.chat.completions.create(
 model=os.environ,
 messages=[{"role": "user", "content": "Reply with the word ok."}],
)
print(resp.choices[0].message.content)
print(resp.usage)

If a field you rely on is silently ignored or rejected, check xAI's API reference rather than OpenAI's. Compatibility means the request shape carries over, not that every parameter behaves the same.

Most-used Grok CLI commands and flags

I'm not going to list flags from memory. A CLI that moves this fast will punish that, and a command I can't tie to the maker's docs doesn't belong in a walkthrough. Print the real surface from the installed binary:

grok --help

Then compare it against the CLI's own documentation for the version you installed. For each command you plan to depend on, run it once by hand, note the exit code, and capture the output.

That gives you a record of what it printed on the day you built. When a scheduled job breaks later, you can diff against that record instead of guessing which release changed the output.

Next comes running these same calls unattended, where the key, the limits and the error codes above stop being theory.

You can follow the rest of this with the builder open. Start free, no card.

Grok API Errors and Production Limits

When a job fails unattended, one of seven symptoms almost always explains it, and the table below shows which, what usually causes it, and what to change.

Read the cause column first: most of these are configuration mistakes, not outages, and retrying them just burns time.

Treating a 401 and a 403 as the same thing sends you to rotate a key that was fine all along.

A 401 means the request arrived without a key the API accepts, and a 403 means the key was recognised but isn't allowed to do what you asked.

429s: rate limit or empty credits

Both come back as 429, so the status code alone can't tell you whether to wait or to pay. Read the response body.

A rate-limit 429 clears if you slow down; an empty-credits 429 never clears on its own, so a retry loop will hammer the endpoint until someone tops up the account.

Row Symptom Cause Fix
401 Unauthorized; every call fails immediately Key missing, mistyped, revoked, or the environment variable isn't set in the job's shell Print whether the variable is set (not its value), recreate the key in the xAI console, and inject it from your secret store
403 Forbidden; the key is valid but the call is refused The key or team lacks permission for that endpoint or model Check the key's permissions and your team's access in the console; don't rotate yet
404 or retired model Model not found Typo in the model name, or a model that has been deprecated and removed Check the current model list in xAI's docs and pin the name in config, not in code
429 rate limit Too many requests; succeeds after a pause You exceeded your tier's request or token limits Back off with jitter, lower concurrency, or move to a higher tier
429 empty credits Same status, but it persists however long you wait Prepaid balance is exhausted or a spend cap was hit Add credits or raise the cap; alert on balance before it reaches zero
5xx or timeout Server error or no response Transient fault on xAI's side, or a request too slow for your client timeout Retry a bounded number of times with jitter; set an explicit timeout
CLI-side failure Command exits non-zero before any API call, or config isn't picked up Wrong install path, stale config file, or the CLI's own bug Run the CLI interactively once, check its config and environment, then reinstall or update

Retry automatically on only two rows of the table. Everything else needs a human, or a config change, so make your wrapper fail loudly on them.

Grok API retries, timeouts and model retirements

Retry rate limits and 5xx errors with exponential backoff plus random jitter, and cap the attempts. Without jitter, every parallel job wakes at the same instant and trips the limit again. Without a cap, a real outage turns into an unbounded queue.

Parallel jobs retrying at staggered times against an API server

Set a spend cap in the console so a runaway loop stops at a budget instead of at your card limit.

Rotate keys on a schedule and whenever someone with access leaves; because the key lives in one environment variable, rotation is a secret-store update, not a code change.

Then there are model retirements, the quiet one. A pinned model name works until the day it returns 404, and that day arrives in a scheduled job nobody is watching.

Read xAI's deprecation notices on the day you build, and add a cheap daily check that calls the pinned model once and pages you if it fails. What follows is wiring that check, and the rest of the job, into something that runs without you.

Running Grok in CI, Cron and Activepieces

You will see a 401 first, from a job that worked on your laptop. A headless Grok run in CI is the same CLI, with the key supplied by the runner instead of by you.

CI and scheduled jobs with a secret key

That 401 usually means the key lived in your shell profile and never reached the runner. Store it as a secret in your CI system, expose it to the one step that calls Grok, and nowhere else.

New variable dialog in Activepieces showing name and value fields for storing an API key securely.

A key echoed into a build log is a key you now have to rotate, and logs outlive the job that wrote them.

Running Grok CLI in cron jobs

On cron the problem runs the other way. A cron job starts with a nearly empty environment, so a variable exported in your terminal doesn't exist there.

Set it in the job's own environment or load it from a file only the job's user can read, and write the output somewhere you'll look.

Spend caps and usage logging

Unattended jobs punish cost hardest. A loop that retries on every failure, with nobody watching, bills per token until someone notices.

Set a spend cap in the xAI Console before the first scheduled run, so a runaway job stops at a ceiling instead of at your card limit. Then check the response's usage field and write it to your job log on every run.

Admin dashboard showing AI usage metrics, spending by source, project costs, and AI model usage breakdown with charts and…

Without that record you can't say which job spent the money.

Handling Grok API rate limits in scripts

Rate limits belong in the script too. A 429 or a 5xx isn't a reason to fail the build or to hammer the endpoint again at once.

Retry with a growing delay, give up after a few attempts, and exit non-zero so the failure is visible.

Connect tools to your workflows

From a runner, the CLI can reach the model, but it can't reach your tickets, your sheets or your chat unless you wire each one by hand. That wiring is where scripts grow credentials nobody tracks.

Activepieces covers this from two sides. For a fixed job, a flow can call the xAI API on a schedule, and a run costs 1 credit however many steps it has; the free plan includes 1,000 credits a month and unlimited flows.

You get the cron job without owning a server, and a credit count you can budget against.

For an agent, an integration connected once in Activepieces is already a tool.

Every integration you connect is available as an MCP tool on the project's MCP server, so Claude, Cursor or an agent you built can call your tickets, sheets and chat from the same connection the flow uses.

Activepieces MCP Server setup page with client configuration instructions and code example.

The MCP Server docs describe it, and the code under packages/integrations in the open repo, home to 751 integrations under an MIT-licensed core, shows the one definition behind both, which means custom adapter development is typically unnecessary.

Be plain about the limit: MCP gives the agent access, not judgement. It will still call a tool with a bad argument, and you still decide which apps are exposed and what each connection is allowed to do.

Each of these is a failure you would otherwise meet in production, and a scheduled run is only trustworthy once all of them are true:

  • Key held as a CI secret
  • Spend cap set in the Console
  • Model name pinned and checked for deprecation
  • Backoff on 429 and 5xx
  • Usage field logged per run

Work through them in that order. The key and the cap protect your account, the pinned model protects you from a silent change, and the last two tell you what happened when something goes wrong.

Frequently asked questions

Is the Grok CLI free to use? Don't assume so. The install costs nothing, but every request the CLI makes goes through the xAI API, which bills per token.

As of 2026-12-06 I have no free-tier allowance I can vouch for. Read the pricing page on the day you build, and treat any promotional credit as something that expires, not a budget.

Does Grok CLI work with an existing X or SuperGrok subscription?

Check before you rely on it. A consumer subscription and an API account are separate billing relationships, and a chat plan paying for the app doesn't mean the CLI draws on it.

The safe assumption is that the CLI authenticates with an API key and bills against your xAI account.

If xAI's docs say a subscription sign-in works, test it with one throwaway prompt and look at which account the usage lands on. That check takes a minute, and it's cheaper than finding out from an invoice.

Which Grok model should a coding agent use?

Grok 4.7, which xAI lists as its flagship for code and chat, with agentic tool calling. That tool-calling support is what an agent loop needs, because the agent has to call tools, read results and call again.

Pin the exact model name in your config rather than relying on a default, so a silent change on xAI's side can't alter your agent's behaviour between two runs. If a cheaper model ever suits your simple jobs, prove it on your own tasks first.

How do I stop surprise bills on the xAI API?

Cap the account, then limit what any one key can do. Set a spending limit in the xAI console if your account offers one, and give each job or pipeline its own key so a runaway loop is traceable and revocable without taking everything down.

Keep the key in your CI secret store, not in the repo or a shell profile on a shared box.

Pin the model, and log token usage per run. The usual cause of a bill nobody expected is an agent retrying on errors in a loop, so cap retries and the length of a single run as well.

Expect all of it to change often: cached input pricing, what triggers a tier upgrade and what happens when a prompt grows very long. Look them up in xAI's docs on the day you build, and write the date next to whatever you find.

Share

Build it

Set this up in minutes.

No code required. Connect your accounts, and Activepieces runs it from there.

Start free Talk to sales