Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,37 +1,52 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
import
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
|
3 |
+
try:
|
4 |
+
from groq import Groq
|
5 |
+
except ImportError:
|
6 |
+
os.system('pip install groq')
|
7 |
+
from groq import Groq
|
8 |
+
|
9 |
+
import gradio as gr
|
10 |
+
|
11 |
+
# 从环境变量中获取 API Key
|
12 |
+
groq_key = os.getenv("groq_key")
|
13 |
+
client = Groq()
|
14 |
+
|
15 |
+
# 定义聊天机器人的响应函数
|
16 |
+
def chat_with_bot(user_input):
|
17 |
+
completion = client.chat.completions.create(
|
18 |
+
model="llama-3.1-70b-versatile",
|
19 |
+
messages=[
|
20 |
+
{
|
21 |
+
"role": "system",
|
22 |
+
"content": "你是一位國中地理老師,使用的語言為繁體中文(zh-tw)。你的興趣是繪製等高線圖,熱愛講冷笑話。無論學生問你什麼問題,你都會把話題引導到地理相關的討論上。"
|
23 |
+
},
|
24 |
+
{
|
25 |
+
"role": "user",
|
26 |
+
"content": user_input
|
27 |
+
}
|
28 |
+
],
|
29 |
+
temperature=1,
|
30 |
+
max_tokens=1024,
|
31 |
+
top_p=1,
|
32 |
+
stream=True,
|
33 |
+
stop=None,
|
34 |
+
)
|
35 |
+
|
36 |
+
response = ""
|
37 |
+
for chunk in completion:
|
38 |
+
response += chunk.choices[0].delta.content or ""
|
39 |
+
|
40 |
+
return response
|
41 |
+
|
42 |
+
# 设置 Gradio 界面
|
43 |
+
with gr.Blocks() as app:
|
44 |
+
gr.Markdown("## 地理老師聊天機器人")
|
45 |
+
chatbot = gr.Chatbot()
|
46 |
+
user_input = gr.Textbox(placeholder="請輸入您的問題...")
|
47 |
+
|
48 |
+
user_input.submit(lambda x: chat_with_bot(x), user_input, chatbot)
|
49 |
+
|
50 |
+
# 启动 Gradio 应用
|
51 |
+
if __name__ == "__main__":
|
52 |
+
app.launch()
|