The Hitchhiker's Guide to Grok
Welcome to the Hitchhiker's Guide to Grok! This guide will walk you through the basics of using the xAI API to interact with our Grok models, providing you with the tools to harness AI in your applications.
Creating your account
You need an xAI account to access xAI API.
You can create an account at xAI Console.
Creating an API key
Go to xAI Console API Keys Page to create an API key.
For production use, store your API key securely. Do not share or hard-code it into your scripts, or commit into version control systems such as git
. Use local environment variables or secure configuration files (e.g. GitHub Secrets, Google Cloud Secret Manager).
Once you have generated an API key, export it as an environment variable in your terminal.
Making your first request
With your xAI API key exported as an environment variable, you're ready to make your first API request.
Let's test out the API using curl
.
Our API is also compatible with OpenAI and Anthropic SDK. For example, to make the same request with OpenAI Python SDK:
Using Grok with image understanding capability
You can also send image in the prompt to models with image input capability. For example:
You will see Grok's response:
Ah, the age-old question. According to Douglas Adams, the answer is 42. However, the real trick lies in understanding the question, which remains a mystery. So, in essence, the meaning of life, the universe, and everything is to seek understanding, embrace the journey, and maybe have a good laugh along the way. Remember, as the Hitchhiker's Guide to the Galaxy suggests, "Don't Panic!" Keep exploring, keep questioning, and enjoy the ride through this cosmic adventure!
The completion
object has more attributes available, such as usage information, tool calls, creation time, service tier and system fingerprint. You can use those information to build more complex interactions between your system and xAI API.
For details on advanced use cases or implementing other types of workflows, check out one of our Guides.
Monitoring usage
As you use your API key, you will be charged for the number of tokens used. For an overview, you can monitor your usage on the xAI Console Usage Page.
If you want a more granular, per request usage tracking, the API response includes a usage object that provides detail on prompt (input) and completion (output) token usage.
If you send requests too frequently or with long prompts, you might run into rate limits and get an error response. For more information, read Usage, Tiers and Rate Limits.