Spaces:
Sleeping
Sleeping
File size: 3,118 Bytes
01d0840 d4bb78b 01d0840 d4bb78b 01d0840 d4bb78b 01d0840 d4bb78b 01d0840 003f2e8 01d0840 d4bb78b 01d0840 003f2e8 01d0840 d4bb78b 01d0840 d4bb78b 01d0840 003f2e8 d4bb78b 003f2e8 01d0840 003f2e8 01d0840 003f2e8 01d0840 003f2e8 01d0840 003f2e8 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 98 99 100 101 102 103 104 |
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.
Please respond in Traditional Chinese (繁體中文).
Keep your responses natural and conversational while maintaining Traditional Chinese characters."""
}
]
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]]) -> Tuple[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 聊天機器人
與 Elon Musk 的 Grok AI 聊天!這個聊天機器人使用了 xAI 的 Grok API。
""")
chatbot = gr.Chatbot(
value=[],
height=500,
bubble_full_width=False,
show_copy_button=True,
)
with gr.Row():
msg = gr.Textbox(
placeholder="輸入訊息...",
container=False,
scale=7,
autofocus=True, # 自動聚焦到輸入框
)
clear = gr.ClearButton([msg, chatbot], variant="secondary", scale=1)
# 注意這裡輸出添加了msg,用於清除輸入框
msg.submit(respond, [msg, chatbot], [msg, chatbot], api_name="chat")
demo.queue()
# 啟動應用
if __name__ == "__main__":
demo.launch() |