A community-maintained SDK (Standard Developer Kit) for XAI Grok models supporting usage with the Python Programming Language. This library provides convenient access to the xAI REST API from Python 3.11+ applications, with type definitions for all request parameters and response fields.
pip install xai-grok- Python 3.11 or higher
- pydantic
- requests
from xai_grok import Grok
client = Grok(
api_key="your-api-key-here"
)
# Example: Create a chat completion
response = client.chat_completions(
ChatRequest(
messages=[
{"role": "user", "content": "Tell me about AI"}
],
model="model-name-here"
)
)
print(response.choices[0].message.content)api_key()- Retrieve information about the current API key
-
chat_completions(request: ChatRequest)- Create chat completions- Input: ChatRequest object containing messages and model settings
- Throws: InvalidRequestError, IncompleteRequestError
-
complete(request: CompleteRequest)- Generate completions- Input: CompleteRequest object with prompt and settings
- Throws: InvalidRequestError, IncompleteRequestError
-
completions(request: SampleRequest)- Alternative completion endpoint- Input: SampleRequest object
- Throws: InvalidRequestError, IncompleteRequestError
-
embedding_model(model_id: str)- Get details of a specific embedding model- Input: Model ID string
- Throws: ModelNotFoundError
-
embedding_models()- List all available embedding models -
embeddings(request: EmbeddingRequest)- Generate embeddings- Input: EmbeddingRequest object
- Throws: InvalidRequestError, IncompleteRequestError
-
language_model(model_id: str)- Get details of a specific language model- Input: Model ID string
- Throws: ModelNotFoundError
-
language_models()- List all available language models
messages(request: MessageRequest)- Send messages- Input: MessageRequest object
- Throws: InvalidRequestError, IncompleteRequestError
-
models()- List all available models -
model(model_id: str)- Get details of a specific model- Input: Model ID string
- Throws: ModelNotFoundError
tokenize_text(request: TokenizeTextRequest)- Tokenize input text- Input: TokenizeTextRequest object
- Throws: InvalidRequestError
All request and response types are Pydantic models, providing type safety and validation. Refer to the schemas module for detailed type definitions.
The API uses https://api.x.ai as the base URL for all endpoints.
The API requires an authorized API key. Authentication-related errors are handled by specific error types:
NoAPIKeyProvidedError: Raised when no API key is provided in the Authorization headerInvalidAPIKeyProvidedError: Raised when an incorrect API key is provided
To avoid these errors:
- Obtain a valid API key from console.x.ai
- Include it in the client initialization:
client = Grok(api_key="your-api-key-here")All responses are parsed into their corresponding Pydantic models, providing
type-safe access to response data. If the API response cannot be parsed into
the expected type, a FailedToParseResponseError will be raised.
