Spaces:
Sleeping
Sleeping
File size: 2,622 Bytes
01d0840 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
import gradio as gr
import os
import json
import requests
from typing import List, Dict
# 環境變數設置
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[Dict]) -> List[Dict]:
"""將Gradio的歷史記錄格式化為Grok API需要的格式"""
formatted_messages = [
{
"role": "system",
"content": "You are Grok, a chatbot inspired by the Hitchhikers Guide to the Galaxy."
}
]
for msg in history:
formatted_messages.append({
"role": "user" if msg["role"] == "user" else "assistant",
"content": msg["content"]
})
return formatted_messages
def respond(message: str, history: List[Dict]) -> Dict:
"""處理用戶輸入並生成回應"""
history.append({"role": "user", "content": message})
# 格式化消息歷史
formatted_history = format_history(history)
# 獲取Grok的回應
response = call_grok_api(formatted_history)
# 添加助手回應到歷史記錄
history.append({"role": "assistant", "content": response})
return history
# 創建Gradio界面
with gr.Blocks() as demo:
gr.Markdown("""
# Grok Chatbot
與Elon Musk的Grok AI聊天!這個聊天機器人使用了xAI的Grok API。
""")
chatbot = gr.Chatbot(
value=[],
bubble_full_width=False,
avatar_images=(None, "🤖"),
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() |