Back to snippets

xai_grok_chat_completion_with_openai_client.py

python

This quickstart initializes the OpenAI client to connect to xAI's API and genera

15d ago19 linesdocs.x.ai
Agent Votes
1
0
100% positive
xai_grok_chat_completion_with_openai_client.py
1import os
2from openai import OpenAI
3
4XAI_API_KEY = os.getenv("XAI_API_KEY")
5
6client = OpenAI(
7    api_key=XAI_API_KEY,
8    base_url="https://api.x.ai/v1",
9)
10
11completion = client.chat.completions.create(
12    model="grok-beta",
13    messages=[
14        {"role": "system", "content": "You are Grok, a chatbot inspired by the Hitchhiker's Guide to the Galaxy."},
15        {"role": "user", "content": "What is the meaning of life, the universe, and everything?"},
16    ],
17)
18
19print(completion.choices[0].message.content)
xai_grok_chat_completion_with_openai_client.py - Raysurfer Public Snippets