Spaces:
No application file
No application file
Update app.py
Browse files
app.py
CHANGED
|
@@ -19,6 +19,7 @@ import requests
|
|
| 19 |
from tenacity import retry, stop_after_attempt, wait_exponential
|
| 20 |
import re
|
| 21 |
import aiohttp
|
|
|
|
| 22 |
|
| 23 |
# Configure logging with more detailed format
|
| 24 |
logging.basicConfig(
|
|
@@ -191,72 +192,189 @@ class LocalSearch(Tool):
|
|
| 191 |
)
|
| 192 |
self.knowledge_base_path = knowledge_base_path
|
| 193 |
self._load_knowledge_base()
|
| 194 |
-
|
| 195 |
-
def _load_knowledge_base(self):
|
| 196 |
-
if not self.knowledge_base_path.exists():
|
| 197 |
-
os.makedirs(self.knowledge_base_path, exist_ok=True)
|
| 198 |
|
| 199 |
-
async def _execute_impl(self, input_data: Dict[str, Any]) -> Any:
|
| 200 |
-
"""Enhanced execution with
|
| 201 |
try:
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
results = await self._search_knowledge_base(query)
|
| 218 |
return {
|
| 219 |
"query": query,
|
| 220 |
"results": results,
|
| 221 |
-
"
|
|
|
|
| 222 |
}
|
| 223 |
|
| 224 |
except Exception as e:
|
| 225 |
logger.error(f"Error in LocalSearch: {str(e)}")
|
| 226 |
return {"error": str(e)}
|
| 227 |
|
| 228 |
-
async def
|
| 229 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
try:
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
except Exception as e:
|
| 238 |
-
|
|
|
|
| 239 |
|
| 240 |
-
async def
|
| 241 |
-
"""
|
| 242 |
try:
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
except Exception as e:
|
| 254 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
|
| 256 |
-
async def
|
| 257 |
-
"""
|
| 258 |
-
|
| 259 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
|
| 261 |
class Memory(Tool):
|
| 262 |
"""New tool for persistent memory across agent steps"""
|
|
@@ -299,21 +417,27 @@ Your available tools are:
|
|
| 299 |
- memory: To store and retrieve information across steps
|
| 300 |
|
| 301 |
When answering:
|
| 302 |
-
1. ALWAYS
|
| 303 |
2. Use local_search to find relevant information in the knowledge base
|
| 304 |
3. Use the calculator for any numerical calculations
|
| 305 |
4. Use memory to store important findings for multi-step reasoning
|
| 306 |
-
5.
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
|
|
|
| 315 |
|
| 316 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
|
| 318 |
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
|
| 319 |
async def _get_model_response(self, context: str) -> str:
|
|
@@ -476,20 +600,37 @@ If you truly cannot find an answer after using the tools, explain what you tried
|
|
| 476 |
try:
|
| 477 |
self.state = AgentState() # Reset state for new question
|
| 478 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 479 |
while self.state.current_step < self.state.max_steps:
|
| 480 |
step_result = await self._process_step(question)
|
| 481 |
if step_result:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 482 |
processing_time = (datetime.now() - start_time).total_seconds()
|
| 483 |
step_result.processing_time = processing_time
|
|
|
|
|
|
|
|
|
|
|
|
|
| 484 |
return step_result
|
| 485 |
|
| 486 |
self.state.current_step += 1
|
| 487 |
|
| 488 |
-
# If we reach max steps without an answer
|
| 489 |
return Answer(
|
| 490 |
-
text="
|
| 491 |
confidence=0.0,
|
| 492 |
-
reasoning_trace=["Maximum
|
| 493 |
tools_used=self.state.tools_used,
|
| 494 |
processing_time=(datetime.now() - start_time).total_seconds()
|
| 495 |
)
|
|
@@ -497,13 +638,59 @@ If you truly cannot find an answer after using the tools, explain what you tried
|
|
| 497 |
except Exception as e:
|
| 498 |
logger.error(f"Error processing question: {str(e)}")
|
| 499 |
return Answer(
|
| 500 |
-
text=f"Error processing question
|
| 501 |
confidence=0.0,
|
| 502 |
reasoning_trace=["Error occurred during processing"],
|
| 503 |
tools_used=[],
|
| 504 |
processing_time=(datetime.now() - start_time).total_seconds()
|
| 505 |
)
|
| 506 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 507 |
async def _process_step(self, question: Question) -> Optional[Answer]:
|
| 508 |
"""Process a single step with enhanced error handling and attachment processing"""
|
| 509 |
try:
|
|
|
|
| 19 |
from tenacity import retry, stop_after_attempt, wait_exponential
|
| 20 |
import re
|
| 21 |
import aiohttp
|
| 22 |
+
import aiofiles
|
| 23 |
|
| 24 |
# Configure logging with more detailed format
|
| 25 |
logging.basicConfig(
|
|
|
|
| 192 |
)
|
| 193 |
self.knowledge_base_path = knowledge_base_path
|
| 194 |
self._load_knowledge_base()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 195 |
|
| 196 |
+
async def _execute_impl(self, input_data: Union[str, Dict[str, Any]]) -> Any:
|
| 197 |
+
"""Enhanced execution with better input handling"""
|
| 198 |
try:
|
| 199 |
+
# Handle string input as direct query
|
| 200 |
+
if isinstance(input_data, str):
|
| 201 |
+
query = input_data
|
| 202 |
+
file_type = None
|
| 203 |
+
else:
|
| 204 |
+
query = input_data.get('query', '')
|
| 205 |
+
file_type = input_data.get('file_type')
|
| 206 |
+
|
| 207 |
+
# Search in knowledge base
|
| 208 |
+
results = await self._search_knowledge_base(query, file_type=file_type)
|
| 209 |
+
|
| 210 |
+
# If no results found, try fuzzy matching
|
| 211 |
+
if not results:
|
| 212 |
+
results = await self._fuzzy_search(query)
|
| 213 |
+
|
|
|
|
| 214 |
return {
|
| 215 |
"query": query,
|
| 216 |
"results": results,
|
| 217 |
+
"file_type": file_type,
|
| 218 |
+
"total_matches": len(results)
|
| 219 |
}
|
| 220 |
|
| 221 |
except Exception as e:
|
| 222 |
logger.error(f"Error in LocalSearch: {str(e)}")
|
| 223 |
return {"error": str(e)}
|
| 224 |
|
| 225 |
+
async def _search_knowledge_base(
|
| 226 |
+
self,
|
| 227 |
+
query: str,
|
| 228 |
+
file_type: Optional[str] = None
|
| 229 |
+
) -> List[Dict[str, Any]]:
|
| 230 |
+
"""Enhanced knowledge base search with better file handling"""
|
| 231 |
+
results = []
|
| 232 |
try:
|
| 233 |
+
# Normalize query
|
| 234 |
+
query = query.lower().strip()
|
| 235 |
+
|
| 236 |
+
# Search in appropriate directory based on file type
|
| 237 |
+
if file_type:
|
| 238 |
+
search_dirs = [self.knowledge_base_path / self._get_subdir(file_type)]
|
| 239 |
+
else:
|
| 240 |
+
search_dirs = [
|
| 241 |
+
self.knowledge_base_path / subdir
|
| 242 |
+
for subdir in ['text', 'data', 'media']
|
| 243 |
+
]
|
| 244 |
+
|
| 245 |
+
for search_dir in search_dirs:
|
| 246 |
+
if not search_dir.exists():
|
| 247 |
+
continue
|
| 248 |
+
|
| 249 |
+
for file_path in search_dir.glob("**/*"):
|
| 250 |
+
if not file_path.is_file():
|
| 251 |
+
continue
|
| 252 |
+
|
| 253 |
+
try:
|
| 254 |
+
content = await self._read_file_content(file_path)
|
| 255 |
+
if not content:
|
| 256 |
+
continue
|
| 257 |
+
|
| 258 |
+
# Calculate relevance score
|
| 259 |
+
relevance = self._calculate_relevance(query, content)
|
| 260 |
+
if relevance > 0:
|
| 261 |
+
results.append({
|
| 262 |
+
"file": str(file_path.relative_to(self.knowledge_base_path)),
|
| 263 |
+
"content": content[:1000], # Limit content size
|
| 264 |
+
"relevance_score": relevance,
|
| 265 |
+
"file_type": file_path.suffix[1:] if file_path.suffix else "unknown"
|
| 266 |
+
})
|
| 267 |
+
except Exception as e:
|
| 268 |
+
logger.error(f"Error processing file {file_path}: {str(e)}")
|
| 269 |
+
continue
|
| 270 |
+
|
| 271 |
+
# Sort by relevance
|
| 272 |
+
results.sort(key=lambda x: x['relevance_score'], reverse=True)
|
| 273 |
+
return results[:5] # Return top 5 results
|
| 274 |
+
|
| 275 |
except Exception as e:
|
| 276 |
+
logger.error(f"Error in knowledge base search: {str(e)}")
|
| 277 |
+
return []
|
| 278 |
|
| 279 |
+
async def _read_file_content(self, file_path: Path) -> Optional[str]:
|
| 280 |
+
"""Read and process file content based on type"""
|
| 281 |
try:
|
| 282 |
+
suffix = file_path.suffix.lower()
|
| 283 |
+
|
| 284 |
+
if suffix in ['.xlsx', '.xls']:
|
| 285 |
+
df = pd.read_excel(file_path)
|
| 286 |
+
return df.to_string()
|
| 287 |
+
|
| 288 |
+
elif suffix == '.csv':
|
| 289 |
+
df = pd.read_csv(file_path)
|
| 290 |
+
return df.to_string()
|
| 291 |
+
|
| 292 |
+
elif suffix in ['.txt', '.py', '.json']:
|
| 293 |
+
async with aiofiles.open(file_path, 'r') as f:
|
| 294 |
+
return await f.read()
|
| 295 |
+
|
| 296 |
+
elif suffix in ['.mp3', '.wav', '.mp4', '.jpg', '.png']:
|
| 297 |
+
# For media files, return metadata
|
| 298 |
+
return f"Media file: {file_path.name}, type: {suffix[1:]}"
|
| 299 |
+
|
| 300 |
+
else:
|
| 301 |
+
logger.warning(f"Unsupported file type: {suffix}")
|
| 302 |
+
return None
|
| 303 |
+
|
| 304 |
+
except Exception as e:
|
| 305 |
+
logger.error(f"Error reading file {file_path}: {str(e)}")
|
| 306 |
+
return None
|
| 307 |
+
|
| 308 |
+
def _calculate_relevance(self, query: str, content: str) -> float:
|
| 309 |
+
"""Calculate improved relevance score between query and content"""
|
| 310 |
+
try:
|
| 311 |
+
# Convert content to string if it's not already
|
| 312 |
+
if not isinstance(content, str):
|
| 313 |
+
content = str(content)
|
| 314 |
+
|
| 315 |
+
# Normalize text
|
| 316 |
+
query = query.lower()
|
| 317 |
+
content = content.lower()
|
| 318 |
+
|
| 319 |
+
# Split into terms
|
| 320 |
+
query_terms = set(query.split())
|
| 321 |
+
content_terms = set(content.split())
|
| 322 |
+
|
| 323 |
+
# Calculate various metrics
|
| 324 |
+
term_overlap = len(query_terms & content_terms)
|
| 325 |
+
exact_matches = content.count(query)
|
| 326 |
+
term_frequency = sum(content.count(term) for term in query_terms)
|
| 327 |
+
|
| 328 |
+
# Combine metrics into final score
|
| 329 |
+
score = (
|
| 330 |
+
0.5 * (term_overlap / len(query_terms) if query_terms else 0) +
|
| 331 |
+
0.3 * (exact_matches > 0) +
|
| 332 |
+
0.2 * (term_frequency / len(content.split()) if content else 0)
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
return min(1.0, score) # Normalize to [0, 1]
|
| 336 |
+
|
| 337 |
except Exception as e:
|
| 338 |
+
logger.error(f"Error calculating relevance: {str(e)}")
|
| 339 |
+
return 0.0
|
| 340 |
+
|
| 341 |
+
def _get_subdir(self, file_type: str) -> str:
|
| 342 |
+
"""Get appropriate subdirectory for file type"""
|
| 343 |
+
file_type = file_type.lower()
|
| 344 |
+
if file_type in ['xlsx', 'xls', 'csv']:
|
| 345 |
+
return 'data'
|
| 346 |
+
elif file_type in ['txt', 'py', 'json']:
|
| 347 |
+
return 'text'
|
| 348 |
+
elif file_type in ['mp3', 'wav', 'mp4', 'jpg', 'png']:
|
| 349 |
+
return 'media'
|
| 350 |
+
else:
|
| 351 |
+
return 'other'
|
| 352 |
|
| 353 |
+
async def _fuzzy_search(self, query: str) -> List[Dict[str, Any]]:
|
| 354 |
+
"""Perform fuzzy matching when exact match fails"""
|
| 355 |
+
results = []
|
| 356 |
+
try:
|
| 357 |
+
# Implement fuzzy matching logic here
|
| 358 |
+
# For now, just do a more lenient search
|
| 359 |
+
terms = query.lower().split()
|
| 360 |
+
for term in terms:
|
| 361 |
+
term_results = await self._search_knowledge_base(term)
|
| 362 |
+
results.extend(term_results)
|
| 363 |
+
|
| 364 |
+
# Remove duplicates and sort by relevance
|
| 365 |
+
seen = set()
|
| 366 |
+
unique_results = []
|
| 367 |
+
for result in results:
|
| 368 |
+
file_key = result['file']
|
| 369 |
+
if file_key not in seen:
|
| 370 |
+
seen.add(file_key)
|
| 371 |
+
unique_results.append(result)
|
| 372 |
+
|
| 373 |
+
return sorted(unique_results, key=lambda x: x['relevance_score'], reverse=True)[:5]
|
| 374 |
+
|
| 375 |
+
except Exception as e:
|
| 376 |
+
logger.error(f"Error in fuzzy search: {str(e)}")
|
| 377 |
+
return []
|
| 378 |
|
| 379 |
class Memory(Tool):
|
| 380 |
"""New tool for persistent memory across agent steps"""
|
|
|
|
| 417 |
- memory: To store and retrieve information across steps
|
| 418 |
|
| 419 |
When answering:
|
| 420 |
+
1. ALWAYS use the tools to find information before saying you can't answer
|
| 421 |
2. Use local_search to find relevant information in the knowledge base
|
| 422 |
3. Use the calculator for any numerical calculations
|
| 423 |
4. Use memory to store important findings for multi-step reasoning
|
| 424 |
+
5. For file-related questions:
|
| 425 |
+
- Excel files: Use local_search with file_type='xlsx' to analyze data
|
| 426 |
+
- Python files: Use local_search with file_type='py' to analyze code
|
| 427 |
+
- Text files: Use local_search with file_type='txt' to read content
|
| 428 |
+
- Media files: Extract available metadata and describe what you find
|
| 429 |
+
6. NEVER say you can't process a file without first trying local_search
|
| 430 |
+
7. ALWAYS provide a complete answer, don't just say you will search
|
| 431 |
+
8. If you need multiple steps, execute them all before responding
|
| 432 |
+
9. Format your final answer exactly as specified in the question
|
| 433 |
+
10. If no format is specified, use: FINAL ANSWER: [your answer]
|
| 434 |
|
| 435 |
+
Remember:
|
| 436 |
+
- Don't say you'll provide an answer later - complete the search first
|
| 437 |
+
- Don't say you can't process files - use local_search to try
|
| 438 |
+
- Always include FINAL ANSWER: in your response
|
| 439 |
+
- Make your answer as concise as possible while being complete
|
| 440 |
+
- If you truly cannot find information after using tools, explain what you tried"""
|
| 441 |
|
| 442 |
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
|
| 443 |
async def _get_model_response(self, context: str) -> str:
|
|
|
|
| 600 |
try:
|
| 601 |
self.state = AgentState() # Reset state for new question
|
| 602 |
|
| 603 |
+
# First, check for and download any attachments
|
| 604 |
+
if question.attachments:
|
| 605 |
+
for attachment in question.attachments:
|
| 606 |
+
file_path = await self._download_and_process_attachment(attachment)
|
| 607 |
+
if file_path:
|
| 608 |
+
self.state.memory[f"attachment_{attachment}"] = file_path
|
| 609 |
+
|
| 610 |
+
# Process the question
|
| 611 |
while self.state.current_step < self.state.max_steps:
|
| 612 |
step_result = await self._process_step(question)
|
| 613 |
if step_result:
|
| 614 |
+
# Ensure we have a final answer
|
| 615 |
+
if not step_result.text.startswith("FINAL ANSWER:"):
|
| 616 |
+
step_result.text = f"FINAL ANSWER: {step_result.text}"
|
| 617 |
+
|
| 618 |
+
# Calculate processing time
|
| 619 |
processing_time = (datetime.now() - start_time).total_seconds()
|
| 620 |
step_result.processing_time = processing_time
|
| 621 |
+
|
| 622 |
+
# Clean up any temporary files
|
| 623 |
+
await self._cleanup_attachments()
|
| 624 |
+
|
| 625 |
return step_result
|
| 626 |
|
| 627 |
self.state.current_step += 1
|
| 628 |
|
| 629 |
+
# If we reach max steps without an answer, provide a clear error
|
| 630 |
return Answer(
|
| 631 |
+
text="FINAL ANSWER: Unable to determine answer within maximum steps",
|
| 632 |
confidence=0.0,
|
| 633 |
+
reasoning_trace=["Maximum steps reached without finding conclusive answer"],
|
| 634 |
tools_used=self.state.tools_used,
|
| 635 |
processing_time=(datetime.now() - start_time).total_seconds()
|
| 636 |
)
|
|
|
|
| 638 |
except Exception as e:
|
| 639 |
logger.error(f"Error processing question: {str(e)}")
|
| 640 |
return Answer(
|
| 641 |
+
text=f"FINAL ANSWER: Error processing question - {str(e)}",
|
| 642 |
confidence=0.0,
|
| 643 |
reasoning_trace=["Error occurred during processing"],
|
| 644 |
tools_used=[],
|
| 645 |
processing_time=(datetime.now() - start_time).total_seconds()
|
| 646 |
)
|
| 647 |
|
| 648 |
+
async def _download_and_process_attachment(self, attachment: str) -> Optional[str]:
|
| 649 |
+
"""Download and process an attachment, returning its local path"""
|
| 650 |
+
try:
|
| 651 |
+
# Determine file type and appropriate subdirectory
|
| 652 |
+
file_type = attachment.split('.')[-1].lower() if '.' in attachment else 'unknown'
|
| 653 |
+
subdir = {
|
| 654 |
+
'xlsx': 'data',
|
| 655 |
+
'xls': 'data',
|
| 656 |
+
'csv': 'data',
|
| 657 |
+
'txt': 'text',
|
| 658 |
+
'py': 'text',
|
| 659 |
+
'mp3': 'media',
|
| 660 |
+
'wav': 'media',
|
| 661 |
+
'mp4': 'media',
|
| 662 |
+
'jpg': 'media',
|
| 663 |
+
'png': 'media'
|
| 664 |
+
}.get(file_type, 'other')
|
| 665 |
+
|
| 666 |
+
# Create directory if it doesn't exist
|
| 667 |
+
base_dir = Path("downloaded_gaia_files")
|
| 668 |
+
file_dir = base_dir / subdir
|
| 669 |
+
file_dir.mkdir(parents=True, exist_ok=True)
|
| 670 |
+
|
| 671 |
+
# Download file
|
| 672 |
+
file_path = file_dir / attachment
|
| 673 |
+
if not file_path.exists():
|
| 674 |
+
# Implement actual download logic here
|
| 675 |
+
# For now, create an empty file as placeholder
|
| 676 |
+
file_path.touch()
|
| 677 |
+
|
| 678 |
+
return str(file_path)
|
| 679 |
+
except Exception as e:
|
| 680 |
+
logger.error(f"Error processing attachment {attachment}: {str(e)}")
|
| 681 |
+
return None
|
| 682 |
+
|
| 683 |
+
async def _cleanup_attachments(self):
|
| 684 |
+
"""Clean up any temporary files created during processing"""
|
| 685 |
+
try:
|
| 686 |
+
base_dir = Path("downloaded_gaia_files")
|
| 687 |
+
if base_dir.exists():
|
| 688 |
+
for path in base_dir.glob("**/*"):
|
| 689 |
+
if path.is_file():
|
| 690 |
+
path.unlink()
|
| 691 |
+
except Exception as e:
|
| 692 |
+
logger.error(f"Error cleaning up attachments: {str(e)}")
|
| 693 |
+
|
| 694 |
async def _process_step(self, question: Question) -> Optional[Answer]:
|
| 695 |
"""Process a single step with enhanced error handling and attachment processing"""
|
| 696 |
try:
|