manasagangotri commited on
Commit
b7b20e2
ยท
verified ยท
1 Parent(s): 09185e4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +118 -0
app.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import dspy
3
+ import torch
4
+ import requests
5
+ from transformers import pipeline
6
+ from sentence_transformers import SentenceTransformer
7
+ from qdrant_client import QdrantClient
8
+ from datetime import datetime
9
+ import json
10
+
11
+ # === Load Models ===
12
+ classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
13
+ embedding_model = SentenceTransformer("intfloat/e5-large")
14
+ qa_pipeline = pipeline("text-generation", model="WizardLM/WizardMath-7B-V1.0", device_map="auto", torch_dtype=torch.float16)
15
+
16
+ # === Qdrant Setup ===
17
+ qdrant_client = QdrantClient(path="qdrant_data")
18
+ collection_name = "math_problems"
19
+
20
+ # === Guard Function ===
21
+ def is_valid_math_question(text):
22
+ candidate_labels = ["math", "not math"]
23
+ result = classifier(text, candidate_labels)
24
+ return result['labels'][0] == "math" and result['scores'][0] > 0.7
25
+
26
+ # === Retrieval ===
27
+ def retrieve_from_qdrant(query):
28
+ query_vector = embedding_model.encode(query).tolist()
29
+ hits = qdrant_client.search(collection_name=collection_name, query_vector=query_vector, limit=3)
30
+ return [hit.payload for hit in hits] if hits else []
31
+
32
+ # === Web Search ===
33
+ def web_search_tavily(query):
34
+ TAVILY_API_KEY = "your_tavily_api_key"
35
+ response = requests.post(
36
+ "https://api.tavily.com/search",
37
+ json={"api_key": TAVILY_API_KEY, "query": query, "search_depth": "advanced"},
38
+ )
39
+ return response.json().get("answer", "No answer found from Tavily.")
40
+
41
+ # === DSPy Signature ===
42
+ class MathAnswer(dspy.Signature):
43
+ question = dspy.InputField()
44
+ retrieved_context = dspy.InputField()
45
+ answer = dspy.OutputField()
46
+
47
+ # === DSPy Programs ===
48
+ class MathRetrievalQA(dspy.Program):
49
+ def forward(self, question):
50
+ context_items = retrieve_from_qdrant(question)
51
+ context = "\n".join([item["solution"] for item in context_items if "solution" in item])
52
+ if not context:
53
+ return dspy.Output(answer="", retrieved_context="")
54
+ prompt = f"Question: {question}\nContext: {context}\nAnswer:"
55
+ answer = qa_pipeline(prompt, max_new_tokens=512)[0]["generated_text"]
56
+ return dspy.Output(answer=answer, retrieved_context=context)
57
+
58
+ class WebFallbackQA(dspy.Program):
59
+ def forward(self, question):
60
+ answer = web_search_tavily(question)
61
+ return dspy.Output(answer=answer, retrieved_context="Tavily")
62
+
63
+ class MathRouter(dspy.Program):
64
+ def forward(self, question):
65
+ if not is_valid_math_question(question):
66
+ return dspy.Output(answer="โŒ Only math questions are accepted. Please rephrase.", retrieved_context="")
67
+ result = MathRetrievalQA().forward(question)
68
+ return result if result.answer else WebFallbackQA().forward(question)
69
+
70
+ router = MathRouter()
71
+
72
+ # === Feedback Storage ===
73
+ def store_feedback(question, answer, feedback, correct_answer):
74
+ entry = {
75
+ "question": question,
76
+ "model_answer": answer,
77
+ "feedback": feedback,
78
+ "correct_answer": correct_answer,
79
+ "timestamp": str(datetime.now())
80
+ }
81
+ with open("feedback.json", "a") as f:
82
+ f.write(json.dumps(entry) + "\n")
83
+
84
+ # === Gradio Functions ===
85
+ def ask_question(question):
86
+ result = router.forward(question)
87
+ return result.answer, question, result.answer
88
+
89
+ def submit_feedback(question, model_answer, feedback, correct_answer):
90
+ store_feedback(question, model_answer, feedback, correct_answer)
91
+ return "โœ… Feedback received. Thank you!"
92
+
93
+ # === Gradio UI ===
94
+ with gr.Blocks() as demo:
95
+ gr.Markdown("## ๐Ÿงฎ Math Question Answering with DSPy + Feedback")
96
+
97
+ with gr.Tab("Ask a Math Question"):
98
+ with gr.Row():
99
+ question_input = gr.Textbox(label="Enter your math question", lines=2)
100
+ answer_output = gr.Markdown(label="Answer")
101
+ hidden_q = gr.Textbox(visible=False)
102
+ hidden_a = gr.Textbox(visible=False)
103
+ submit_btn = gr.Button("Get Answer")
104
+ submit_btn.click(fn=ask_question, inputs=[question_input], outputs=[answer_output, hidden_q, hidden_a])
105
+
106
+ with gr.Tab("Submit Feedback"):
107
+ gr.Markdown("### Was the answer helpful?")
108
+ fb_question = gr.Textbox(label="Original Question")
109
+ fb_answer = gr.Textbox(label="Model's Answer")
110
+ fb_like = gr.Radio(["๐Ÿ‘", "๐Ÿ‘Ž"], label="Your Feedback")
111
+ fb_correct = gr.Textbox(label="Correct Answer (optional)")
112
+ fb_submit_btn = gr.Button("Submit Feedback")
113
+ fb_status = gr.Textbox(label="Status", interactive=False)
114
+ fb_submit_btn.click(fn=submit_feedback,
115
+ inputs=[fb_question, fb_answer, fb_like, fb_correct],
116
+ outputs=[fb_status])
117
+
118
+ demo.launch()