tatianija commited on
Commit
1b2a135
·
verified ·
1 Parent(s): f003351

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +509 -1
app.py CHANGED
@@ -33,4 +33,512 @@ 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
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_progress():
308
+ """
309
+ Get the current progress of answer generation.
310
+ """
311
+ if not processing_status["is_processing"] and processing_status["progress"] == 0:
312
+ return "Not started", None
313
+
314
+ if processing_status["is_processing"]:
315
+ progress = processing_status["progress"]
316
+ total = processing_status["total"]
317
+ status_msg = f"Generating answers... {progress}/{total} completed"
318
+ return status_msg, None
319
+ else:
320
+ # Generation completed
321
+ if cached_answers:
322
+ # Create DataFrame with results
323
+ display_data = []
324
+ for task_id, data in cached_answers.items():
325
+ display_data.append({
326
+ "Task ID": task_id,
327
+ "Question": data["question"][:100] + "..." if len(data["question"]) > 100 else data["question"],
328
+ "Generated Answer": data["answer"][:200] + "..." if len(data["answer"]) > 200 else data["answer"]
329
+ })
330
+
331
+ df = pd.DataFrame(display_data)
332
+ status_msg = f"Answer generation completed! {len(cached_answers)} answers ready for submission."
333
+ return status_msg, df
334
+ else:
335
+ return "Answer generation completed but no answers were generated.", None
336
+
337
+ def submit_cached_answers(profile: gr.OAuthProfile | None):
338
+ """
339
+ Submit the cached answers to the evaluation API.
340
+ """
341
+ global cached_answers
342
+
343
+ if not profile:
344
+ return "Please log in to Hugging Face first.", None
345
+
346
+ if not cached_answers:
347
+ return "No cached answers available. Please generate answers first.", None
348
+
349
+ username = profile.username
350
+ space_id = os.getenv("SPACE_ID")
351
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Unknown"
352
+
353
+ # Prepare submission payload
354
+ answers_payload = []
355
+ for task_id, data in cached_answers.items():
356
+ answers_payload.append({
357
+ "task_id": task_id,
358
+ "submitted_answer": data["answer"]
359
+ })
360
+
361
+ submission_data = {
362
+ "username": username.strip(),
363
+ "agent_code": agent_code,
364
+ "answers": answers_payload
365
+ }
366
+
367
+ # Submit to API
368
+ api_url = DEFAULT_API_URL
369
+ submit_url = f"{api_url}/submit"
370
+
371
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
372
+
373
+ try:
374
+ response = requests.post(submit_url, json=submission_data, timeout=60)
375
+ response.raise_for_status()
376
+ result_data = response.json()
377
+
378
+ final_status = (
379
+ f"Submission Successful!\n"
380
+ f"User: {result_data.get('username')}\n"
381
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
382
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
383
+ f"Message: {result_data.get('message', 'No message received.')}"
384
+ )
385
+
386
+ # Create results DataFrame
387
+ results_log = []
388
+ for task_id, data in cached_answers.items():
389
+ results_log.append({
390
+ "Task ID": task_id,
391
+ "Question": data["question"],
392
+ "Submitted Answer": data["answer"]
393
+ })
394
+
395
+ results_df = pd.DataFrame(results_log)
396
+ return final_status, results_df
397
+
398
+ except requests.exceptions.HTTPError as e:
399
+ error_detail = f"Server responded with status {e.response.status_code}."
400
+ try:
401
+ error_json = e.response.json()
402
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
403
+ except:
404
+ error_detail += f" Response: {e.response.text[:500]}"
405
+ return f"Submission Failed: {error_detail}", None
406
+
407
+ except requests.exceptions.Timeout:
408
+ return "Submission Failed: The request timed out.", None
409
+
410
+ except Exception as e:
411
+ return f"Submission Failed: {e}", None
412
+
413
+ def clear_cache():
414
+ """
415
+ Clear all cached data.
416
+ """
417
+ global cached_answers, cached_questions, processing_status
418
+ cached_answers = {}
419
+ cached_questions = []
420
+ processing_status = {"is_processing": False, "progress": 0, "total": 0}
421
+ return "Cache cleared successfully.", None
422
+
423
+ def test_single_question(question: str, model_choice: str):
424
+ """Test the agent with a single question."""
425
+ if not question.strip():
426
+ return "Please enter a question to test."
427
+
428
+ # Map model choice to actual model name
429
+ model_map = {
430
+ "Llama 3.1 8B": "meta-llama/Llama-3.1-8B-Instruct",
431
+ "Llama 3.1 70B": "meta-llama/Llama-3.1-70B-Instruct",
432
+ "Mistral 7B": "mistralai/Mistral-7B-Instruct-v0.3",
433
+ "CodeLlama 7B": "codellama/CodeLlama-7b-Instruct-hf"
434
+ }
435
+
436
+ selected_model = model_map.get(model_choice, "meta-llama/Llama-3.1-8B-Instruct")
437
+
438
+ try:
439
+ agent = IntelligentAgent(debug=True, model_name=selected_model)
440
+ answer = agent(question)
441
+ return f"**Answer using {model_choice}:**\n\n{answer}"
442
+ except Exception as e:
443
+ return f"Error testing question: {e}"
444
+
445
+ # --- Enhanced Gradio Interface ---
446
+ with gr.Blocks(title="Intelligent Agent with Conditional Search") as demo:
447
+ gr.Markdown("# Intelligent Agent with Conditional Search")
448
+ gr.Markdown("This agent uses an LLM to decide when search is needed, optimizing for both accuracy and efficiency.")
449
+
450
+ with gr.Row():
451
+ gr.LoginButton()
452
+ clear_btn = gr.Button("Clear Cache", variant="secondary")
453
+
454
+ with gr.Tab("Test Single Question"):
455
+ gr.Markdown("### Test the Agent with a Single Question")
456
+ with gr.Row():
457
+ test_question = gr.Textbox(
458
+ label="Enter your question",
459
+ placeholder="e.g., What is the current weather in Paris? or What is machine learning?",
460
+ lines=2
461
+ )
462
+ test_model = gr.Dropdown(
463
+ choices=["Llama 3.1 8B", "Llama 3.1 70B", "Mistral 7B", "CodeLlama 7B"],
464
+ value="Llama 3.1 8B",
465
+ label="Select Model"
466
+ )
467
+
468
+ test_btn = gr.Button("Test Question", variant="primary")
469
+ test_result = gr.Textbox(label="Agent Response", lines=10, interactive=False)
470
+
471
+ test_btn.click(
472
+ fn=test_single_question,
473
+ inputs=[test_question, test_model],
474
+ outputs=[test_result]
475
+ )
476
+
477
+ with gr.Tab("Step 1: Fetch Questions"):
478
+ gr.Markdown("### Fetch Questions from API")
479
+ fetch_btn = gr.Button("Fetch Questions", variant="primary")
480
+ fetch_status = gr.Textbox(label="Fetch Status", lines=2, interactive=False)
481
+ questions_table = gr.DataFrame(label="Available Questions", wrap=True)
482
+
483
+ fetch_btn.click(
484
+ fn=fetch_questions,
485
+ outputs=[fetch_status, questions_table]
486
+ )
487
+
488
+ with gr.Tab("Step 2: Generate Answers"):
489
+ gr.Markdown("### Generate Answers with Intelligent Search Decision")
490
+
491
+ with gr.Row():
492
+ model_choice = gr.Dropdown(
493
+ choices=["Llama 3.1 8B", "Llama 3.1 70B", "Mistral 7B", "CodeLlama 7B"],
494
+ value="Llama 3.1 8B",
495
+ label="Select Model"
496
+ )
497
+ generate_btn = gr.Button("Start Answer Generation", variant="primary")
498
+ refresh_btn = gr.Button("Refresh Progress", variant="secondary")
499
+
500
+ generation_status = gr.Textbox(label="Generation Status", lines=2, interactive=False)
501
+ answers_preview = gr.DataFrame(label="Generated Answers Preview", wrap=True)
502
+
503
+ generate_btn.click(
504
+ fn=start_answer_generation,
505
+ inputs=[model_choice],
506
+ outputs=[generation_status, answers_preview]
507
+ )
508
+
509
+ refresh_btn.click(
510
+ fn=get_generation_progress,
511
+ outputs=[generation_status, answers_preview]
512
+ )
513
+
514
+ with gr.Tab("Step 3: Submit Results"):
515
+ gr.Markdown("### Submit Generated Answers")
516
+ submit_btn = gr.Button("Submit Cached Answers", variant="primary")
517
+ submission_status = gr.Textbox(label="Submission Status", lines=5, interactive=False)
518
+ final_results = gr.DataFrame(label="Final Submission Results", wrap=True)
519
+
520
+ submit_btn.click(
521
+ fn=submit_cached_answers,
522
+ outputs=[submission_status, final_results]
523
+ )
524
+
525
+ # Clear cache functionality
526
+ clear_btn.click(
527
+ fn=clear_cache,
528
+ outputs=[fetch_status, questions_table]
529
+ )
530
+
531
+ # Auto-refresh progress every 5 seconds when generation is active
532
+ demo.load(
533
+ fn=get_generation_progress,
534
+ outputs=[generation_status, answers_preview]
535
+ )
536
+
537
+ if __name__ == "__main__":
538
+ print("\n" + "-"*30 + " Intelligent Agent Starting " + "-"*30)
539
+
540
+ space_host_startup = os.getenv("SPACE_HOST")
541
+ space_id_startup = os.getenv("SPACE_ID")
542
+
543
+ if space_host_startup:
544
+ print(f"✅ SPACE_HOST foun