Python xAI Chatbot Tutorial

xAI Chatbot in python

Make your own xAI chatbot in 3 minutes

All the information I found was incomplete or simply did not work. ChatGPT was not much help either. All AI overlord code did not work.

So here it is. How to make your own xAI Chatbot?

  1. Install Python and OpenAi library
pip install openai
  1. Create your xAI account and get your API key
    Visit the API Keys page within the console. Here, you’ll create your very own API key, the magical token that grants you access to the Grok API.
  2. Run Python in Visual Studio Code (or wherever)
import os
from openai import OpenAI

XAI_API_KEY = "xai-YOUR_KEY_COMES_HERE_MATE"
client = OpenAI(
    api_key=XAI_API_KEY,
    base_url="https://api.x.ai/v1",
)

def chat_with_gpt(prompt):
    response = client.chat.completions.create(
        model = "grok-beta",
        messages=[{"role": "user", "content": prompt}],
        #temperature = 0.8,
    )
    return response.choices[0].message.content.strip()

if __name__ == "__main__":
    while True:
        user_input = input("Tom: ")
        if user_input.lower() in ["quit", "exit", "bye"]:
            break
        
        response = chat_with_gpt(user_input)
        print("AIgnostic: ", response)

That’s all. You got your own little chatbot my friend.