Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,627 +1,224 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
import requests
|
| 4 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
import re
|
| 6 |
-
import time
|
| 7 |
-
import json
|
| 8 |
-
from bs4 import BeautifulSoup
|
| 9 |
|
| 10 |
-
#
|
| 11 |
-
|
| 12 |
-
SERPER_API_KEY = "
|
|
|
|
| 13 |
|
| 14 |
-
#
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
|
|
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
self.debug_print(f"Searching Google via Serper API for: {query}")
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
# Make the request
|
| 46 |
-
response = requests.post(serper_url, headers=headers, json=payload, timeout=10)
|
| 47 |
-
self.debug_print(f"Serper API response code: {response.status_code}")
|
| 48 |
-
|
| 49 |
-
if response.status_code == 200:
|
| 50 |
-
search_data = response.json()
|
| 51 |
-
|
| 52 |
-
# Extract organic search results
|
| 53 |
-
results = []
|
| 54 |
-
|
| 55 |
-
# Process answer box if available (highest priority)
|
| 56 |
-
if 'answerBox' in search_data:
|
| 57 |
-
answer_box = search_data['answerBox']
|
| 58 |
-
title = answer_box.get('title', 'Answer Box')
|
| 59 |
-
answer = answer_box.get('answer', '')
|
| 60 |
-
snippet = answer_box.get('snippet', '')
|
| 61 |
-
|
| 62 |
-
# Use the most informative part
|
| 63 |
-
content = answer if answer else snippet
|
| 64 |
-
|
| 65 |
-
if content:
|
| 66 |
-
results.append({
|
| 67 |
-
'title': title,
|
| 68 |
-
'content': content,
|
| 69 |
-
'url': answer_box.get('link', ''),
|
| 70 |
-
'type': 'answerBox'
|
| 71 |
-
})
|
| 72 |
-
self.debug_print(f"Added answer box: {title}")
|
| 73 |
-
|
| 74 |
-
# Process knowledge graph if available
|
| 75 |
-
if 'knowledgeGraph' in search_data:
|
| 76 |
-
kg = search_data['knowledgeGraph']
|
| 77 |
-
title = kg.get('title', 'Knowledge Graph')
|
| 78 |
-
description = kg.get('description', '')
|
| 79 |
-
attributes = kg.get('attributes', {})
|
| 80 |
-
|
| 81 |
-
# Combine description and attributes
|
| 82 |
-
content = description
|
| 83 |
-
for key, value in attributes.items():
|
| 84 |
-
content += f" {key}: {value}."
|
| 85 |
-
|
| 86 |
-
if content:
|
| 87 |
-
results.append({
|
| 88 |
-
'title': title,
|
| 89 |
-
'content': content,
|
| 90 |
-
'url': kg.get('link', ''),
|
| 91 |
-
'type': 'knowledgeGraph'
|
| 92 |
-
})
|
| 93 |
-
self.debug_print(f"Added knowledge graph: {title}")
|
| 94 |
-
|
| 95 |
-
# Process organic results
|
| 96 |
-
if 'organic' in search_data:
|
| 97 |
-
for item in search_data['organic']:
|
| 98 |
-
title = item.get('title', '')
|
| 99 |
-
snippet = item.get('snippet', '')
|
| 100 |
-
link = item.get('link', '')
|
| 101 |
-
|
| 102 |
-
if snippet and link:
|
| 103 |
-
results.append({
|
| 104 |
-
'title': title,
|
| 105 |
-
'content': snippet,
|
| 106 |
-
'url': link,
|
| 107 |
-
'type': 'organic'
|
| 108 |
-
})
|
| 109 |
-
self.debug_print(f"Added organic result: {title}")
|
| 110 |
-
|
| 111 |
-
# Check if we have video results for video-related queries
|
| 112 |
-
if 'videos' in search_data and any(word in query.lower() for word in ["video", "youtube", "watch"]):
|
| 113 |
-
for video in search_data['videos']:
|
| 114 |
-
title = video.get('title', '')
|
| 115 |
-
link = video.get('link', '')
|
| 116 |
-
|
| 117 |
-
if title and link:
|
| 118 |
-
results.append({
|
| 119 |
-
'title': f"Video: {title}",
|
| 120 |
-
'content': f"Video content about: {title}",
|
| 121 |
-
'url': link,
|
| 122 |
-
'type': 'video'
|
| 123 |
-
})
|
| 124 |
-
self.debug_print(f"Added video result: {title}")
|
| 125 |
-
|
| 126 |
-
self.debug_print(f"Total results collected: {len(results)}")
|
| 127 |
-
return results
|
| 128 |
-
else:
|
| 129 |
-
self.debug_print(f"Serper API error: {response.status_code} - {response.text}")
|
| 130 |
-
return []
|
| 131 |
-
|
| 132 |
-
except Exception as e:
|
| 133 |
-
self.debug_print(f"Error in Serper search: {e}")
|
| 134 |
-
return []
|
| 135 |
|
| 136 |
-
|
| 137 |
-
""
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
#
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
found_capitals = [cap for cap in capitals if cap in text]
|
| 170 |
-
if found_capitals:
|
| 171 |
-
self.debug_print(f"Found capitals: {found_capitals}")
|
| 172 |
-
return found_capitals
|
| 173 |
-
|
| 174 |
-
if "country" in question_lower and "no longer exists" in question_lower:
|
| 175 |
-
# Extract former countries
|
| 176 |
-
former_countries = ["Soviet Union", "USSR", "Yugoslavia", "Czechoslovakia",
|
| 177 |
-
"East Germany", "GDR", "Ottoman Empire"]
|
| 178 |
-
found_countries = [c for c in former_countries if c in text]
|
| 179 |
-
if found_countries:
|
| 180 |
-
self.debug_print(f"Found former countries: {found_countries}")
|
| 181 |
-
return found_countries
|
| 182 |
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
# Default: return None
|
| 193 |
-
return None
|
| 194 |
|
| 195 |
-
|
| 196 |
-
"""Special processing for the specific Malko Competition question"""
|
| 197 |
-
all_content = " ".join([r.get('content', '') for r in search_results])
|
| 198 |
|
| 199 |
-
#
|
| 200 |
-
|
| 201 |
-
# Pattern to find names associated with these countries
|
| 202 |
-
pattern = r'([A-Z][a-z]+) ([A-Z][a-z]+)[^.]*?{}'.format(former_country)
|
| 203 |
-
matches = re.findall(pattern, all_content)
|
| 204 |
-
|
| 205 |
-
if matches:
|
| 206 |
-
self.debug_print(f"Found Malko recipient from {former_country}: {matches[0]}")
|
| 207 |
-
return matches[0][0] # Return first name
|
| 208 |
-
|
| 209 |
-
# Try to find recipients by year after 1977 and then check nationality
|
| 210 |
-
recipients_pattern = r'(\d{4})[^.]*?([A-Z][a-z]+) ([A-Z][a-z]+)'
|
| 211 |
-
recipients = re.findall(recipients_pattern, all_content)
|
| 212 |
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
# Look for nationality information for this person
|
| 218 |
-
nationality_pattern = r'{} {}[^.]*?(from|nationality)[^.]*?([A-Z][a-z]+)'.format(
|
| 219 |
-
first_name, last_name)
|
| 220 |
-
nationality_matches = re.findall(nationality_pattern, all_content)
|
| 221 |
-
|
| 222 |
-
if nationality_matches:
|
| 223 |
-
nationality = nationality_matches[0][1]
|
| 224 |
-
self.debug_print(f"Found nationality for {first_name}: {nationality}")
|
| 225 |
-
|
| 226 |
-
# Check if nationality is a former country
|
| 227 |
-
former_countries = ["Soviet", "USSR", "Yugoslavia", "Czechoslovakia", "East Germany"]
|
| 228 |
-
if any(country in nationality for country in former_countries):
|
| 229 |
-
return first_name
|
| 230 |
|
| 231 |
-
#
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
# If found in the specific Wikipedia page, it might be one of these common answers
|
| 235 |
-
if "Dmitry" in all_content or "Igor" in all_content or "Roman" in all_content:
|
| 236 |
-
return "Dmitry" # This is a guess based on common Malko recipients
|
| 237 |
|
| 238 |
-
return
|
| 239 |
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
# 1. Get context from Serper search
|
| 249 |
-
search_results = self.serper_search(question)
|
| 250 |
-
self.last_search_results = search_results # Store for access in other methods
|
| 251 |
-
|
| 252 |
-
# 2. Process search results
|
| 253 |
-
if not search_results:
|
| 254 |
-
self.debug_print("No search results found")
|
| 255 |
-
return "Insufficient information"
|
| 256 |
-
|
| 257 |
-
# 3. Special handling for specific question types
|
| 258 |
-
|
| 259 |
-
# Special case for Malko Competition question
|
| 260 |
-
if "malko competition" in question_lower and "country that no longer exists" in question_lower:
|
| 261 |
-
answer = self.process_malko_competition_question(search_results)
|
| 262 |
-
if answer:
|
| 263 |
-
return answer
|
| 264 |
-
|
| 265 |
-
# Combine all content for processing
|
| 266 |
-
all_content = " ".join([r.get('content', '') for r in search_results])
|
| 267 |
-
|
| 268 |
-
# 4. Extract patterns based on question type
|
| 269 |
-
patterns = self.extract_patterns(all_content, question)
|
| 270 |
-
|
| 271 |
-
if patterns:
|
| 272 |
-
# Return the most relevant pattern
|
| 273 |
-
if "first name" in question_lower:
|
| 274 |
-
return patterns[0] # First name
|
| 275 |
-
elif "last name" in question_lower:
|
| 276 |
-
return patterns[0] # Last name
|
| 277 |
-
elif "year" in question_lower:
|
| 278 |
-
return patterns[0] # Year
|
| 279 |
-
elif "how many" in question_lower:
|
| 280 |
-
return patterns[0] # Number
|
| 281 |
-
else:
|
| 282 |
-
return patterns[0] # Generic pattern
|
| 283 |
-
|
| 284 |
-
# 5. Look for answer box content (highest priority)
|
| 285 |
-
for result in search_results:
|
| 286 |
-
if result.get('type') == 'answerBox':
|
| 287 |
-
content = result.get('content', '')
|
| 288 |
-
if content:
|
| 289 |
-
# For "what is" or "who is" questions, return the content directly
|
| 290 |
-
if question_lower.startswith("what is") or question_lower.startswith("who is"):
|
| 291 |
-
return content.split('.')[0] # First sentence
|
| 292 |
-
|
| 293 |
-
# 6. Extract relevant sentences from all content
|
| 294 |
-
sentences = re.split(r'[.!?]', all_content)
|
| 295 |
-
# Find sentences containing key terms from the question
|
| 296 |
-
key_terms = [word for word in question_lower.split()
|
| 297 |
-
if len(word) > 3 and word not in ["what", "when", "where", "which", "how", "this", "that", "from", "with"]]
|
| 298 |
-
|
| 299 |
-
relevant_sentences = []
|
| 300 |
-
for sentence in sentences:
|
| 301 |
-
if any(term in sentence.lower() for term in key_terms):
|
| 302 |
-
relevant_sentences.append(sentence)
|
| 303 |
-
|
| 304 |
-
if relevant_sentences:
|
| 305 |
-
self.debug_print(f"Found {len(relevant_sentences)} relevant sentences")
|
| 306 |
-
|
| 307 |
-
# Try to extract a concise answer from the most relevant sentence
|
| 308 |
-
best_sentence = max(relevant_sentences,
|
| 309 |
-
key=lambda s: sum(1 for term in key_terms if term in s.lower()))
|
| 310 |
-
|
| 311 |
-
# For "what is the first name" questions, try to extract a first name
|
| 312 |
-
if "first name" in question_lower:
|
| 313 |
-
name_pattern = r'([A-Z][a-z]+) [A-Z][a-z]+'
|
| 314 |
-
names = re.findall(name_pattern, best_sentence)
|
| 315 |
-
if names:
|
| 316 |
-
return names[0]
|
| 317 |
-
|
| 318 |
-
# For date/year questions
|
| 319 |
-
if "year" in question_lower or "when" in question_lower:
|
| 320 |
-
year_pattern = r'\b(19|20)\d{2}\b'
|
| 321 |
-
years = re.findall(year_pattern, best_sentence)
|
| 322 |
-
if years:
|
| 323 |
-
return years[0]
|
| 324 |
-
|
| 325 |
-
# For short answers, return a reasonable subset
|
| 326 |
-
words = best_sentence.split()
|
| 327 |
-
if 3 <= len(words) <= 10:
|
| 328 |
-
return best_sentence.strip()
|
| 329 |
-
else:
|
| 330 |
-
# First few words for longer sentences
|
| 331 |
-
return " ".join(words[:5]).strip()
|
| 332 |
-
|
| 333 |
-
self.debug_print("Insufficient information found in search results")
|
| 334 |
-
return "Insufficient information"
|
| 335 |
-
|
| 336 |
-
except Exception as e:
|
| 337 |
-
self.debug_print(f"Error in agent: {e}")
|
| 338 |
-
return "Error processing question"
|
| 339 |
|
| 340 |
-
|
| 341 |
-
def
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
"task_id": "sample-1",
|
| 346 |
-
"question": "In what year was YouTube founded?",
|
| 347 |
-
"answer": "2005"
|
| 348 |
-
},
|
| 349 |
-
{
|
| 350 |
-
"task_id": "sample-2",
|
| 351 |
-
"question": "Who is the founder of Microsoft?",
|
| 352 |
-
"answer": "Bill Gates"
|
| 353 |
-
},
|
| 354 |
-
{
|
| 355 |
-
"task_id": "sample-3",
|
| 356 |
-
"question": "What is the capital of France?",
|
| 357 |
-
"answer": "Paris"
|
| 358 |
-
},
|
| 359 |
-
{
|
| 360 |
-
"task_id": "sample-4",
|
| 361 |
-
"question": "What color is a typical stop sign?",
|
| 362 |
-
"answer": "red"
|
| 363 |
-
},
|
| 364 |
-
{
|
| 365 |
-
"task_id": "sample-5",
|
| 366 |
-
"question": "How many sides does a triangle have?",
|
| 367 |
-
"answer": "3"
|
| 368 |
-
},
|
| 369 |
-
{
|
| 370 |
-
"task_id": "malko-test",
|
| 371 |
-
"question": "What is the first name of the only Malko Competition recipient from the 20th Century (after 1977) whose nationality on record is a country that no longer exists?",
|
| 372 |
-
"answer": "Dmitry" # This is a placeholder, update with correct answer
|
| 373 |
-
}
|
| 374 |
-
]
|
| 375 |
-
|
| 376 |
-
# Initialize the agent
|
| 377 |
-
agent = PatternMatchingAgent()
|
| 378 |
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 382 |
|
| 383 |
-
|
|
|
|
| 384 |
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
# Run the agent on the question
|
| 393 |
-
answer = agent.run(question)
|
| 394 |
-
|
| 395 |
-
# Check if the answer is correct (exact match)
|
| 396 |
-
is_correct = answer.lower().strip() == expected_answer.lower().strip()
|
| 397 |
-
|
| 398 |
-
if is_correct:
|
| 399 |
-
correct_count += 1
|
| 400 |
-
result = "✓ CORRECT"
|
| 401 |
-
else:
|
| 402 |
-
result = "✗ INCORRECT"
|
| 403 |
-
|
| 404 |
-
print(f"Agent answer: {answer}")
|
| 405 |
-
print(f"Expected: {expected_answer}")
|
| 406 |
-
print(f"Result: {result}\n")
|
| 407 |
-
|
| 408 |
-
results.append({
|
| 409 |
-
"question": question,
|
| 410 |
-
"agent_answer": answer,
|
| 411 |
-
"expected_answer": expected_answer,
|
| 412 |
-
"is_correct": is_correct
|
| 413 |
-
})
|
| 414 |
-
|
| 415 |
-
except Exception as e:
|
| 416 |
-
print(f"Error: {e}\n")
|
| 417 |
-
results.append({
|
| 418 |
-
"question": question,
|
| 419 |
-
"agent_answer": f"ERROR: {str(e)}",
|
| 420 |
-
"expected_answer": expected_answer,
|
| 421 |
-
"is_correct": False
|
| 422 |
-
})
|
| 423 |
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
print(f"=== Test Complete ===")
|
| 427 |
-
print(f"Correct: {correct_count}/{len(sample_questions)} ({accuracy:.1f}%)")
|
| 428 |
|
| 429 |
-
return
|
| 430 |
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
Fetches all questions, runs the PatternMatchingAgent on them, submits all answers,
|
| 434 |
-
and displays the results.
|
| 435 |
-
"""
|
| 436 |
-
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 437 |
-
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 438 |
-
|
| 439 |
-
if profile:
|
| 440 |
-
username= f"{profile.username}"
|
| 441 |
-
print(f"User logged in: {username}")
|
| 442 |
-
else:
|
| 443 |
-
print("User not logged in.")
|
| 444 |
-
return "Please Login to Hugging Face with the button.", None
|
| 445 |
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
|
|
|
| 449 |
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
response.raise_for_status()
|
| 467 |
-
questions_data = response.json()
|
| 468 |
-
if not questions_data:
|
| 469 |
-
print("Fetched questions list is empty.")
|
| 470 |
-
return "Fetched questions list is empty or invalid format.", None
|
| 471 |
-
print(f"Fetched {len(questions_data)} questions.")
|
| 472 |
-
except requests.exceptions.RequestException as e:
|
| 473 |
-
print(f"Error fetching questions: {e}")
|
| 474 |
-
return f"Error fetching questions: {e}", None
|
| 475 |
-
except requests.exceptions.JSONDecodeError as e:
|
| 476 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 477 |
-
print(f"Response text: {response.text[:500]}")
|
| 478 |
-
return f"Error decoding server response for questions: {e}", None
|
| 479 |
-
except Exception as e:
|
| 480 |
-
print(f"An unexpected error occurred fetching questions: {e}")
|
| 481 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
| 482 |
-
|
| 483 |
-
# 3. Run your Agent
|
| 484 |
-
results_log = []
|
| 485 |
-
answers_payload = []
|
| 486 |
-
print(f"Running agent on {len(questions_data)} questions...")
|
| 487 |
-
for item in questions_data:
|
| 488 |
-
task_id = item.get("task_id")
|
| 489 |
-
question_text = item.get("question")
|
| 490 |
-
if not task_id or question_text is None:
|
| 491 |
-
print(f"Skipping item with missing task_id or question: {item}")
|
| 492 |
-
continue
|
| 493 |
-
try:
|
| 494 |
-
# Add a delay between questions to avoid rate limiting
|
| 495 |
-
time.sleep(3)
|
| 496 |
-
|
| 497 |
-
submitted_answer = agent.run(question_text)
|
| 498 |
-
# Clean up the answer if needed
|
| 499 |
-
if submitted_answer and len(submitted_answer) > 500:
|
| 500 |
-
submitted_answer = submitted_answer[:500] # Limit answer length
|
| 501 |
-
|
| 502 |
-
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 503 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 504 |
-
|
| 505 |
-
print(f"Processed question {len(results_log)}/{len(questions_data)}")
|
| 506 |
-
|
| 507 |
-
except Exception as e:
|
| 508 |
-
print(f"Error running agent on task {task_id}: {e}")
|
| 509 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 510 |
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 514 |
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 519 |
|
| 520 |
-
|
| 521 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 522 |
try:
|
| 523 |
-
response =
|
| 524 |
-
response
|
| 525 |
-
result_data = response.json()
|
| 526 |
-
final_status = (
|
| 527 |
-
f"Submission Successful!\n"
|
| 528 |
-
f"User: {result_data.get('username')}\n"
|
| 529 |
-
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 530 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 531 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
| 532 |
-
)
|
| 533 |
-
print("Submission successful.")
|
| 534 |
-
results_df = pd.DataFrame(results_log)
|
| 535 |
-
return final_status, results_df
|
| 536 |
-
except requests.exceptions.HTTPError as e:
|
| 537 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
| 538 |
-
try:
|
| 539 |
-
error_json = e.response.json()
|
| 540 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 541 |
-
except requests.exceptions.JSONDecodeError:
|
| 542 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
| 543 |
-
status_message = f"Submission Failed: {error_detail}"
|
| 544 |
-
print(status_message)
|
| 545 |
-
results_df = pd.DataFrame(results_log)
|
| 546 |
-
return status_message, results_df
|
| 547 |
-
except requests.exceptions.Timeout:
|
| 548 |
-
status_message = "Submission Failed: The request timed out."
|
| 549 |
-
print(status_message)
|
| 550 |
-
results_df = pd.DataFrame(results_log)
|
| 551 |
-
return status_message, results_df
|
| 552 |
-
except requests.exceptions.RequestException as e:
|
| 553 |
-
status_message = f"Submission Failed: Network error - {e}"
|
| 554 |
-
print(status_message)
|
| 555 |
-
results_df = pd.DataFrame(results_log)
|
| 556 |
-
return status_message, results_df
|
| 557 |
except Exception as e:
|
| 558 |
-
|
| 559 |
-
print(status_message)
|
| 560 |
-
results_df = pd.DataFrame(results_log)
|
| 561 |
-
return status_message, results_df
|
| 562 |
-
|
| 563 |
-
# Gradio Interface
|
| 564 |
-
with gr.Blocks() as demo:
|
| 565 |
-
gr.Markdown("# GAIA Agent Evaluation Runner")
|
| 566 |
-
gr.Markdown(
|
| 567 |
-
"""
|
| 568 |
-
**Instructions:**
|
| 569 |
-
1. Add your Serper API key as a secret named SERPER_API_KEY in the Space settings
|
| 570 |
-
2. Log in to your Hugging Face account using the button below
|
| 571 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score
|
| 572 |
-
"""
|
| 573 |
-
)
|
| 574 |
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 582 |
-
|
| 583 |
-
run_button.click(
|
| 584 |
-
fn=run_and_submit_all,
|
| 585 |
-
outputs=[status_output, results_table]
|
| 586 |
-
)
|
| 587 |
-
|
| 588 |
-
# Local testing section
|
| 589 |
-
with gr.Tab("Local Testing"):
|
| 590 |
-
test_button = gr.Button("Run Local Tests")
|
| 591 |
-
test_results = gr.DataFrame(
|
| 592 |
-
headers=["Question", "Agent Answer", "Expected Answer", "Is Correct"],
|
| 593 |
-
label="Local Test Results"
|
| 594 |
-
)
|
| 595 |
-
|
| 596 |
-
test_button.click(
|
| 597 |
-
fn=test_agent_locally,
|
| 598 |
-
outputs=test_results
|
| 599 |
-
)
|
| 600 |
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
debug_question = gr.Textbox(label="Enter a question to debug", lines=2)
|
| 604 |
-
debug_button = gr.Button("Analyze Question")
|
| 605 |
-
debug_output = gr.Textbox(label="Debug Output", lines=20)
|
| 606 |
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
f = io.StringIO()
|
| 612 |
-
with redirect_stdout(f):
|
| 613 |
-
agent = PatternMatchingAgent(debug_mode=True)
|
| 614 |
-
answer = agent.run(question)
|
| 615 |
-
print(f"\n==== FINAL ANSWER ====\n{answer}")
|
| 616 |
-
|
| 617 |
-
return f.getvalue()
|
| 618 |
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
inputs=debug_question,
|
| 622 |
-
outputs=debug_output
|
| 623 |
-
)
|
| 624 |
|
| 625 |
if __name__ == "__main__":
|
| 626 |
-
|
| 627 |
-
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
import os
|
| 2 |
+
import json
|
| 3 |
import requests
|
| 4 |
+
from typing import Dict, List, Any, Optional, Union
|
| 5 |
+
from langchain_core.prompts import ChatPromptTemplate
|
| 6 |
+
from langchain_core.output_parsers import StrOutputParser, JsonOutputParser
|
| 7 |
+
from langchain.agents import AgentExecutor, create_openai_tools_agent
|
| 8 |
+
from langchain_core.tools import tool, BaseTool
|
| 9 |
+
from langchain_openai import ChatOpenAI
|
| 10 |
+
from langchain_core.messages import AIMessage, HumanMessage
|
| 11 |
+
import youtube_transcript_api
|
| 12 |
+
from youtube_transcript_api import YouTubeTranscriptApi
|
| 13 |
+
from youtube_transcript_api.formatters import TextFormatter
|
| 14 |
import re
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
+
# Environment variables setup
|
| 17 |
+
OPENAI_API_KEY = os.environ.get("OPENAI_TEST", "your-openai-key")
|
| 18 |
+
SERPER_API_KEY = os.environ.get("SERPER_API_KEY", "your-serper-key")
|
| 19 |
+
MODEL_NAME = "gpt-4o-mini" # You can change this to the model you prefer
|
| 20 |
|
| 21 |
+
# Initialize the LLM
|
| 22 |
+
llm = ChatOpenAI(
|
| 23 |
+
model=MODEL_NAME,
|
| 24 |
+
temperature=0.1,
|
| 25 |
+
api_key=OPENAI_API_KEY
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# Tools for the agent
|
| 29 |
+
|
| 30 |
+
@tool
|
| 31 |
+
def search(query: str) -> str:
|
| 32 |
+
"""
|
| 33 |
+
Search the web using Google via the Serper API.
|
| 34 |
|
| 35 |
+
Args:
|
| 36 |
+
query: The search query string
|
|
|
|
| 37 |
|
| 38 |
+
Returns:
|
| 39 |
+
Search results as a string
|
| 40 |
+
"""
|
| 41 |
+
url = "https://google.serper.dev/search"
|
| 42 |
+
payload = json.dumps({
|
| 43 |
+
"q": query,
|
| 44 |
+
"gl": "us",
|
| 45 |
+
"hl": "en",
|
| 46 |
+
"num": 5
|
| 47 |
+
})
|
| 48 |
+
headers = {
|
| 49 |
+
'X-API-KEY': SERPER_API_KEY,
|
| 50 |
+
'Content-Type': 'application/json'
|
| 51 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
+
try:
|
| 54 |
+
response = requests.request("POST", url, headers=headers, data=payload)
|
| 55 |
+
results = response.json()
|
| 56 |
+
|
| 57 |
+
# Format the results into a readable string
|
| 58 |
+
formatted_results = "Search results:\n\n"
|
| 59 |
+
|
| 60 |
+
# Process organic results
|
| 61 |
+
if "organic" in results:
|
| 62 |
+
for i, result in enumerate(results["organic"][:5], 1):
|
| 63 |
+
formatted_results += f"{i}. {result.get('title', 'No Title')}\n"
|
| 64 |
+
formatted_results += f" Link: {result.get('link', 'No Link')}\n"
|
| 65 |
+
formatted_results += f" Snippet: {result.get('snippet', 'No Snippet')}\n\n"
|
| 66 |
+
|
| 67 |
+
# Process knowledge graph if available
|
| 68 |
+
if "knowledgeGraph" in results:
|
| 69 |
+
kg = results["knowledgeGraph"]
|
| 70 |
+
formatted_results += "Knowledge Graph:\n"
|
| 71 |
+
formatted_results += f"Title: {kg.get('title', 'N/A')}\n"
|
| 72 |
+
formatted_results += f"Description: {kg.get('description', 'N/A')}\n"
|
| 73 |
+
|
| 74 |
+
return formatted_results
|
| 75 |
+
|
| 76 |
+
except Exception as e:
|
| 77 |
+
return f"Error performing search: {str(e)}"
|
| 78 |
+
|
| 79 |
+
@tool
|
| 80 |
+
def extract_youtube_transcript(youtube_url: str) -> str:
|
| 81 |
+
"""
|
| 82 |
+
Extract and return the transcript from a YouTube video.
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
youtube_url: URL of the YouTube video
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
+
Returns:
|
| 88 |
+
The video transcript as a string
|
| 89 |
+
"""
|
| 90 |
+
try:
|
| 91 |
+
# Extract the video ID from the URL
|
| 92 |
+
video_id_match = re.search(r'(?:v=|\/)([0-9A-Za-z_-]{11}).*', youtube_url)
|
| 93 |
+
if not video_id_match:
|
| 94 |
+
return "Could not extract video ID from the URL."
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
+
video_id = video_id_match.group(1)
|
|
|
|
|
|
|
| 97 |
|
| 98 |
+
# Get the transcript
|
| 99 |
+
transcript = YouTubeTranscriptApi.get_transcript(video_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
+
# Format the transcript to plain text
|
| 102 |
+
formatter = TextFormatter()
|
| 103 |
+
formatted_transcript = formatter.format_transcript(transcript)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
+
# Limit transcript length if too long
|
| 106 |
+
if len(formatted_transcript) > 10000:
|
| 107 |
+
formatted_transcript = formatted_transcript[:10000] + "...(transcript truncated due to length)"
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
+
return f"YouTube Video Transcript:\n\n{formatted_transcript}"
|
| 110 |
|
| 111 |
+
except youtube_transcript_api.NoTranscriptFound:
|
| 112 |
+
return "No transcript is available for this video."
|
| 113 |
+
except youtube_transcript_api.TranscriptsDisabled:
|
| 114 |
+
return "Transcripts are disabled for this video."
|
| 115 |
+
except youtube_transcript_api.VideoUnavailable:
|
| 116 |
+
return "The video is unavailable or private."
|
| 117 |
+
except Exception as e:
|
| 118 |
+
return f"Error extracting transcript: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
|
| 120 |
+
@tool
|
| 121 |
+
def analyze_video_content(youtube_url: str) -> str:
|
| 122 |
+
"""
|
| 123 |
+
Analyze the content of a YouTube video by extracting its transcript
|
| 124 |
+
and summarizing the main points.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
+
Args:
|
| 127 |
+
youtube_url: URL of the YouTube video
|
| 128 |
+
|
| 129 |
+
Returns:
|
| 130 |
+
A summary and analysis of the video content
|
| 131 |
+
"""
|
| 132 |
+
# First extract the transcript
|
| 133 |
+
transcript = extract_youtube_transcript(youtube_url)
|
| 134 |
|
| 135 |
+
if "Error" in transcript or "No transcript" in transcript or "Transcripts are disabled" in transcript:
|
| 136 |
+
return transcript
|
| 137 |
|
| 138 |
+
# Use the LLM to analyze the transcript
|
| 139 |
+
analysis_prompt = ChatPromptTemplate.from_messages([
|
| 140 |
+
("system", "You are an expert at analyzing video content based on transcripts. "
|
| 141 |
+
"Extract the key points, main arguments, and important information."),
|
| 142 |
+
("user", f"Analyze the following YouTube video transcript and provide a concise summary of the main points, "
|
| 143 |
+
f"key arguments, and important information:\n\n{transcript}")
|
| 144 |
+
])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
+
analysis_chain = analysis_prompt | llm | StrOutputParser()
|
| 147 |
+
analysis_result = analysis_chain.invoke({})
|
|
|
|
|
|
|
| 148 |
|
| 149 |
+
return f"Video Analysis:\n\n{analysis_result}"
|
| 150 |
|
| 151 |
+
# Define tools list
|
| 152 |
+
tools = [search, extract_youtube_transcript, analyze_video_content]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
+
# Agent prompt template with detailed instructions
|
| 155 |
+
agent_prompt = ChatPromptTemplate.from_messages([
|
| 156 |
+
("system", """You are a highly capable AI research agent designed to complete tasks effectively.
|
| 157 |
+
Your goal is to provide accurate, helpful responses by utilizing available tools when needed.
|
| 158 |
|
| 159 |
+
For tasks requiring current information, use the search tool.
|
| 160 |
+
For tasks involving YouTube videos, extract and analyze their transcripts.
|
| 161 |
+
|
| 162 |
+
Always think step-by-step about the best approach before acting.
|
| 163 |
+
|
| 164 |
+
When a task is complex:
|
| 165 |
+
1. Break it down into smaller steps
|
| 166 |
+
2. Determine which tools would be most helpful for each step
|
| 167 |
+
3. Execute each step methodically
|
| 168 |
+
4. Synthesize the information into a coherent response
|
| 169 |
+
|
| 170 |
+
Your response should be comprehensive yet concise, focusing on the most relevant information to answer the user's question or complete their task.
|
| 171 |
+
"""),
|
| 172 |
+
("human", "{input}"),
|
| 173 |
+
("ai", "{agent_scratchpad}")
|
| 174 |
+
])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
|
| 176 |
+
# Create the agent
|
| 177 |
+
agent = create_openai_tools_agent(llm, tools, agent_prompt)
|
|
|
|
| 178 |
|
| 179 |
+
# Create the agent executor
|
| 180 |
+
agent_executor = AgentExecutor(
|
| 181 |
+
agent=agent,
|
| 182 |
+
tools=tools,
|
| 183 |
+
verbose=True,
|
| 184 |
+
handle_parsing_errors=True,
|
| 185 |
+
max_iterations=5,
|
| 186 |
+
early_stopping_method="force"
|
| 187 |
+
)
|
| 188 |
|
| 189 |
+
# Main function to handle input and generate responses
|
| 190 |
+
def process_input(user_input: str) -> str:
|
| 191 |
+
"""
|
| 192 |
+
Process user input and generate agent response.
|
| 193 |
+
|
| 194 |
+
Args:
|
| 195 |
+
user_input: The user's query or instruction
|
| 196 |
+
|
| 197 |
+
Returns:
|
| 198 |
+
The agent's response
|
| 199 |
+
"""
|
| 200 |
try:
|
| 201 |
+
response = agent_executor.invoke({"input": user_input})
|
| 202 |
+
return response["output"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
except Exception as e:
|
| 204 |
+
return f"Error processing your request: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
|
| 206 |
+
# Example usage for GAIA benchmark
|
| 207 |
+
def main():
|
| 208 |
+
"""
|
| 209 |
+
Main function to demonstrate the agent's capabilities.
|
| 210 |
+
"""
|
| 211 |
+
print("GAIA Agent initialized. Enter 'exit' to quit.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
|
| 213 |
+
while True:
|
| 214 |
+
user_input = input("\nUser: ")
|
|
|
|
|
|
|
|
|
|
| 215 |
|
| 216 |
+
if user_input.lower() == 'exit':
|
| 217 |
+
print("Exiting the agent.")
|
| 218 |
+
break
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
+
response = process_input(user_input)
|
| 221 |
+
print(f"\nAgent: {response}")
|
|
|
|
|
|
|
|
|
|
| 222 |
|
| 223 |
if __name__ == "__main__":
|
| 224 |
+
main()
|
|
|