xAI-Chat / app.py
typesdigital's picture
Update app.py
4ccab68 verified
raw
history blame
1.84 kB
import os
import requests
import gradio as gr
# Set your API key
os.environ['XAI_API_KEY'] = 'xai-Gxw7oW4yR6Q6oTd0v9lDRLotXZQYJNz9YKlH7R6eMyTmqIV9h6uustEGZAaJEvGmewlwbUnM1jTX4chj' # Replace with your actual API key
# Initialize conversation history
conversation_history = []
def chat_with_bot(user_input):
# Append user input to conversation history
conversation_history.append({"role": "user", "content": user_input})
url = "https://api.x.ai/v1/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {os.environ['XAI_API_KEY']}"
}
# Prepare messages for the API call
messages = [{"role": "system", "content": "You are a helpful assistant."}] + \
[{"role": msg["role"], "content": msg["content"]} for msg in conversation_history]
data = {
"messages": messages,
"model": "grok-beta",
"stream": False,
"temperature": 0.7
}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
bot_response = response.json()['choices'][0]['message']['content']
# Append bot response to conversation history
conversation_history.append({"role": "assistant", "content": bot_response})
# Format the chat history for display
chat_display = "\n".join([f"{msg['role'].capitalize()}: {msg['content']}" for msg in conversation_history])
return chat_display
else:
return f"Error: {response.text}"
# Create Gradio interface
iface = gr.Interface(
fn=chat_with_bot,
inputs="text",
outputs="text",
title="xAI Chatbot",
description="Chat with Grok! Type your message below.",
theme="default",
)
# Launch the interface
if __name__ == "__main__":
iface.launch()