import gradio as gr import openai from openai import OpenAI import os def setup_client(): api_key = os.environ.get('OPENROUTER_API_KEY') if not api_key: raise ValueError("OPENROUTER_API_KEY environment variable not set") return OpenAI( base_url="https://openrouter.ai/api/v1", api_key=api_key, ) def chat_with_grok(message, history): """Main chat function""" if not message: return history, "" try: client = setup_client() # Create the completion completion = client.chat.completions.create( model="x-ai/grok-4", messages=[ { "role": "user", "content": message } ], max_tokens=1000, temperature=0.7 ) response = completion.choices[0].message.content # Add to history history.append((message, response)) return history, "" except Exception as e: error_msg = f"Error: {str(e)}" history.append((message, error_msg)) return history, "" def clear_chat(): """Clear the chat history""" return [], "" # Create the Gradio interface with gr.Blocks(title="Grok 4 Chat Interface by Xhaheen ", theme=gr.themes.Soft()) as demo: gr.HTML("""
Chat with xAI's Grok 4 model via OpenRouter