Getting started
Our SDK is the recommended way of interacting with the xAI API. To get started using our SDK, install it via pip
:
API Key
Before you can start using the SDK, you have to generate an API key in the PromptIDE. Please follow these instructions.
Once you have created your key, copy it to your clipboard and store it in an environment variable named XAI_API_KEY
:
Remember that API keys are associated with a set of ACLs. If you get a permission denied error, double check to make sure your API key has the right ACLs for the task you're trying to accomplish. You can validate that API access works, by running the following command:
If everything works correctly, it will output the string Does it work? Yes, it does.
. Note that your API key must have the
sampler:write
ACL in order for this sanity check to work.
Example
Now that you have installed our SDK and configured your API key, you should be able to run the following example program. Note that
your API key needs the sampler:write
ACL in order for this program to work.
"""A simple example demonstrating text completion."""
import asyncio
import xai_sdk
async def main():
"""Runs the example."""
client = xai_sdk.Client()
prompt = "The answer to live and the universe is"
print(prompt, end="")
async for token in client.sampler.sample(prompt, max_len=3):
print(token.token_str, end="")
print("")
asyncio.run(main())
Trouble shooting
Missing XAI_API_KEY
If you get the following error, you have not configured your XAI_API_KEY
environment variable correctly.
ValueError: Trying to read the xAI API key from the XAI_API_KEY environment variable but it doesn't exist.
Double check to make sure you followed the instruction above.
Missing ACLs
If you get the following error, you have not configured the correct ACLs on your API key.
Return to the PromptIDE and edit your API key.
API Reference
xai_sdk.Client
Client for connecting to the xAI API.
The client uses an API key, which is either read from the environment variable XAI_API_KEY
or
provided by the api_key
constructor argument. API keys can be created and managed in our IDE,
which is available under ide.x.ai (click on your username in the top right hand corner).
The API is hosted on api.x.ai, and we connect via port 443.
Source code in xai_sdk/client.py
xai_sdk.Client.__init__(api_key=None, *, initial_rng_seed=None, api_host='api.x.ai')
Initializes a new instance of the Client
class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
api_key |
Optional[str]
|
API key to use. If unspecified, the API key is read from the |
None
|
initial_rng_seed |
Optional[int]
|
Used to make calls to the API deterministic given the initial seed and
the order of API calls. If unspecified, a random seed will be sampled for every new
instance of the |
None
|
api_host |
str
|
Hostname of the API server. |
'api.x.ai'
|
Raises:
Type | Description |
---|---|
ValueError
|
If the |
ValueError
|
If the API key is empty. |