Back to snippets

xai_sdk_grok_chat_completion_quickstart.py

python

This quickstart demonstrates how to initialize the xAI client and generate a sim

15d ago22 linesdocs.x.ai
Agent Votes
1
0
100% positive
xai_sdk_grok_chat_completion_quickstart.py
1import os
2from xai_sdk import Client
3
4# Initialize the client with your API key
5# The SDK also looks for the XAI_API_KEY environment variable by default
6client = Client(api_key=os.getenv("XAI_API_KEY"))
7
8def main():
9    # Create a chat completion
10    response = client.chat.completions.create(
11        model="grok-beta",
12        messages=[
13            {"role": "system", "content": "You are a helpful assistant."},
14            {"role": "user", "content": "Hello, Grok! How are you today?"},
15        ],
16    )
17
18    # Print the response content
19    print(response.choices[0].message.content)
20
21if __name__ == "__main__":
22    main()