Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,44 +1,70 @@
|
|
| 1 |
-
|
|
|
|
| 2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
client = Groq()
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
|
| 4 |
+
# 確保 groq 已安裝
|
| 5 |
+
try:
|
| 6 |
+
from groq import Groq
|
| 7 |
+
except ImportError:
|
| 8 |
+
os.system('pip install groq')
|
| 9 |
+
from groq import Groq
|
| 10 |
+
|
| 11 |
+
# 初始化 Groq 客戶端
|
| 12 |
client = Groq()
|
| 13 |
+
|
| 14 |
+
# 獲取 API 密鑰
|
| 15 |
+
api_key = os.getenv('groq_key')
|
| 16 |
+
if not api_key:
|
| 17 |
+
raise ValueError("API key 'groq_key' 未設定於環境變數中!")
|
| 18 |
+
|
| 19 |
+
client.api_key = api_key
|
| 20 |
+
|
| 21 |
+
def chat_with_groq(user_message):
|
| 22 |
+
"""與 Groq 模型進行互動"""
|
| 23 |
+
try:
|
| 24 |
+
completion = client.chat.completions.create(
|
| 25 |
+
model="llama-3.1-70b-versatile",
|
| 26 |
+
messages=[
|
| 27 |
+
{
|
| 28 |
+
"role": "system",
|
| 29 |
+
"content": "「你是一位國中國文老師,使用的語言為繁體中文(zh-tw)。你的興趣是讓學生喜歡成語,信手拈來都能用成語融入生活情境。無論學生問你什麼問題,你都會把話題引導到國文成語相關的討論上。」"
|
| 30 |
+
},
|
| 31 |
+
{"role": "user", "content": user_message}
|
| 32 |
+
],
|
| 33 |
+
temperature=1,
|
| 34 |
+
max_tokens=1024,
|
| 35 |
+
top_p=1,
|
| 36 |
+
stream=False
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
# 確保返回結果格式正確
|
| 40 |
+
if "choices" in completion and len(completion["choices"]) > 0:
|
| 41 |
+
response = completion["choices"][0]["message"]["content"]
|
| 42 |
+
return response or "抱歉,我無法生成有效的回應。"
|
| 43 |
+
else:
|
| 44 |
+
return "抱歉,我無法解析 API 的回應結果。"
|
| 45 |
+
|
| 46 |
+
except Exception as e:
|
| 47 |
+
return f"發生錯誤:{e}"
|
| 48 |
+
|
| 49 |
+
# 定義 Gradio 介面
|
| 50 |
+
def gradio_chatbot():
|
| 51 |
+
def respond(message, history):
|
| 52 |
+
response = chat_with_groq(message)
|
| 53 |
+
history = history or []
|
| 54 |
+
history.append((message, response))
|
| 55 |
+
return history, history
|
| 56 |
+
|
| 57 |
+
with gr.Blocks() as demo:
|
| 58 |
+
gr.Markdown("### 成語遊戲 Chatbot")
|
| 59 |
+
chatbot = gr.Chatbot()
|
| 60 |
+
user_input = gr.Textbox(placeholder="輸入你的訊息...")
|
| 61 |
+
submit_button = gr.Button("送出")
|
| 62 |
+
|
| 63 |
+
submit_button.click(respond, [user_input, chatbot], [chatbot, chatbot])
|
| 64 |
+
|
| 65 |
+
return demo
|
| 66 |
+
|
| 67 |
+
# 啟動應用程式
|
| 68 |
+
if __name__ == "__main__":
|
| 69 |
+
app = gradio_chatbot()
|
| 70 |
+
app.launch()
|