WingYip commited on
Commit
20e8876
·
verified ·
1 Parent(s): 80771f6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -12
app.py CHANGED
@@ -8,30 +8,58 @@ client = OpenAI(
8
  api_key=os.getenv("OPENROUTER_API_KEY"),
9
  )
10
 
11
- # Chatbot 回覆邏輯
12
- def chatbot_reply(message, history=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  try:
14
  response = client.chat.completions.create(
15
- model="mistralai/mistral-small-3.1-24b-instruct:free", # 建議用穩定模型
16
  messages=[
17
- {"role": "system", "content": "你是一位校園小老師,只回答學校生活相關問題,並且每次回答不多於100字。"},
18
- {"role": "user", "content": message}
 
 
 
 
 
 
19
  ],
20
  extra_headers={
21
- "HTTP-Referer": "https://your-education-workshop.com", # 可選
22
- "X-Title": "AI Chatbot Demo", # 可選
23
  },
24
- max_tokens=256 # 限制輸出長度,避免 content-length 問題
25
  )
26
  reply = response.choices[0].message.content
27
  return reply.strip()
 
28
  except Exception as e:
29
  return f"發生錯誤:{str(e)}"
30
 
31
- # Gradio Web App
32
  gr.ChatInterface(
33
  fn=chatbot_reply,
34
- title="校園小老師 Chatbot",
35
- theme="soft",
36
- description="請輸入關於學校生活的問題,我會盡量幫你解答!(提示:)",
37
  ).launch()
 
8
  api_key=os.getenv("OPENROUTER_API_KEY"),
9
  )
10
 
11
+ # 自訂知識庫(key = 主題關鍵字, value = 資料內容)
12
+ knowledge_base = {
13
+ "午餐": "我們學校提供兩輪午餐時間。第一輪是12:15-12:45,第二輪是12:45-13:15。菜單每週更新,可在校網查閱。",
14
+ "課外活動": "我們的課外活動包括足球、籃球、辯論、機械人編程等,活動時間是放學後 3:30 至 5:00。",
15
+ "圖書館": "圖書館平日開放時間為早上8:30至下午4:30。借書需使用學生證,每次最多借3本,期限為兩週。",
16
+ "校車": "校車每日早上7:30從主要地鐵站出發,下午放學後15分鐘內發車,請準時到指定上車地點。",
17
+ }
18
+
19
+ # 根據輸入問題比對知識庫,回傳對應資料串成 prompt
20
+ def search_kb(question: str) -> str:
21
+ matched_info = []
22
+ for keyword, content in knowledge_base.items():
23
+ if keyword in question:
24
+ matched_info.append(f"{keyword}:{content}")
25
+ if matched_info:
26
+ return "以下是你可能需要的學校資料:\n" + "\n".join(matched_info)
27
+ else:
28
+ return "找不到相關資料,請直接由 Chatbot 回答。"
29
+
30
+ # Chatbot 回覆邏輯:將知識庫資訊加入 system prompt
31
+ def chatbot_reply(user_input, history=None):
32
+ kb_prompt = search_kb(user_input)
33
+
34
  try:
35
  response = client.chat.completions.create(
36
+ model="mistralai/mistral-small-3.1-24b-instruct:free",
37
  messages=[
38
+ {
39
+ "role": "system",
40
+ "content": f"你是一位校園小老師,根據以下學校資料回答問題:\n{kb_prompt}"
41
+ },
42
+ {
43
+ "role": "user",
44
+ "content": user_input
45
+ }
46
  ],
47
  extra_headers={
48
+ "HTTP-Referer": "https://your-education-workshop.com",
49
+ "X-Title": "AI Chatbot with Knowledge Base",
50
  },
51
+ max_tokens=300
52
  )
53
  reply = response.choices[0].message.content
54
  return reply.strip()
55
+
56
  except Exception as e:
57
  return f"發生錯誤:{str(e)}"
58
 
59
+ # Gradio Web Chat App
60
  gr.ChatInterface(
61
  fn=chatbot_reply,
62
+ title="校園小老師 Chatbot (知識庫版)",
63
+ description="請輸入關於學校生活的問題(如:課外活動、午餐、圖書館、校車),AI 小老師會回答你!",
64
+ theme="soft"
65
  ).launch()