The short answer: create a single Python script that accepts a prompt from the command line, sends it to Grok, prints the content, and also prints the finish_reason and usage so you can see what actually happened. Keep the script under 80 lines, load the key from the environment, and make the request observable. That is a complete, useful tool.
I built the first version of this on a Sunday afternoon in my Denver home office because I was tired of opening a notebook every time I wanted a quick Grok answer while working in the terminal. The script has lived on my PATH ever since. It is deliberately small. It does one job well and leaves an audit trail.
This article walks through a clean, minimal implementation you can copy, understand, and then extend.
What This Solves
You want a fast way to ask Grok a question from the terminal without leaving your shell or writing a new script every time. By the end of this post you will have:
A working command-line tool that takes a prompt as an argument or from stdin
Clear separation between the model response and the application output
Automatic logging of finish_reason and usage on every call
A pattern you can later extend with flags for model selection, system prompts, or JSON output
This is still part of the Grok API Starting Point series. We are not building an agent or a multi-turn chat. We are building the smallest useful tool that makes the API behavior visible.
Who Should Use This Approach
Developers who already know how to authenticate and make a basic Grok request and now want something they can run from any terminal. If you have not yet set up an API key or sent a first request, go back to the earlier articles. If you need a full interactive chat or tool-calling agent, the later posts in the Agents and Automation series will be more relevant.
Design Goals for the Tool
One file
No required configuration beyond XAI_API_KEY
Accept the prompt as a command-line argument or from stdin
Print the model’s content to stdout
Print finish_reason and usage to stderr (so they do not pollute pipes)
Fail fast and clearly if the key is missing
Stay short enough that you can read the whole script in one screen
These constraints keep the tool honest. Every extra feature is a temptation to hide behavior.
The Complete Script
Save this as grok (or grok.py) and make it executable:
Python
#!/usr/bin/env python3
"""
Minimal Grok command-line tool.
Usage:
grok "What is the difference between a model response and an application action?"
echo "Summarize this" | grok
"""
import argparse
import os
import sys
from openai import OpenAI
def require_api_key() -> str:
key = os.getenv("XAI_API_KEY")
if not key:
print("Error: XAI_API_KEY environment variable is not set.", file=sys.stderr)
sys.exit(1)
return key
def main() -> None:
parser = argparse.ArgumentParser(description="Ask Grok a question from the terminal.")
parser.add_argument(
"prompt",
nargs="?",
help="Prompt to send. If omitted, read from stdin.",
)
parser.add_argument(
"--model",
default="grok-4-1-fast-reasoning",
help="Model identifier (default: grok-4-1-fast-reasoning). Check current docs.",
)
parser.add_argument(
"--system",
default="You are a precise technical assistant. Answer clearly and concisely.",
help="Optional system prompt.",
)
args = parser.parse_args()
if args.prompt:
user_content = args.prompt
else:
user_content = sys.stdin.read().strip()
if not user_content:
print("Error: no prompt provided as argument or on stdin.", file=sys.stderr)
sys.exit(1)
client = OpenAI(
api_key=require_api_key(),
base_url="https://api.x.ai/v1",
)
completion = client.chat.completions.create(
model=args.model,
messages=[
{"role": "system", "content": args.system},
{"role": "user", "content": user_content},
],
)
choice = completion.choices[0]
content = choice.message.content or ""
finish_reason = choice.finish_reason
usage = completion.usage
# Main answer goes to stdout so it can be piped
print(content)
# Evidence goes to stderr so it stays out of pipes
print(f"\n[finish_reason={finish_reason}]", file=sys.stderr)
if usage:
print(
f"[usage: prompt={usage.prompt_tokens} completion={usage.completion_tokens} total={usage.total_tokens}]",
file=sys.stderr,
)
print(f"[model={completion.model} id={completion.id}]", file=sys.stderr)
if __name__ == "__main__":
main()
Make it executable and put it on your PATH:
Bash
chmod +x grok
# move or symlink into a directory that is on your PATHHow to Use It
Bash
grok "Explain the difference between finish_reason stop and length in one sentence."Or pipe input:
Bash
echo "What should I log on every Grok API call?" | grokOr override the model and system prompt:
Bash
grok --model grok-4-1-fast-reasoning --system "Answer in exactly two sentences." "Why is usage worth logging?"The model’s answer appears on stdout. The finish_reason, token counts, model name, and response id appear on stderr. That separation means you can still pipe the answer into another command while keeping the evidence visible in the terminal.
Why This Design
Stdout vs stderr
The content is the product. The metadata is the evidence. Keeping them on different streams lets you use the tool in pipelines without losing the ability to inspect what happened.
Explicit key check
Failing immediately with a clear message is better than a deep stack trace from the client library.
Default model is visible
The default is written in the help text and in the code. When the recommended model changes, you only have to update one place (and you should re-check the official docs).
No hidden retries or magic
The script does one request and shows you the result. If you later need retries or tool calling, add them deliberately rather than inheriting hidden behavior.
Extending the Tool Without Losing Clarity
Once the basic version is solid, useful next steps include:
A --json flag that prints the full response object as JSON on stdout (and still logs a short summary on stderr)
A --raw flag that dumps the entire completion object for debugging
Support for reading a longer system prompt from a file
A simple history file that records prompt, finish_reason, and usage for later review
Each addition should preserve the core rule: the application never treats the content field as the only output that matters.
Common Mistakes When Building CLI Tools Around the API
Putting the API key in the script or in a config file that gets committed
Printing everything (including usage) to stdout and then wondering why pipes break
Swallowing exceptions and only showing a generic “request failed” message
Hard-coding a model name that later disappears from the catalog
Adding a complex interactive chat loop before the single-shot path is reliable
Start with the single-shot path. Make it observable. Only then decide whether a multi-turn interface is worth the extra complexity.
A Small Story from the Home Lab
I originally wrote this tool because I was jumping between a terminal and a browser window dozens of times a day. The first version printed only the content. After a few weeks I noticed I had no record of how many tokens the quick questions were actually using, and I could not tell whether a short answer had been truncated. Adding the stderr summary took ten minutes and immediately changed how I used the tool. I started noticing when a prompt was larger than I expected and when a finish_reason was not the simple “stop” I assumed. The tool became both a convenience and a lightweight observability aid.

Practical Checklist
Script runs with only XAI_API_KEY set
Prompt can come from an argument or from stdin
Model content goes to stdout
finish_reason, usage, model, and id go to stderr
Missing key produces a clear error and non-zero exit
You have tested both interactive use and a simple pipe
When a Simpler Approach Is Better
If you only need an answer once, the consumer chat interfaces are faster. If you need multi-turn conversation, tool calling, or persistent state, a full application or the later agent patterns on this site will be more appropriate. Do not turn this small CLI into an agent framework. Keep it small and observable.
Closing
A good command-line tool for Grok does three things: it sends a clear request, it surfaces the model’s content, and it never hides the evidence about what the API actually returned. The script above does exactly that and nothing more.
Install it, run a few questions, and watch the stderr lines. Once you are in the habit of seeing finish_reason and usage on every call, the rest of the integration work becomes much easier.
Build the smallest tool that answers the question.
Explain every piece of output it produces.
Verify that the evidence is still visible when you pipe the answer somewhere else.
Build it. Explain it. Verify it.
Next we will look at what to do when the SDK succeeds but the raw request (or the other way around) fails—how to debug the gap between a high-level client and the actual HTTP traffic.
Comments
No comments yet — be the first to share a thought.