import gradio as gr import os import json import requests from typing import List, Tuple # 環境變數設置 XAI_API_KEY = os.getenv("XAI_API_KEY") if not XAI_API_KEY: raise ValueError("Please set XAI_API_KEY environment variable") def call_grok_api(messages: List[dict]) -> str: """調用Grok API""" headers = { "Content-Type": "application/json", "Authorization": f"Bearer {XAI_API_KEY}" } data = { "messages": messages, "model": "grok-beta", "stream": False, "temperature": 0.7 } try: response = requests.post( "https://api.x.ai/v1/chat/completions", headers=headers, json=data ) response.raise_for_status() return response.json()["choices"][0]["message"]["content"] except requests.exceptions.RequestException as e: return f"Error calling Grok API: {str(e)}" def format_history(history: List[Tuple[str, str]]) -> List[dict]: """將聊天歷史格式化為Grok API需要的格式""" formatted_messages = [ { "role": "system", "content": "You are Grok, a chatbot inspired by the Hitchhikers Guide to the Galaxy." } ] for user_msg, assistant_msg in history: if user_msg: formatted_messages.append({ "role": "user", "content": user_msg }) if assistant_msg: formatted_messages.append({ "role": "assistant", "content": assistant_msg }) return formatted_messages def respond(message: str, history: List[Tuple[str, str]]) -> List[Tuple[str, str]]: """處理用戶輸入並生成回應""" # 格式化歷史記錄並添加新消息 history_for_api = format_history(history + [(message, None)]) # 獲取Grok的回應 response = call_grok_api(history_for_api) # 返回更新後的歷史記錄 history.append((message, response)) return history # 創建Gradio界面 with gr.Blocks() as demo: gr.Markdown(""" # Grok Chatbot 與Elon Musk的Grok AI聊天!這個聊天機器人使用了xAI的Grok API。 """) chatbot = gr.Chatbot( value=[], height=500 ) msg = gr.Textbox( placeholder="輸入訊息...", container=False, scale=7 ) clear = gr.ClearButton([msg, chatbot], variant="secondary", scale=1) msg.submit(respond, [msg, chatbot], [chatbot], api_name="chat") demo.queue() # 啟動應用 if __name__ == "__main__": demo.launch()