Cudd1es commited on
Commit
05ddcd3
·
1 Parent(s): eaa42b1

app.py updated

Browse files
Files changed (1) hide show
  1. app.py +67 -58
app.py CHANGED
@@ -1,70 +1,79 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
-
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
- """
15
- 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
16
- """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
 
19
- messages = [{"role": "system", "content": system_message}]
 
20
 
21
- messages.extend(history)
 
 
22
 
23
- messages.append({"role": "user", "content": message})
 
 
24
 
25
- response = ""
 
 
26
 
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = 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
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
- )
62
 
63
- with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
 
 
67
 
 
68
 
69
- if __name__ == "__main__":
70
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import os
3
+ from openai import OpenAI
4
+ from retriever import (
5
+ load_collection, load_encoder, encode_query, retrieve_docs,
6
+ query_rerank, expand_with_neighbors, dedup_by_chapter_event
7
+ )
8
+ from sentence_transformers import CrossEncoder
 
 
 
 
 
 
 
 
 
9
 
10
+ api_key = os.getenv("OPENAI_API_KEY")
11
+ client = OpenAI(api_key=api_key)
12
 
13
+ collection = load_collection()
14
+ encoder = load_encoder()
15
+ reranker = CrossEncoder("BAAI/bge-reranker-large")
16
 
17
+ def build_rag_prompt(query, context):
18
+ prompt = f"""已知资料如下:
19
+ {context}
20
 
21
+ 用户提问:{query}
22
+ 请参考所有已知资料, 并结合资料内容,简明、准确地回答问题。如果有多个符合的答案, 可以根据你是否确定而决定是否分别陈述这些答案.如果不能确定答案,请如实说明理由,不要凭空编造。"""
23
+ return prompt
24
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
+ def answer_fn(query, history=None):
27
+ query_vec = encode_query(encoder, query)
28
+ results = retrieve_docs(collection, query_vec, top_k=30)
29
+ reranked = query_rerank(reranker, query, results, top_n=10)
30
+ deduped = dedup_by_chapter_event(reranked, max_per_group=1)
31
+ expanded_results = expand_with_neighbors(deduped[:3], collection)
32
 
33
+ context = expanded_results[0][0] if expanded_results else ""
34
+ rag_prompt = build_rag_prompt(query, context)
35
+ system_prompt = "你是BangDream知识问答助手, 也就是邦学家. 只能基于提供的资料内容作答。"
36
 
37
+ response = client.chat.completions.create(
38
+ model="gpt-4o",
39
+ messages=[
40
+ {"role": "system", "content": system_prompt},
41
+ {"role": "user", "content": rag_prompt}
42
+ ],
43
+ temperature=0.2,
44
+ max_tokens=512,
45
+ )
46
+ answer = response.choices[0].message.content.strip()
 
 
 
 
 
 
 
 
 
47
 
48
+ references = ""
49
+ for idx, (doc, score, meta) in enumerate(expanded_results, 1):
50
+ chapter = meta.get("chapterTitle", "UnknownChapter")
51
+ event = meta.get("eventName", "UnknownEvent")
52
+ references += f"\n--- reference: {idx} (chapter: {chapter}, event: {event}, score={score:.4f}) ---\n"
53
+ references += doc[:300] + "...\n"
54
 
55
+ return answer, references
56
 
57
+ # Gradio UI
58
+ with gr.Blocks(title="Dr-Bang RAG QA") as demo:
59
+ gr.Markdown("# Dr-Bang RAG QA\n\n基于BangDream知识库的RAG问答系统。")
60
+ with gr.Row():
61
+ chatbot = gr.ChatInterface(
62
+ fn=answer_fn,
63
+ title="Dr-Bang RAG Chat",
64
+ description="输入你有关BangDream的问题,邦学家会基于资料库为你检索并作答。",
65
+ additional_inputs=[],
66
+ retry_btn=None,
67
+ undo_btn=None,
68
+ clear_btn="clear",
69
+ examples=[
70
+ ["乐奈为什么喜欢吉他?"],
71
+ ["LOCK和CHU²第一次见面是什么情节?"],
72
+ ["谁是RAS的初代成员?"],
73
+ ],
74
+ outputs=[
75
+ gr.Textbox(label="Answer", lines=6, interactive=False),
76
+ gr.Textbox(label="Reference", lines=8, interactive=False)
77
+ ]
78
+ )
79
+ demo.launch()