Grok SDK
The Grok SDK grants you access to the APIs powering grok.x.ai. Note that all of these APIs are personalized to your user and thus should not be used to create derived applications. Use the Chat SDK instead if you wish to implement an app that is powered by Grok and will serve other users.
The main distinction between the Grok SDK and the Chat SDK is that Grok conversations are stateful (i.e. they are persisted on our servers) and you can see all your conversation on grok.x.ai.
This SDK is mostly intended for researchers who would like to investigate Grok's capabilities using more powerful prompting techniques and branching.
Getting started
You can access the Grok SDK by creating a new Client
instance and then accessing the grok
property.
Linear conversation
To start a linear conversation, call the create_conversation
method on the Grok SDK and then use the add_response
function to add a new user-response to the conversation.
"""A simple example demonstrating text completion."""
import asyncio
import sys
import xai_sdk
async def main():
"""Runs the example."""
client = xai_sdk.Client()
conversation = client.grok.create_conversation()
print("Enter an empty message to quit.\n")
first = True
while True:
user_input = input("Human: ")
print("")
if not user_input:
return
token_stream, _ = conversation.add_response(user_input)
print("Grok: ", end="")
async for token in token_stream:
print(token, end="")
sys.stdout.flush()
print("\n")
if first:
print("===")
print("Generating title..")
title = await conversation.generate_title()
print(f"Title: {title}")
print("===\n")
first = False
asyncio.run(main())
Note that add_response
returns a tuple of the form token_stream, response
where token_stream
is an iterable, which
streams out Grok's response in real time and response
as a future that resolves once the response has been fully created.
It's important to emphasize that you must iterate over token_stream
in order for response
to resolve.
API reference
xai_sdk.grok.AsyncGrok
Allows talking to Grok via the API.
Note that all conversations performed via this API will show up on grok.x.ai too. So, do NOT use
this API to build new products as it's personalized to your user. Use the chat
API instead.
Source code in xai_sdk/grok.py
xai_sdk.grok.AsyncGrok.__init__(stub)
Initializes a new instance of the AsyncGrok
class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
stub |
ChatStub
|
gRPC Stub used to communicate with the xAI API. |
required |
xai_sdk.grok.AsyncGrok.create_conversation(model_name='', fun_mode=False)
Creates a new empty conversation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_name |
str
|
Name of the model to use for this conversation. Leave empty to use the default model. |
''
|
fun_mode |
bool
|
Whether fun mode shall be enabled for this conversation. |
False
|
Returns:
Type | Description |
---|---|
Conversation
|
Newly created conversation. |
Source code in xai_sdk/grok.py
xai_sdk.grok.AsyncGrok.get_conversation(conversation_id, model_name='', fun_mode=False)
async
Loads an existing conversation based on its ID.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
conversation_id |
str
|
ID of the conversation to load. |
required |
model_name |
str
|
Name of the model to use for this conversation. Leave empty to use the default model. |
''
|
fun_mode |
bool
|
Whether fun mode shall be enabled for this conversation. |
False
|
Returns:
Type | Description |
---|---|
Conversation
|
Loaded conversation. |
Source code in xai_sdk/grok.py
xai_sdk.grok.AsyncGrok.list_conversations()
async
Returns a list of all conversations.
xai_sdk.grok.Conversation
SDK for interacting with a Grok conversation.
A Grok conversation is composed of a forest of responses. It's not a tree because there can be multiple root nodes. Each connected component in the response graph is, however, a tree. Responses can be created by a human user or sampled from Grok. Users can also store responses with Grok indicated as the sender, which is useful for debugging and research purposes.
Note that the properties of the conversation are cached client-side.
Important: A single conversation is not thread-safe. Only a single response must be sampled at any point in time.
Source code in xai_sdk/grok.py
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 |
|
xai_sdk.grok.Conversation.conversation_id: str
property
Returns the ID of this conversation.
Raises:
Type | Description |
---|---|
ValueError
|
if no actual conversation has been created or loaded yet. |
xai_sdk.grok.Conversation.create_time: datetime.datetime
property
Returns the time when this conversation was created.
Raises:
Type | Description |
---|---|
ValueError
|
if no actual conversation has been created or loaded yet. |
xai_sdk.grok.Conversation.root_responses: Generator[Response, None, None]
property
Returns all root responses in the response graph.
xai_sdk.grok.Conversation.starred: bool
property
Returns whether the conversation is starred.
Raises:
Type | Description |
---|---|
ValueError
|
if no actual conversation has been created or loaded yet. |
xai_sdk.grok.Conversation.title: str
property
Returns the title of this conversation.
Raises:
Type | Description |
---|---|
ValueError
|
if no actual conversation has been created or loaded yet. |
xai_sdk.grok.Conversation.__init__(stub, model_name, fun_mode, conversation_id)
Initializes a new instance of the Conversation
class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
stub |
ChatStub
|
gRPC stub used to communicate with the xAI API. |
required |
model_name |
str
|
Name of the model to use for this conversation. |
required |
fun_mode |
bool
|
True if fun mode shall be enabled for this conversation. |
required |
conversation_id |
Optional[str]
|
ID of this conversation. If no ID was provided, a new conversation is created when the first API call is issued. |
required |
Source code in xai_sdk/grok.py
xai_sdk.grok.Conversation.add_response(user_message)
Adds a new response to this conversation.
The response is added to the graph with its parent being the current leaf
response.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
user_message |
str
|
Message written by the user. If empty, no user response is generated. |
required |
Yields:
Type | Description |
---|---|
tuple[AsyncGenerator[str, Response], Future[Response]]
|
Text snippets emitted by the model. |
Returns:
Type | Description |
---|---|
tuple[AsyncGenerator[str, Response], Future[Response]]
|
A tuple of the form (token_generator, new_model_response). |
Source code in xai_sdk/grok.py
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 |
|
xai_sdk.grok.Conversation.delete()
async
Deletes this conversation.
Source code in xai_sdk/grok.py
xai_sdk.grok.Conversation.generate_title()
async
Automatically generates a title for this conversation.
Returns:
Type | Description |
---|---|
str
|
The newly generated title. |
Source code in xai_sdk/grok.py
xai_sdk.grok.Conversation.get_children(parent_response_id)
Yields all responses whose parent is parent_response_id
.
Source code in xai_sdk/grok.py
xai_sdk.grok.Conversation.get_response(response_id)
Returns a response by its ID.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
response_id |
str
|
ID of the response to return. |
required |
Returns:
Type | Description |
---|---|
Response
|
KeyError if the response cannot be found. |
Source code in xai_sdk/grok.py
xai_sdk.grok.Conversation.load()
async
Loads the conversation and all its responses from the API.
Raises:
Type | Description |
---|---|
ValueError
|
If no conversation ID was provided. |
Source code in xai_sdk/grok.py
xai_sdk.grok.Conversation.register_response(response)
Manually adds a response to the response graph.
Don't use this API unless you know what you're doing.
xai_sdk.grok.Conversation.set_leaf_response_id(leaf_response_id)
Updates the leaf response ID. Don't use this API directly. Prefer Response.select()
.
xai_sdk.grok.Conversation.set_title(title)
async
Updates the title of this conversation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
title |
str
|
New title of the conversation. |
required |
Source code in xai_sdk/grok.py
xai_sdk.grok.Conversation.star()
async
Stars this conversation.
Source code in xai_sdk/grok.py
xai_sdk.grok.Conversation.unstar()
async
Unstars this conversation.
Source code in xai_sdk/grok.py
xai_sdk.grok.Response
Represents a single response in a conversation.
Note that the properties of the response are cached client-side. Call the refresh function
Source code in xai_sdk/grok.py
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 |
|
xai_sdk.grok.Response.children: list[Response]
property
Returns a list of all child responses.
xai_sdk.grok.Response.create_time: datetime.datetime
property
Returns the time when this response was created.
xai_sdk.grok.Response.manual: bool
property
Returns True if the response was created manually via the API.
xai_sdk.grok.Response.message: str
property
Returns the message content.
xai_sdk.grok.Response.parent_response: Optional[Response]
property
Returns the parent response of None if this is a root response.
Raises:
Type | Description |
---|---|
KeyError
|
If the parent response cannot be found. |
xai_sdk.grok.Response.parent_response_id: Optional[str]
property
Returns the ID of the parent response in the response graph.
xai_sdk.grok.Response.partial: bool
property
Returns True if the response represents a partial model output.
xai_sdk.grok.Response.query: str
property
Returns the query string used by the model if the model performed a query.
xai_sdk.grok.Response.query_type: str
property
Returns the type of query performed by the model if it performed a query.
xai_sdk.grok.Response.response_id: str
property
Returns the ID of this response.
xai_sdk.grok.Response.sender: str
property
Returns the sender of this message. "human" indicates the message was sent by a human.
xai_sdk.grok.Response.shared: bool
property
Returns True if the response was shared publicly.
xai_sdk.grok.Response.__init__(response, conversation, stub)
Initializes a new instance of the Response
class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
response |
Response
|
Raw proto response object returned from the API. |
required |
conversation |
Conversation
|
Conversation this response belongs to. |
required |
stub |
ChatStub
|
Stub used to communicate with the xAI API. |
required |
Source code in xai_sdk/grok.py
xai_sdk.grok.Response.replace(new_message)
Replaces the text of this message with a new text.
Note: If this is a user response, a new model response will be sampled. If this is a model response, it will be replaced by a new response with the given message. In both cases, the return value is a model response.
Source code in xai_sdk/grok.py
xai_sdk.grok.Response.resample()
async
Resamples this response.
This adds a new child to the parent response that is sampled from the model.
Raises:
Type | Description |
---|---|
ValueError
|
If this response was generated by human. |
Source code in xai_sdk/grok.py
xai_sdk.grok.Response.select()
Selects this response to be the most recent one in the conversation.
Use this to go back to an earlier response.
xai_sdk.grok.Response.share()
async
Shares the conversation up to this point publicly.
Returns:
Type | Description |
---|---|
str
|
The RUL of the shared conversation. |