Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,19 +1,21 @@
|
|
| 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 |
-
|
| 10 |
-
|
| 11 |
-
# 从环境变量中获取 API Key
|
| 12 |
-
groq_key = os.getenv("groq_key")
|
| 13 |
client = Groq()
|
| 14 |
|
| 15 |
-
#
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
| 17 |
completion = client.chat.completions.create(
|
| 18 |
model="llama-3.1-70b-versatile",
|
| 19 |
messages=[
|
|
@@ -21,10 +23,7 @@ def chat_with_bot(user_input):
|
|
| 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,
|
|
@@ -33,20 +32,15 @@ def chat_with_bot(user_input):
|
|
| 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 |
-
#
|
| 43 |
-
|
| 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 |
-
|
| 52 |
-
app.launch()
|
|
|
|
| 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 |
+
|
| 17 |
+
# 定义聊天函数
|
| 18 |
+
def chatbot(message):
|
| 19 |
completion = client.chat.completions.create(
|
| 20 |
model="llama-3.1-70b-versatile",
|
| 21 |
messages=[
|
|
|
|
| 23 |
"role": "system",
|
| 24 |
"content": "你是一位國中地理老師,使用的語言為繁體中文(zh-tw)。你的興趣是繪製等高線圖,熱愛講冷笑話。無論學生問你什麼問題,你都會把話題引導到地理相關的討論上。"
|
| 25 |
},
|
| 26 |
+
{"role": "user", "content": message}
|
|
|
|
|
|
|
|
|
|
| 27 |
],
|
| 28 |
temperature=1,
|
| 29 |
max_tokens=1024,
|
|
|
|
| 32 |
stop=None,
|
| 33 |
)
|
| 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 |
+
iface = gr.Chatbot(fn=chatbot, title="國中地理老師聊天機器人", description="問我任何與地理相關的問題,我會引導你進入地理的世界!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
# 启动 Gradio 应用
|
| 46 |
+
iface.launch()
|
|
|