Howarddddd commited on
Commit
9aa8153
·
verified ·
1 Parent(s): 841bded

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -53
app.py CHANGED
@@ -1,64 +1,63 @@
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
 
27
 
28
- response = ""
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
 
39
- response += token
40
- yield response
41
 
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
  """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
-
62
 
63
- if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
  import gradio as gr
3
+ from langchain_community.vectorstores import FAISS
4
+ from langchain_community.embeddings import HuggingFaceEmbeddings
5
+ from openai import OpenAI
 
 
 
6
 
7
+ class CustomE5Embedding(HuggingFaceEmbeddings):
8
+ def embed_documents(self, texts):
9
+ texts = [f"passage: {t}" for t in texts]
10
+ return super().embed_documents(texts)
11
 
12
+ def embed_query(self, text):
13
+ return super().embed_query(f"query: {text}")
 
 
 
 
 
 
 
14
 
15
+ embedding_model = CustomE5Embedding(model_name="intfloat/multilingual-e5-small")
16
+ db = FAISS.load_local("faiss_db", embedding_model, allow_dangerous_deserialization=True)
17
+ retriever = db.as_retriever(search_kwargs={"k": 20})
 
 
18
 
19
+ client = OpenAI()
20
+ model = "gpt-4o"
21
 
22
+ system_prompt = "你是清華大學校園資訊助理 AI,專門解答與課程、社團、場地與設施時段相關的問題。請根據資料內容,以台灣人熟悉的繁體中文提供清楚、簡潔且實用的回應。如無法在資料中找到答案,請誠實說明。"
23
 
24
+ prompt_template = """以下是關於國立清華大學課程、社團與校內設施的資料片段:
25
+ {retrieved_chunks}
 
 
 
 
 
 
26
 
27
+ 使用者的提問是:{question}
 
28
 
29
+ 請根據提供的內容回答問題,若提到課程請具體指出課程名稱、教師或時間地點;若提到社團或場地,也請回應具體活動內容或使用時段。
30
+ 如查無相關資訊,請明確告知查無資料。
 
31
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
+ def chat_with_rag(user_input):
34
+ docs = retriever.get_relevant_documents(user_input)
35
+ retrieved_chunks = "\n\n".join([doc.page_content for doc in docs])
36
+ final_prompt = prompt_template.format(retrieved_chunks=retrieved_chunks, question=user_input)
37
+
38
+ response = client.chat.completions.create(
39
+ model=model,
40
+ max_tokens=1000,
41
+ messages=[
42
+ {"role": "system", "content": system_prompt},
43
+ {"role": "assistant", "content": f"以下是相關資料片段:\n\n{retrieved_chunks}"},
44
+ {"role": "user", "content": f"問題:{user_input}\n\n請根據資料,詳細列出所有相關內容,包括課程名稱、授課教師、時間地點等,必要時請使用條列式說明。若查無資料,也請清楚說明。"}
45
+ ]
46
+ )
47
+ return response.choices[0].message.content
48
+
49
+ with gr.Blocks() as demo:
50
+ gr.Markdown("# 🎓 校園資訊查詢小幫手")
51
+ gr.Markdown("請輸入你想詢問的清華大學的問題,包含資工系課程、校園設施、社團,我會根據資料幫你解答 💬")
52
+
53
+ chatbot = gr.Chatbot(label="📚 問答紀錄", height=600)
54
+ msg = gr.Textbox(placeholder="例如:大一有哪些必修課?", label="❓ 問題輸入")
55
+
56
+ def respond(message, chat_history_local):
57
+ response = chat_with_rag(message)
58
+ chat_history_local.append((message, response))
59
+ return "", chat_history_local
60
+
61
+ msg.submit(respond, [msg, chatbot], [msg, chatbot])
62
+
63
+ demo.launch()