How multi-turn chat works with the `append` method
mainThe SDK manages conversation history through a chat object. Instead of manually managing a list of messages, you use the append method to add new messages (using system, user, or assistant helpers) to the chat instance.
To get a response from the model, call chat.sample(). For asynchronous workflows, use AsyncClient and await chat.sample().
from xai_sdk import Client
from xai_sdk.chat import system, user
client = Client()
chat = client.chat.create(
model="grok-3",
messages=[system("You are a pirate assistant.")]
)
# Add a user message
chat.append(user("Hello!"))
# Get model response
response = chat.sample()
# Add the assistant response back to history to maintain context
chat.append(response)