Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -33,275 +33,4 @@ class IntelligentAgent:
|
|
33 |
Returns True if search is recommended, False otherwise.
|
34 |
"""
|
35 |
decision_prompt = f"""You are an AI assistant that decides whether a web search is needed to answer questions accurately.
|
36 |
-
|
37 |
-
Analyze this question and decide if it requires real-time information, recent data, or specific facts that might not be in your training data.
|
38 |
-
|
39 |
-
SEARCH IS NEEDED for:
|
40 |
-
- Current events, news, recent developments
|
41 |
-
- Real-time data (weather, stock prices, sports scores)
|
42 |
-
- Specific factual information that changes frequently
|
43 |
-
- Recent product releases, company information
|
44 |
-
- Current status of people, organizations, or projects
|
45 |
-
- Location-specific current information
|
46 |
-
|
47 |
-
SEARCH IS NOT NEEDED for:
|
48 |
-
- General knowledge questions
|
49 |
-
- Mathematical calculations
|
50 |
-
- Programming concepts and syntax
|
51 |
-
- Historical facts (older than 1 year)
|
52 |
-
- Definitions of well-established concepts
|
53 |
-
- How-to instructions for common tasks
|
54 |
-
- Creative writing or opinion-based responses
|
55 |
-
|
56 |
-
Question: "{question}"
|
57 |
-
|
58 |
-
Respond with only "SEARCH" or "NO_SEARCH" followed by a brief reason (max 20 words).
|
59 |
-
|
60 |
-
Example responses:
|
61 |
-
- "SEARCH - Current weather data needed"
|
62 |
-
- "NO_SEARCH - Mathematical concept, general knowledge sufficient"
|
63 |
-
"""
|
64 |
-
|
65 |
-
try:
|
66 |
-
response = self.client.text_generation(
|
67 |
-
decision_prompt,
|
68 |
-
max_new_tokens=50,
|
69 |
-
temperature=0.1,
|
70 |
-
do_sample=False
|
71 |
-
)
|
72 |
-
|
73 |
-
decision = response.strip().upper()
|
74 |
-
should_search = decision.startswith("SEARCH")
|
75 |
-
|
76 |
-
if self.debug:
|
77 |
-
print(f"Decision for '{question}': {decision}")
|
78 |
-
|
79 |
-
return should_search
|
80 |
-
|
81 |
-
except Exception as e:
|
82 |
-
if self.debug:
|
83 |
-
print(f"Error in search decision: {e}, defaulting to search")
|
84 |
-
# Default to search if decision fails
|
85 |
-
return True
|
86 |
-
|
87 |
-
def _answer_with_llm(self, question: str) -> str:
|
88 |
-
"""
|
89 |
-
Generate answer using LLM without search.
|
90 |
-
"""
|
91 |
-
answer_prompt = f"""You are a helpful AI assistant. Answer the following question based on your knowledge. Be accurate, concise, and helpful. If you're not certain about something, acknowledge the uncertainty.
|
92 |
-
|
93 |
-
Question: {question}
|
94 |
-
|
95 |
-
Answer:"""
|
96 |
-
|
97 |
-
try:
|
98 |
-
response = self.client.text_generation(
|
99 |
-
answer_prompt,
|
100 |
-
max_new_tokens=500,
|
101 |
-
temperature=0.3,
|
102 |
-
do_sample=True
|
103 |
-
)
|
104 |
-
return response.strip()
|
105 |
-
|
106 |
-
except Exception as e:
|
107 |
-
return f"Sorry, I encountered an error generating the response: {e}"
|
108 |
-
|
109 |
-
def _answer_with_search(self, question: str) -> str:
|
110 |
-
"""
|
111 |
-
Generate answer using search results and LLM.
|
112 |
-
"""
|
113 |
-
try:
|
114 |
-
# Perform search
|
115 |
-
search_results = self.search(question)
|
116 |
-
|
117 |
-
if not search_results:
|
118 |
-
return "No search results found. Let me try to answer based on my knowledge:\n\n" + self._answer_with_llm(question)
|
119 |
-
|
120 |
-
# Format search results
|
121 |
-
formatted_results = []
|
122 |
-
for i, result in enumerate(search_results[:3]): # Use top 3 results
|
123 |
-
title = result.get("title", "No title")
|
124 |
-
snippet = result.get("snippet", "").strip()
|
125 |
-
link = result.get("link", "")
|
126 |
-
|
127 |
-
formatted_results.append(f"Result {i+1}:\nTitle: {title}\nContent: {snippet}\nSource: {link}")
|
128 |
-
|
129 |
-
search_context = "\n\n".join(formatted_results)
|
130 |
-
|
131 |
-
# Generate answer using search context
|
132 |
-
answer_prompt = f"""You are a helpful AI assistant. Use the provided search results to answer the question accurately. Synthesize information from multiple sources when relevant, and cite sources when appropriate.
|
133 |
-
|
134 |
-
Question: {question}
|
135 |
-
|
136 |
-
Search Results:
|
137 |
-
{search_context}
|
138 |
-
|
139 |
-
Based on the search results above, provide a comprehensive answer to the question. If the search results don't fully answer the question, you can supplement with your general knowledge but clearly indicate what comes from the search results vs. your knowledge.
|
140 |
-
|
141 |
-
Answer:"""
|
142 |
-
|
143 |
-
try:
|
144 |
-
response = self.client.text_generation(
|
145 |
-
answer_prompt,
|
146 |
-
max_new_tokens=600,
|
147 |
-
temperature=0.3,
|
148 |
-
do_sample=True
|
149 |
-
)
|
150 |
-
return response.strip()
|
151 |
-
|
152 |
-
except Exception as e:
|
153 |
-
# Fallback to simple search result formatting
|
154 |
-
top_result = search_results[0]
|
155 |
-
title = top_result.get("title", "No title")
|
156 |
-
snippet = top_result.get("snippet", "").strip()
|
157 |
-
link = top_result.get("link", "")
|
158 |
-
|
159 |
-
return f"**{title}**\n\n{snippet}\n\nSource: {link}"
|
160 |
-
|
161 |
-
except Exception as e:
|
162 |
-
return f"Search failed: {e}. Let me try to answer based on my knowledge:\n\n" + self._answer_with_llm(question)
|
163 |
-
|
164 |
-
def __call__(self, question: str) -> str:
|
165 |
-
"""
|
166 |
-
Main entry point - decide whether to search and generate appropriate response.
|
167 |
-
"""
|
168 |
-
if self.debug:
|
169 |
-
print(f"Agent received question: {question}")
|
170 |
-
|
171 |
-
# Early validation
|
172 |
-
if not question or not question.strip():
|
173 |
-
return "Please provide a valid question."
|
174 |
-
|
175 |
-
try:
|
176 |
-
# Decide whether to search
|
177 |
-
if self._should_search(question):
|
178 |
-
if self.debug:
|
179 |
-
print("Using search-based approach")
|
180 |
-
answer = self._answer_with_search(question)
|
181 |
-
else:
|
182 |
-
if self.debug:
|
183 |
-
print("Using LLM-only approach")
|
184 |
-
answer = self._answer_with_llm(question)
|
185 |
-
|
186 |
-
except Exception as e:
|
187 |
-
answer = f"Sorry, I encountered an error: {e}"
|
188 |
-
|
189 |
-
if self.debug:
|
190 |
-
print(f"Agent returning answer: {answer[:100]}...")
|
191 |
-
|
192 |
-
return answer
|
193 |
-
|
194 |
-
def fetch_questions() -> Tuple[str, Optional[pd.DataFrame]]:
|
195 |
-
"""
|
196 |
-
Fetch questions from the API and cache them.
|
197 |
-
"""
|
198 |
-
global cached_questions
|
199 |
-
|
200 |
-
api_url = DEFAULT_API_URL
|
201 |
-
questions_url = f"{api_url}/questions"
|
202 |
-
|
203 |
-
print(f"Fetching questions from: {questions_url}")
|
204 |
-
try:
|
205 |
-
response = requests.get(questions_url, timeout=15)
|
206 |
-
response.raise_for_status()
|
207 |
-
questions_data = response.json()
|
208 |
-
|
209 |
-
if not questions_data:
|
210 |
-
return "Fetched questions list is empty.", None
|
211 |
-
|
212 |
-
cached_questions = questions_data
|
213 |
-
|
214 |
-
# Create DataFrame for display
|
215 |
-
display_data = []
|
216 |
-
for item in questions_data:
|
217 |
-
display_data.append({
|
218 |
-
"Task ID": item.get("task_id", "Unknown"),
|
219 |
-
"Question": item.get("question", "")
|
220 |
-
})
|
221 |
-
|
222 |
-
df = pd.DataFrame(display_data)
|
223 |
-
status_msg = f"Successfully fetched {len(questions_data)} questions. Ready to generate answers."
|
224 |
-
|
225 |
-
return status_msg, df
|
226 |
-
|
227 |
-
except requests.exceptions.RequestException as e:
|
228 |
-
return f"Error fetching questions: {e}", None
|
229 |
-
except Exception as e:
|
230 |
-
return f"An unexpected error occurred: {e}", None
|
231 |
-
|
232 |
-
def generate_answers_async(model_name: str = "meta-llama/Llama-3.1-8B-Instruct", progress_callback=None):
|
233 |
-
"""
|
234 |
-
Generate answers for all cached questions asynchronously using the intelligent agent.
|
235 |
-
"""
|
236 |
-
global cached_answers, processing_status
|
237 |
-
|
238 |
-
if not cached_questions:
|
239 |
-
return "No questions available. Please fetch questions first."
|
240 |
-
|
241 |
-
processing_status["is_processing"] = True
|
242 |
-
processing_status["progress"] = 0
|
243 |
-
processing_status["total"] = len(cached_questions)
|
244 |
-
|
245 |
-
try:
|
246 |
-
agent = IntelligentAgent(debug=True, model_name=model_name)
|
247 |
-
cached_answers = {}
|
248 |
-
|
249 |
-
for i, item in enumerate(cached_questions):
|
250 |
-
if not processing_status["is_processing"]: # Check if cancelled
|
251 |
-
break
|
252 |
-
|
253 |
-
task_id = item.get("task_id")
|
254 |
-
question_text = item.get("question")
|
255 |
-
|
256 |
-
if not task_id or question_text is None:
|
257 |
-
continue
|
258 |
-
|
259 |
-
try:
|
260 |
-
answer = agent(question_text)
|
261 |
-
cached_answers[task_id] = {
|
262 |
-
"question": question_text,
|
263 |
-
"answer": answer
|
264 |
-
}
|
265 |
-
except Exception as e:
|
266 |
-
cached_answers[task_id] = {
|
267 |
-
"question": question_text,
|
268 |
-
"answer": f"AGENT ERROR: {e}"
|
269 |
-
}
|
270 |
-
|
271 |
-
processing_status["progress"] = i + 1
|
272 |
-
if progress_callback:
|
273 |
-
progress_callback(i + 1, len(cached_questions))
|
274 |
-
|
275 |
-
except Exception as e:
|
276 |
-
print(f"Error in generate_answers_async: {e}")
|
277 |
-
finally:
|
278 |
-
processing_status["is_processing"] = False
|
279 |
-
|
280 |
-
def start_answer_generation(model_choice: str):
|
281 |
-
"""
|
282 |
-
Start the answer generation process in a separate thread.
|
283 |
-
"""
|
284 |
-
if processing_status["is_processing"]:
|
285 |
-
return "Answer generation is already in progress.", None
|
286 |
-
|
287 |
-
if not cached_questions:
|
288 |
-
return "No questions available. Please fetch questions first.", None
|
289 |
-
|
290 |
-
# Map model choice to actual model name
|
291 |
-
model_map = {
|
292 |
-
"Llama 3.1 8B": "meta-llama/Llama-3.1-8B-Instruct",
|
293 |
-
"Llama 3.1 70B": "meta-llama/Llama-3.1-70B-Instruct",
|
294 |
-
"Mistral 7B": "mistralai/Mistral-7B-Instruct-v0.3",
|
295 |
-
"CodeLlama 7B": "codellama/CodeLlama-7b-Instruct-hf"
|
296 |
-
}
|
297 |
-
|
298 |
-
selected_model = model_map.get(model_choice, "meta-llama/Llama-3.1-8B-Instruct")
|
299 |
-
|
300 |
-
# Start generation in background thread
|
301 |
-
thread = threading.Thread(target=generate_answers_async, args=(selected_model,))
|
302 |
-
thread.daemon = True
|
303 |
-
thread.start()
|
304 |
-
|
305 |
-
return f"Answer generation started using {model_choice}. Check progress below.", None
|
306 |
-
|
307 |
-
def get_generation_progre
|
|
|
33 |
Returns True if search is recommended, False otherwise.
|
34 |
"""
|
35 |
decision_prompt = f"""You are an AI assistant that decides whether a web search is needed to answer questions accurately.
|
36 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|