Spaces:
No application file
No application file
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,1127 +1,599 @@
|
|
| 1 |
-
import
|
| 2 |
-
import
|
| 3 |
-
|
| 4 |
-
# Add the current directory to Python path
|
| 5 |
-
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
| 6 |
-
|
| 7 |
-
from typing import List, Dict, Any, Optional, Union
|
| 8 |
-
from pydantic import BaseModel, Field, field_validator
|
| 9 |
-
import logging
|
| 10 |
-
from pathlib import Path
|
| 11 |
-
import json
|
| 12 |
import asyncio
|
| 13 |
-
|
|
|
|
|
|
|
| 14 |
from datetime import datetime
|
| 15 |
-
|
| 16 |
-
import
|
| 17 |
-
|
| 18 |
-
import gradio as gr
|
| 19 |
-
from fastapi import FastAPI, HTTPException
|
| 20 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 21 |
-
import pandas as pd
|
| 22 |
-
from openai import OpenAI, AsyncOpenAI
|
| 23 |
-
import requests
|
| 24 |
-
from tenacity import retry, stop_after_attempt, wait_exponential
|
| 25 |
import re
|
| 26 |
import aiohttp
|
| 27 |
-
import
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
handlers=[
|
| 35 |
-
logging.FileHandler("agent.log"),
|
| 36 |
-
logging.StreamHandler()
|
| 37 |
-
]
|
| 38 |
)
|
| 39 |
-
|
| 40 |
|
| 41 |
-
#
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
return v
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
-
|
| 89 |
-
"""
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
attachments: Optional[List[str]] = None
|
| 93 |
-
metadata: Dict[str, Any] = Field(default_factory=dict)
|
| 94 |
-
priority: int = Field(default=1, ge=1, le=5)
|
| 95 |
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
def validate_text(cls, v: str) -> str:
|
| 99 |
-
if not v or not v.strip():
|
| 100 |
-
raise ValueError("Question text cannot be empty")
|
| 101 |
-
return v.strip()
|
| 102 |
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
metadata={
|
| 111 |
-
'task_id': data.get('task_id', ''),
|
| 112 |
-
'original_data': data
|
| 113 |
-
}
|
| 114 |
-
)
|
| 115 |
-
|
| 116 |
-
class Answer(BaseModel):
|
| 117 |
-
"""Enhanced answer structure with validation"""
|
| 118 |
-
text: str
|
| 119 |
-
confidence: float
|
| 120 |
-
reasoning_trace: List[str]
|
| 121 |
-
tools_used: List[str]
|
| 122 |
-
processing_time: float
|
| 123 |
-
timestamp: datetime = Field(default_factory=datetime.now)
|
| 124 |
-
metadata: Dict[str, Any] = Field(default_factory=dict)
|
| 125 |
|
| 126 |
-
|
| 127 |
-
@classmethod
|
| 128 |
-
def validate_confidence(cls, v: float) -> float:
|
| 129 |
-
if not 0 <= v <= 1:
|
| 130 |
-
raise ValueError("Confidence must be between 0 and 1")
|
| 131 |
-
return v
|
| 132 |
|
| 133 |
-
|
| 134 |
-
"""
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
extra = "allow"
|
| 143 |
-
|
| 144 |
-
async def execute(self, input_data: Any) -> ToolResult:
|
| 145 |
-
start_time = datetime.now()
|
| 146 |
-
try:
|
| 147 |
-
result = await self._execute_impl(input_data)
|
| 148 |
-
execution_time = (datetime.now() - start_time).total_seconds()
|
| 149 |
-
return ToolResult(
|
| 150 |
-
success=True,
|
| 151 |
-
result=result,
|
| 152 |
-
execution_time=execution_time,
|
| 153 |
-
metadata={"tool_version": self.version}
|
| 154 |
-
)
|
| 155 |
-
except Exception as e:
|
| 156 |
-
logger.error(f"Tool execution error in {self.name}: {str(e)}")
|
| 157 |
-
return ToolResult(
|
| 158 |
-
success=False,
|
| 159 |
-
result=None,
|
| 160 |
-
error_message=str(e),
|
| 161 |
-
execution_time=(datetime.now() - start_time).total_seconds()
|
| 162 |
-
)
|
| 163 |
-
|
| 164 |
-
async def _execute_impl(self, input_data: Any) -> Any:
|
| 165 |
-
raise NotImplementedError
|
| 166 |
|
| 167 |
-
|
| 168 |
-
"""
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
-
|
| 192 |
-
"""
|
| 193 |
-
|
| 194 |
-
super().__init__(
|
| 195 |
-
name="local_search",
|
| 196 |
-
description="Search and analyze content including text, code, Excel files, and other attachments",
|
| 197 |
-
type=ToolType.LOCAL_SEARCH
|
| 198 |
-
)
|
| 199 |
-
self.knowledge_base_path = knowledge_base_path
|
| 200 |
-
self._load_knowledge_base()
|
| 201 |
|
| 202 |
-
|
| 203 |
-
"""Initialize the knowledge base directories"""
|
| 204 |
try:
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
dir_path.mkdir(parents=True, exist_ok=True)
|
| 209 |
-
logger.info(f"Knowledge base initialized at {self.knowledge_base_path}")
|
| 210 |
except Exception as e:
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
async def _execute_impl(self, input_data: Union[str, Dict[str, Any]]) -> Any:
|
| 215 |
-
"""Enhanced execution with better input handling"""
|
| 216 |
-
try:
|
| 217 |
-
# Handle string input as direct query
|
| 218 |
-
if isinstance(input_data, str):
|
| 219 |
-
query = input_data
|
| 220 |
-
file_type = None
|
| 221 |
else:
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
|
|
|
|
|
|
| 242 |
|
| 243 |
-
|
| 244 |
-
self,
|
| 245 |
-
query: str,
|
| 246 |
-
file_type: Optional[str] = None
|
| 247 |
-
) -> List[Dict[str, Any]]:
|
| 248 |
-
"""Enhanced knowledge base search with better file handling"""
|
| 249 |
-
results = []
|
| 250 |
-
try:
|
| 251 |
-
# Normalize query
|
| 252 |
-
query = query.lower().strip()
|
| 253 |
-
|
| 254 |
-
# Search in appropriate directory based on file type
|
| 255 |
-
if file_type:
|
| 256 |
-
search_dirs = [self.knowledge_base_path / self._get_subdir(file_type)]
|
| 257 |
-
else:
|
| 258 |
-
search_dirs = [
|
| 259 |
-
self.knowledge_base_path / subdir
|
| 260 |
-
for subdir in ['text', 'data', 'media']
|
| 261 |
-
]
|
| 262 |
-
|
| 263 |
-
for search_dir in search_dirs:
|
| 264 |
-
if not search_dir.exists():
|
| 265 |
-
continue
|
| 266 |
-
|
| 267 |
-
for file_path in search_dir.glob("**/*"):
|
| 268 |
-
if not file_path.is_file():
|
| 269 |
-
continue
|
| 270 |
-
|
| 271 |
-
try:
|
| 272 |
-
content = await self._read_file_content(file_path)
|
| 273 |
-
if not content:
|
| 274 |
-
continue
|
| 275 |
-
|
| 276 |
-
# Calculate relevance score
|
| 277 |
-
relevance = self._calculate_relevance(query, content)
|
| 278 |
-
if relevance > 0:
|
| 279 |
-
results.append({
|
| 280 |
-
"file": str(file_path.relative_to(self.knowledge_base_path)),
|
| 281 |
-
"content": content[:1000], # Limit content size
|
| 282 |
-
"relevance_score": relevance,
|
| 283 |
-
"file_type": file_path.suffix[1:] if file_path.suffix else "unknown"
|
| 284 |
-
})
|
| 285 |
-
except Exception as e:
|
| 286 |
-
logger.error(f"Error processing file {file_path}: {str(e)}")
|
| 287 |
-
continue
|
| 288 |
-
|
| 289 |
-
# Sort by relevance
|
| 290 |
-
results.sort(key=lambda x: x['relevance_score'], reverse=True)
|
| 291 |
-
return results[:5] # Return top 5 results
|
| 292 |
-
|
| 293 |
-
except Exception as e:
|
| 294 |
-
logger.error(f"Error in knowledge base search: {str(e)}")
|
| 295 |
-
return []
|
| 296 |
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
return df.to_string()
|
| 309 |
-
|
| 310 |
-
elif suffix in ['.txt', '.py', '.json']:
|
| 311 |
-
async with aiofiles.open(file_path, 'r') as f:
|
| 312 |
-
return await f.read()
|
| 313 |
-
|
| 314 |
-
elif suffix in ['.mp3', '.wav', '.mp4', '.jpg', '.png']:
|
| 315 |
-
# For media files, return metadata
|
| 316 |
-
return f"Media file: {file_path.name}, type: {suffix[1:]}"
|
| 317 |
-
|
| 318 |
-
else:
|
| 319 |
-
logger.warning(f"Unsupported file type: {suffix}")
|
| 320 |
-
return None
|
| 321 |
-
|
| 322 |
-
except Exception as e:
|
| 323 |
-
logger.error(f"Error reading file {file_path}: {str(e)}")
|
| 324 |
-
return None
|
| 325 |
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
# Convert content to string if it's not already
|
| 330 |
-
if not isinstance(content, str):
|
| 331 |
-
content = str(content)
|
| 332 |
-
|
| 333 |
-
# Normalize text
|
| 334 |
-
query = query.lower()
|
| 335 |
-
content = content.lower()
|
| 336 |
-
|
| 337 |
-
# Split into terms
|
| 338 |
-
query_terms = set(query.split())
|
| 339 |
-
content_terms = set(content.split())
|
| 340 |
-
|
| 341 |
-
# Calculate various metrics
|
| 342 |
-
term_overlap = len(query_terms & content_terms)
|
| 343 |
-
exact_matches = content.count(query)
|
| 344 |
-
term_frequency = sum(content.count(term) for term in query_terms)
|
| 345 |
-
|
| 346 |
-
# Combine metrics into final score
|
| 347 |
-
score = (
|
| 348 |
-
0.5 * (term_overlap / len(query_terms) if query_terms else 0) +
|
| 349 |
-
0.3 * (exact_matches > 0) +
|
| 350 |
-
0.2 * (term_frequency / len(content.split()) if content else 0)
|
| 351 |
-
)
|
| 352 |
-
|
| 353 |
-
return min(1.0, score) # Normalize to [0, 1]
|
| 354 |
-
|
| 355 |
-
except Exception as e:
|
| 356 |
-
logger.error(f"Error calculating relevance: {str(e)}")
|
| 357 |
-
return 0.0
|
| 358 |
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
file_type = file_type.lower()
|
| 362 |
-
if file_type in ['xlsx', 'xls', 'csv']:
|
| 363 |
-
return 'data'
|
| 364 |
-
elif file_type in ['txt', 'py', 'json']:
|
| 365 |
-
return 'text'
|
| 366 |
-
elif file_type in ['mp3', 'wav', 'mp4', 'jpg', 'png']:
|
| 367 |
-
return 'media'
|
| 368 |
-
else:
|
| 369 |
-
return 'other'
|
| 370 |
|
| 371 |
-
|
| 372 |
-
"""Perform fuzzy matching when exact match fails"""
|
| 373 |
-
results = []
|
| 374 |
-
try:
|
| 375 |
-
# Implement fuzzy matching logic here
|
| 376 |
-
# For now, just do a more lenient search
|
| 377 |
-
terms = query.lower().split()
|
| 378 |
-
for term in terms:
|
| 379 |
-
term_results = await self._search_knowledge_base(term)
|
| 380 |
-
results.extend(term_results)
|
| 381 |
-
|
| 382 |
-
# Remove duplicates and sort by relevance
|
| 383 |
-
seen = set()
|
| 384 |
-
unique_results = []
|
| 385 |
-
for result in results:
|
| 386 |
-
file_key = result['file']
|
| 387 |
-
if file_key not in seen:
|
| 388 |
-
seen.add(file_key)
|
| 389 |
-
unique_results.append(result)
|
| 390 |
-
|
| 391 |
-
return sorted(unique_results, key=lambda x: x['relevance_score'], reverse=True)[:5]
|
| 392 |
-
|
| 393 |
-
except Exception as e:
|
| 394 |
-
logger.error(f"Error in fuzzy search: {str(e)}")
|
| 395 |
-
return []
|
| 396 |
|
| 397 |
-
class
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 406 |
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
|
|
|
|
|
|
| 411 |
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
elif operation == "retrieve":
|
| 416 |
-
return self._memory.get(key)
|
| 417 |
-
elif operation == "list":
|
| 418 |
-
return list(self._memory.keys())
|
| 419 |
-
else:
|
| 420 |
-
raise ValueError(f"Unknown memory operation: {operation}")
|
| 421 |
-
|
| 422 |
-
class ImprovedAgent:
|
| 423 |
-
"""Enhanced GAIA agent implementation with improved error handling and processing"""
|
| 424 |
-
def __init__(self, openai_module, tools: List[Tool]):
|
| 425 |
-
self.openai = openai_module
|
| 426 |
-
self.tools = {tool.name: tool for tool in tools}
|
| 427 |
-
self.state = AgentState()
|
| 428 |
-
self._executor = ThreadPoolExecutor(max_workers=3)
|
| 429 |
|
| 430 |
-
|
| 431 |
-
You must use the available tools to find answers rather than saying you can't access information.
|
| 432 |
-
Your available tools are:
|
| 433 |
-
- calculator: For mathematical calculations
|
| 434 |
-
- local_search: To search the knowledge base for relevant information
|
| 435 |
-
- memory: To store and retrieve information across steps
|
| 436 |
-
|
| 437 |
-
When answering:
|
| 438 |
-
1. ALWAYS use the tools to find information before saying you can't answer
|
| 439 |
-
2. Use local_search to find relevant information in the knowledge base
|
| 440 |
-
3. Use the calculator for any numerical calculations
|
| 441 |
-
4. Use memory to store important findings for multi-step reasoning
|
| 442 |
-
5. For file-related questions:
|
| 443 |
-
- Excel files: Use local_search with file_type='xlsx' to analyze data
|
| 444 |
-
- Python files: Use local_search with file_type='py' to analyze code
|
| 445 |
-
- Text files: Use local_search with file_type='txt' to read content
|
| 446 |
-
- Media files: Extract available metadata and describe what you find
|
| 447 |
-
6. NEVER say you can't process a file without first trying local_search
|
| 448 |
-
7. ALWAYS provide a complete answer, don't just say you will search
|
| 449 |
-
8. If you need multiple steps, execute them all before responding
|
| 450 |
-
9. Format your final answer exactly as specified in the question
|
| 451 |
-
10. If no format is specified, use: FINAL ANSWER: [your answer]
|
| 452 |
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 463 |
try:
|
| 464 |
-
#
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
)
|
| 468 |
-
|
| 469 |
-
client = AsyncOpenAI(api_key=self.openai.api_key)
|
| 470 |
-
response = await client.chat.completions.create(
|
| 471 |
-
model="gpt-4",
|
| 472 |
-
messages=[
|
| 473 |
-
{"role": "system", "content": self.system_prompt + tool_context},
|
| 474 |
-
{"role": "user", "content": context}
|
| 475 |
-
],
|
| 476 |
-
temperature=0.1,
|
| 477 |
-
max_tokens=1000
|
| 478 |
-
)
|
| 479 |
-
return response.choices[0].message.content
|
| 480 |
except Exception as e:
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 489 |
|
| 490 |
-
if question
|
| 491 |
-
|
| 492 |
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
if self.state.memory:
|
| 497 |
-
context_parts.append("\nRelevant memory items:")
|
| 498 |
-
for key, value in self.state.memory.items():
|
| 499 |
-
context_parts.append(f"- {key}: {value}")
|
| 500 |
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
for result in self.state.intermediate_results:
|
| 504 |
-
if result.get('reasoning'):
|
| 505 |
-
context_parts.append("Reasoning: " + " ".join(result['reasoning']))
|
| 506 |
-
if result.get('tool_results'):
|
| 507 |
-
for tool_result in result['tool_results']:
|
| 508 |
-
if tool_result['status'] == 'success':
|
| 509 |
-
context_parts.append(f"Tool {tool_result['tool']} result: {tool_result['result']}")
|
| 510 |
|
| 511 |
-
#
|
| 512 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 513 |
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
def _parse_model_response(self, response: str) -> Dict[str, Any]:
|
| 517 |
-
"""Enhanced response parser with better error handling"""
|
| 518 |
try:
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
'reasoning': [],
|
| 522 |
-
'tool_requests': [],
|
| 523 |
-
'confidence': 0.0,
|
| 524 |
-
'final_answer': None,
|
| 525 |
-
'is_final': False
|
| 526 |
-
}
|
| 527 |
-
|
| 528 |
-
current_section = None
|
| 529 |
-
for line in lines:
|
| 530 |
-
line = line.strip()
|
| 531 |
-
if not line:
|
| 532 |
-
continue
|
| 533 |
-
|
| 534 |
-
if line.startswith('REASONING:'):
|
| 535 |
-
current_section = 'reasoning'
|
| 536 |
-
continue
|
| 537 |
-
elif line.startswith('TOOL USAGE:'):
|
| 538 |
-
current_section = 'tool_usage'
|
| 539 |
-
continue
|
| 540 |
-
elif line.startswith('CONFIDENCE:'):
|
| 541 |
-
try:
|
| 542 |
-
confidence = float(line.split(':')[1].strip().split()[0])
|
| 543 |
-
parsed['confidence'] = max(0.0, min(1.0, confidence))
|
| 544 |
-
except (ValueError, IndexError):
|
| 545 |
-
logger.warning("Could not parse confidence score, defaulting to 0.0")
|
| 546 |
-
continue
|
| 547 |
-
elif line.startswith('FINAL ANSWER:'):
|
| 548 |
-
current_section = 'final_answer'
|
| 549 |
-
parsed['is_final'] = True
|
| 550 |
-
parsed['final_answer'] = line.split(':', 1)[1].strip()
|
| 551 |
-
continue
|
| 552 |
-
|
| 553 |
-
if current_section == 'reasoning':
|
| 554 |
-
parsed['reasoning'].append(line)
|
| 555 |
-
elif current_section == 'tool_usage':
|
| 556 |
-
# Look for tool usage in the entire line
|
| 557 |
-
for tool_name in self.tools.keys():
|
| 558 |
-
if tool_name.lower() in line.lower():
|
| 559 |
-
parsed['tool_requests'].append({
|
| 560 |
-
'tool': tool_name,
|
| 561 |
-
'input': line
|
| 562 |
-
})
|
| 563 |
-
|
| 564 |
-
# If no tool requests were found but tools were mentioned in reasoning
|
| 565 |
-
if not parsed['tool_requests']:
|
| 566 |
-
for line in parsed['reasoning']:
|
| 567 |
-
for tool_name in self.tools.keys():
|
| 568 |
-
if tool_name.lower() in line.lower():
|
| 569 |
-
parsed['tool_requests'].append({
|
| 570 |
-
'tool': tool_name,
|
| 571 |
-
'input': line
|
| 572 |
-
})
|
| 573 |
-
|
| 574 |
-
return parsed
|
| 575 |
except Exception as e:
|
| 576 |
-
|
| 577 |
-
return {'is_final': True, 'final_answer': "Error processing response"}
|
| 578 |
-
|
| 579 |
-
async def _execute_tools(self, tool_requests: List[Dict[str, str]]) -> List[Dict[str, Any]]:
|
| 580 |
-
"""Execute tools with concurrent processing"""
|
| 581 |
-
async def execute_tool(request):
|
| 582 |
-
tool_name = request['tool']
|
| 583 |
-
tool = self.tools.get(tool_name)
|
| 584 |
-
if not tool:
|
| 585 |
-
return {
|
| 586 |
-
'tool': tool_name,
|
| 587 |
-
'status': 'error',
|
| 588 |
-
'error': f"Tool {tool_name} not found"
|
| 589 |
-
}
|
| 590 |
-
|
| 591 |
-
try:
|
| 592 |
-
result = await tool.execute(request['input'])
|
| 593 |
-
return {
|
| 594 |
-
'tool': tool_name,
|
| 595 |
-
'status': 'success',
|
| 596 |
-
'result': result
|
| 597 |
-
}
|
| 598 |
-
except Exception as e:
|
| 599 |
-
logger.error(f"Error executing tool {tool_name}: {str(e)}")
|
| 600 |
-
return {
|
| 601 |
-
'tool': tool_name,
|
| 602 |
-
'status': 'error',
|
| 603 |
-
'error': str(e)
|
| 604 |
-
}
|
| 605 |
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
|
|
|
|
|
|
|
|
|
| 613 |
|
| 614 |
-
#
|
| 615 |
-
|
| 616 |
-
question = Question(text=question, context=context)
|
| 617 |
|
| 618 |
-
|
| 619 |
-
self.state = AgentState() # Reset state for new question
|
| 620 |
-
|
| 621 |
-
# First, check for and download any attachments
|
| 622 |
-
if question.attachments:
|
| 623 |
-
for attachment in question.attachments:
|
| 624 |
-
file_path = await self._download_and_process_attachment(attachment)
|
| 625 |
-
if file_path:
|
| 626 |
-
self.state.memory[f"attachment_{attachment}"] = file_path
|
| 627 |
-
|
| 628 |
-
# Process the question
|
| 629 |
-
while self.state.current_step < self.state.max_steps:
|
| 630 |
-
step_result = await self._process_step(question)
|
| 631 |
-
if step_result:
|
| 632 |
-
# Ensure we have a final answer
|
| 633 |
-
if not step_result.text.startswith("FINAL ANSWER:"):
|
| 634 |
-
step_result.text = f"FINAL ANSWER: {step_result.text}"
|
| 635 |
-
|
| 636 |
-
# Calculate processing time
|
| 637 |
-
processing_time = (datetime.now() - start_time).total_seconds()
|
| 638 |
-
step_result.processing_time = processing_time
|
| 639 |
-
|
| 640 |
-
# Clean up any temporary files
|
| 641 |
-
await self._cleanup_attachments()
|
| 642 |
-
|
| 643 |
-
return step_result
|
| 644 |
-
|
| 645 |
-
self.state.current_step += 1
|
| 646 |
-
|
| 647 |
-
# If we reach max steps without an answer, provide a clear error
|
| 648 |
-
return Answer(
|
| 649 |
-
text="FINAL ANSWER: Unable to determine answer within maximum steps",
|
| 650 |
-
confidence=0.0,
|
| 651 |
-
reasoning_trace=["Maximum steps reached without finding conclusive answer"],
|
| 652 |
-
tools_used=self.state.tools_used,
|
| 653 |
-
processing_time=(datetime.now() - start_time).total_seconds()
|
| 654 |
-
)
|
| 655 |
-
|
| 656 |
-
except Exception as e:
|
| 657 |
-
logger.error(f"Error processing question: {str(e)}")
|
| 658 |
-
return Answer(
|
| 659 |
-
text=f"FINAL ANSWER: Error processing question - {str(e)}",
|
| 660 |
-
confidence=0.0,
|
| 661 |
-
reasoning_trace=["Error occurred during processing"],
|
| 662 |
-
tools_used=[],
|
| 663 |
-
processing_time=(datetime.now() - start_time).total_seconds()
|
| 664 |
-
)
|
| 665 |
-
|
| 666 |
-
async def _download_and_process_attachment(self, attachment: str) -> Optional[str]:
|
| 667 |
-
"""Download and process an attachment, returning its local path"""
|
| 668 |
-
try:
|
| 669 |
-
# Determine file type and appropriate subdirectory
|
| 670 |
-
file_type = attachment.split('.')[-1].lower() if '.' in attachment else 'unknown'
|
| 671 |
-
subdir = {
|
| 672 |
-
'xlsx': 'data',
|
| 673 |
-
'xls': 'data',
|
| 674 |
-
'csv': 'data',
|
| 675 |
-
'txt': 'text',
|
| 676 |
-
'py': 'text',
|
| 677 |
-
'mp3': 'media',
|
| 678 |
-
'wav': 'media',
|
| 679 |
-
'mp4': 'media',
|
| 680 |
-
'jpg': 'media',
|
| 681 |
-
'png': 'media'
|
| 682 |
-
}.get(file_type, 'other')
|
| 683 |
-
|
| 684 |
-
# Create directory if it doesn't exist
|
| 685 |
-
base_dir = Path("downloaded_gaia_files")
|
| 686 |
-
file_dir = base_dir / subdir
|
| 687 |
-
file_dir.mkdir(parents=True, exist_ok=True)
|
| 688 |
-
|
| 689 |
-
# Download file
|
| 690 |
-
file_path = file_dir / attachment
|
| 691 |
-
if not file_path.exists():
|
| 692 |
-
# Implement actual download logic here
|
| 693 |
-
# For now, create an empty file as placeholder
|
| 694 |
-
file_path.touch()
|
| 695 |
-
|
| 696 |
-
return str(file_path)
|
| 697 |
-
except Exception as e:
|
| 698 |
-
logger.error(f"Error processing attachment {attachment}: {str(e)}")
|
| 699 |
-
return None
|
| 700 |
-
|
| 701 |
-
async def _cleanup_attachments(self):
|
| 702 |
-
"""Clean up any temporary files created during processing"""
|
| 703 |
-
try:
|
| 704 |
-
base_dir = Path("downloaded_gaia_files")
|
| 705 |
-
if base_dir.exists():
|
| 706 |
-
for path in base_dir.glob("**/*"):
|
| 707 |
-
if path.is_file():
|
| 708 |
-
path.unlink()
|
| 709 |
-
except Exception as e:
|
| 710 |
-
logger.error(f"Error cleaning up attachments: {str(e)}")
|
| 711 |
-
|
| 712 |
-
async def _process_step(self, question: Question) -> Optional[Answer]:
|
| 713 |
-
"""Process a single step with enhanced error handling and attachment processing"""
|
| 714 |
-
try:
|
| 715 |
-
# Prepare the context for the model
|
| 716 |
-
context = self._prepare_context(question)
|
| 717 |
-
|
| 718 |
-
# Get model's analysis of the next step
|
| 719 |
-
response = await self._get_model_response(context)
|
| 720 |
-
|
| 721 |
-
# Parse the response to extract reasoning and tool requests
|
| 722 |
-
parsed = self._parse_model_response(response)
|
| 723 |
-
|
| 724 |
-
# Update state with reasoning
|
| 725 |
-
self.state.intermediate_results.append({
|
| 726 |
-
'step': self.state.current_step,
|
| 727 |
-
'reasoning': parsed.get('reasoning', [])
|
| 728 |
-
})
|
| 729 |
-
|
| 730 |
-
# Process attachments if present
|
| 731 |
-
if question.attachments:
|
| 732 |
-
for attachment in question.attachments:
|
| 733 |
-
# Determine attachment type
|
| 734 |
-
if attachment.endswith('.xlsx') or attachment.endswith('.xls'):
|
| 735 |
-
parsed['tool_requests'].append({
|
| 736 |
-
'tool': 'local_search',
|
| 737 |
-
'input': {'attachment': attachment, 'attachment_type': 'excel'}
|
| 738 |
-
})
|
| 739 |
-
elif attachment.endswith('.py'):
|
| 740 |
-
parsed['tool_requests'].append({
|
| 741 |
-
'tool': 'local_search',
|
| 742 |
-
'input': {'attachment': attachment, 'attachment_type': 'python'}
|
| 743 |
-
})
|
| 744 |
-
elif attachment.endswith(('.mp3', '.wav', '.m4a')):
|
| 745 |
-
parsed['tool_requests'].append({
|
| 746 |
-
'tool': 'local_search',
|
| 747 |
-
'input': {'attachment': attachment, 'attachment_type': 'audio'}
|
| 748 |
-
})
|
| 749 |
-
elif attachment.endswith(('.mp4', '.avi', '.mov')):
|
| 750 |
-
parsed['tool_requests'].append({
|
| 751 |
-
'tool': 'local_search',
|
| 752 |
-
'input': {'attachment': attachment, 'attachment_type': 'video'}
|
| 753 |
-
})
|
| 754 |
-
|
| 755 |
-
# If tools are requested, execute them
|
| 756 |
-
if parsed.get('tool_requests'):
|
| 757 |
-
tool_results = await self._execute_tools(parsed['tool_requests'])
|
| 758 |
-
# Add tool results to state
|
| 759 |
-
self.state.tools_used.extend([req['tool'] for req in parsed['tool_requests']])
|
| 760 |
-
self.state.intermediate_results[-1]['tool_results'] = tool_results
|
| 761 |
-
|
| 762 |
-
# Process tool results
|
| 763 |
-
for result in tool_results:
|
| 764 |
-
if result['status'] == 'success' and isinstance(result['result'], dict):
|
| 765 |
-
if 'error' in result['result']:
|
| 766 |
-
parsed['reasoning'].append(f"Tool error: {result['result']['error']}")
|
| 767 |
-
else:
|
| 768 |
-
self.state.memory[f"tool_result_{self.state.current_step}"] = result['result']
|
| 769 |
-
|
| 770 |
-
# If we need more processing, return None to continue
|
| 771 |
-
if not parsed.get('is_final', False):
|
| 772 |
-
return None
|
| 773 |
-
|
| 774 |
-
# If we have a final answer, construct and return it
|
| 775 |
-
if parsed.get('final_answer'):
|
| 776 |
-
# Extract reasoning traces as strings
|
| 777 |
-
reasoning_trace = []
|
| 778 |
-
for step in self.state.intermediate_results:
|
| 779 |
-
# Add reasoning from the step
|
| 780 |
-
if step.get('reasoning'):
|
| 781 |
-
reasoning_trace.extend(step['reasoning'])
|
| 782 |
-
# Add tool results if any
|
| 783 |
-
if step.get('tool_results'):
|
| 784 |
-
for tool_result in step['tool_results']:
|
| 785 |
-
if tool_result['status'] == 'success':
|
| 786 |
-
if isinstance(tool_result['result'], dict) and 'error' in tool_result['result']:
|
| 787 |
-
reasoning_trace.append(f"Tool {tool_result['tool']} error: {tool_result['result']['error']}")
|
| 788 |
-
else:
|
| 789 |
-
reasoning_trace.append(f"Tool {tool_result['tool']} result: {str(tool_result['result'])}")
|
| 790 |
-
|
| 791 |
-
return Answer(
|
| 792 |
-
text=parsed['final_answer'],
|
| 793 |
-
confidence=parsed.get('confidence', 0.0),
|
| 794 |
-
reasoning_trace=reasoning_trace,
|
| 795 |
-
tools_used=self.state.tools_used,
|
| 796 |
-
processing_time=0.0, # Will be updated in process_question
|
| 797 |
-
metadata={'memory_used': bool(self.state.memory)}
|
| 798 |
-
)
|
| 799 |
-
|
| 800 |
-
return None
|
| 801 |
-
|
| 802 |
-
except Exception as e:
|
| 803 |
-
logger.error(f"Error in processing step: {str(e)}")
|
| 804 |
-
return None
|
| 805 |
|
| 806 |
-
|
| 807 |
-
|
| 808 |
-
tools = [
|
| 809 |
-
Calculator(),
|
| 810 |
-
LocalSearch(knowledge_base_path),
|
| 811 |
-
Memory()
|
| 812 |
-
]
|
| 813 |
-
return ImprovedAgent(openai_module, tools)
|
| 814 |
|
| 815 |
-
#
|
| 816 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 817 |
|
| 818 |
-
|
| 819 |
-
|
| 820 |
-
|
| 821 |
-
|
| 822 |
-
|
| 823 |
-
|
|
|
|
|
|
|
|
|
|
| 824 |
)
|
| 825 |
|
| 826 |
-
|
| 827 |
-
|
| 828 |
-
|
| 829 |
-
|
| 830 |
-
|
| 831 |
-
|
| 832 |
-
|
| 833 |
-
|
| 834 |
-
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
|
| 843 |
-
|
| 844 |
-
|
| 845 |
-
|
| 846 |
-
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
|
| 850 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 851 |
else:
|
| 852 |
-
|
| 853 |
-
|
| 854 |
-
|
| 855 |
-
|
| 856 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 857 |
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
base_dir = Path("downloaded_gaia_files")
|
| 861 |
-
for subdir in ['text', 'data', 'media', 'other']:
|
| 862 |
-
(base_dir / subdir).mkdir(parents=True, exist_ok=True)
|
| 863 |
-
logger.info("Created knowledge base directories successfully")
|
| 864 |
-
except Exception as e:
|
| 865 |
-
logger.error(f"Error creating directories: {str(e)}")
|
| 866 |
-
raise
|
| 867 |
|
| 868 |
-
#
|
| 869 |
-
|
| 870 |
-
|
| 871 |
-
# Get API key from environment (HF Secrets)
|
| 872 |
-
api_key = os.environ.get("OPENAI_API_KEY", "").strip()
|
| 873 |
-
if not api_key:
|
| 874 |
-
raise ValueError("OPENAI_API_KEY not found in environment variables")
|
| 875 |
-
|
| 876 |
-
# Configure OpenAI with cleaned API key
|
| 877 |
-
client = OpenAI(api_key=api_key.strip())
|
| 878 |
-
|
| 879 |
-
# Test the API key
|
| 880 |
-
test_response = client.chat.completions.create(
|
| 881 |
model="gpt-4",
|
| 882 |
-
|
| 883 |
-
|
| 884 |
)
|
| 885 |
-
print("OpenAI initialized successfully with GPT-4")
|
| 886 |
|
| 887 |
-
|
| 888 |
-
knowledge_base_path = Path(__file__).parent / "knowledge_base"
|
| 889 |
-
agent = create_agent(client, knowledge_base_path)
|
| 890 |
-
except Exception as e:
|
| 891 |
-
print(f"Error initializing OpenAI or agent: {e}")
|
| 892 |
-
|
| 893 |
-
# Add API interaction functions
|
| 894 |
-
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
|
| 895 |
-
async def api_get_questions() -> List[Dict[str, Any]]:
|
| 896 |
-
"""Fetch questions from the course API with retry logic."""
|
| 897 |
-
try:
|
| 898 |
-
logger.info(f"Fetching questions from: {config.api_base_url}/questions")
|
| 899 |
-
async with aiohttp.ClientSession() as session:
|
| 900 |
-
async with session.get(
|
| 901 |
-
f"{config.api_base_url}/questions",
|
| 902 |
-
headers=config.headers,
|
| 903 |
-
timeout=config.timeout
|
| 904 |
-
) as response:
|
| 905 |
-
if response.status != 200:
|
| 906 |
-
error_text = await response.text()
|
| 907 |
-
logger.error(f"API error (status {response.status}): {error_text}")
|
| 908 |
-
raise HTTPException(
|
| 909 |
-
status_code=response.status,
|
| 910 |
-
detail=f"API error: {error_text}"
|
| 911 |
-
)
|
| 912 |
-
|
| 913 |
-
questions = await response.json()
|
| 914 |
-
logger.info(f"Successfully fetched {len(questions)} questions")
|
| 915 |
-
return questions
|
| 916 |
-
|
| 917 |
-
except asyncio.TimeoutError:
|
| 918 |
-
logger.error("Timeout while fetching questions")
|
| 919 |
-
raise HTTPException(
|
| 920 |
-
status_code=504,
|
| 921 |
-
detail="Timeout while fetching questions"
|
| 922 |
-
)
|
| 923 |
-
except Exception as e:
|
| 924 |
-
logger.error(f"Error fetching questions: {str(e)}")
|
| 925 |
-
raise HTTPException(
|
| 926 |
-
status_code=500,
|
| 927 |
-
detail=f"Error fetching questions: {str(e)}"
|
| 928 |
-
)
|
| 929 |
-
|
| 930 |
-
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
|
| 931 |
-
async def api_submit_answers(
|
| 932 |
-
processed_answers: List[Dict[str, Any]],
|
| 933 |
-
username: str = config.username
|
| 934 |
-
) -> Dict[str, Any]:
|
| 935 |
-
"""Submit answers to the course API with retry logic."""
|
| 936 |
-
try:
|
| 937 |
-
# Validate answers format
|
| 938 |
-
for answer in processed_answers:
|
| 939 |
-
if 'task_id' not in answer or 'submitted_answer' not in answer:
|
| 940 |
-
raise ValueError(
|
| 941 |
-
"Invalid answer format. Each answer must contain 'task_id' and 'submitted_answer'"
|
| 942 |
-
)
|
| 943 |
-
|
| 944 |
-
submission_data = {
|
| 945 |
-
"username": username,
|
| 946 |
-
"agent_code": config.agent_code_identifier,
|
| 947 |
-
"answers": processed_answers
|
| 948 |
-
}
|
| 949 |
-
|
| 950 |
-
logger.info("=== Submission Details ===")
|
| 951 |
-
logger.info(f"Username: {username}")
|
| 952 |
-
logger.info(f"Agent Code: {config.agent_code_identifier}")
|
| 953 |
-
logger.info(f"Number of Answers: {len(processed_answers)}")
|
| 954 |
-
logger.debug(f"Sample answer format: {json.dumps(processed_answers[0], indent=2) if processed_answers else 'No answers'}")
|
| 955 |
-
logger.debug(f"Full submission data: {json.dumps(submission_data, indent=2)}")
|
| 956 |
-
|
| 957 |
-
async with aiohttp.ClientSession() as session:
|
| 958 |
-
async with session.post(
|
| 959 |
-
f"{config.api_base_url}/submit",
|
| 960 |
-
headers=config.headers,
|
| 961 |
-
json=submission_data,
|
| 962 |
-
timeout=config.timeout
|
| 963 |
-
) as response:
|
| 964 |
-
if response.status != 200:
|
| 965 |
-
error_text = await response.text()
|
| 966 |
-
logger.error(f"Submission error (status {response.status}): {error_text}")
|
| 967 |
-
raise HTTPException(
|
| 968 |
-
status_code=response.status,
|
| 969 |
-
detail=f"Submission error: {error_text}"
|
| 970 |
-
)
|
| 971 |
-
|
| 972 |
-
result = await response.json()
|
| 973 |
-
logger.info("Submission successful")
|
| 974 |
-
logger.debug(f"Submission response: {json.dumps(result, indent=2)}")
|
| 975 |
-
return result
|
| 976 |
-
|
| 977 |
-
except asyncio.TimeoutError:
|
| 978 |
-
logger.error("Timeout while submitting answers")
|
| 979 |
-
raise HTTPException(
|
| 980 |
-
status_code=504,
|
| 981 |
-
detail="Timeout while submitting answers"
|
| 982 |
-
)
|
| 983 |
-
except ValueError as e:
|
| 984 |
-
logger.error(f"Validation error: {str(e)}")
|
| 985 |
-
raise HTTPException(
|
| 986 |
-
status_code=400,
|
| 987 |
-
detail=str(e)
|
| 988 |
-
)
|
| 989 |
-
except Exception as e:
|
| 990 |
-
logger.error(f"Error submitting answers: {str(e)}")
|
| 991 |
-
raise HTTPException(
|
| 992 |
-
status_code=500,
|
| 993 |
-
detail=f"Error submitting answers: {str(e)}"
|
| 994 |
-
)
|
| 995 |
-
|
| 996 |
-
# Define the function before using it in the Gradio interface
|
| 997 |
-
async def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 998 |
-
"""Process and submit all questions with enhanced error handling."""
|
| 999 |
-
if not profile:
|
| 1000 |
-
return "Authentication required", None
|
| 1001 |
|
| 1002 |
-
|
| 1003 |
-
|
| 1004 |
-
questions = await api_get_questions()
|
| 1005 |
-
if not questions:
|
| 1006 |
-
logger.warning("No questions received from API")
|
| 1007 |
-
return "No questions available", None
|
| 1008 |
|
| 1009 |
-
|
| 1010 |
-
agent = create_agent(OpenAI(api_key=os.environ.get("OPENAI_API_KEY", "")), Path("knowledge_base"))
|
| 1011 |
-
|
| 1012 |
-
# Process questions
|
| 1013 |
-
processed_answers = []
|
| 1014 |
-
results_log = [] # Track detailed results for display
|
| 1015 |
-
|
| 1016 |
-
for question in questions:
|
| 1017 |
try:
|
| 1018 |
-
|
| 1019 |
-
|
| 1020 |
-
|
| 1021 |
-
|
| 1022 |
-
question_text = question.get('question', question.get('text', ''))
|
| 1023 |
-
if not question_text:
|
| 1024 |
-
logger.error(f"Question text not found in: {question}")
|
| 1025 |
-
continue
|
| 1026 |
-
|
| 1027 |
-
# Create Question object with proper validation
|
| 1028 |
-
agent_question = Question(
|
| 1029 |
-
text=question_text,
|
| 1030 |
-
context=question.get('context', ''),
|
| 1031 |
-
attachments=question.get('attachments', []),
|
| 1032 |
-
metadata={
|
| 1033 |
-
'task_id': question.get('task_id', ''),
|
| 1034 |
-
'original_data': question
|
| 1035 |
}
|
| 1036 |
)
|
| 1037 |
|
| 1038 |
-
|
| 1039 |
-
|
| 1040 |
-
|
| 1041 |
-
|
| 1042 |
-
continue
|
| 1043 |
-
|
| 1044 |
-
processed_answers.append({
|
| 1045 |
-
'task_id': question.get('task_id', ''),
|
| 1046 |
-
'submitted_answer': answer.text
|
| 1047 |
-
})
|
| 1048 |
|
| 1049 |
-
|
| 1050 |
-
|
| 1051 |
-
|
| 1052 |
-
'Question': question_text[:200] + ('...' if len(question_text) > 200 else ''), # Truncate long questions
|
| 1053 |
-
'Answer': answer.text[:200] + ('...' if len(answer.text) > 200 else ''), # Truncate long answers
|
| 1054 |
-
'Confidence': f"{answer.confidence:.2f}",
|
| 1055 |
-
'Processing Time': f"{answer.processing_time:.2f}s"
|
| 1056 |
-
})
|
| 1057 |
|
| 1058 |
-
logger.info(f"Processed question {question.get('task_id', '')} with confidence {answer.confidence}")
|
| 1059 |
except Exception as e:
|
| 1060 |
-
|
| 1061 |
-
|
| 1062 |
-
|
| 1063 |
-
|
| 1064 |
-
|
| 1065 |
-
|
| 1066 |
-
|
| 1067 |
-
'Processing Time': '0.00s'
|
| 1068 |
-
})
|
| 1069 |
-
continue
|
| 1070 |
-
|
| 1071 |
-
if not processed_answers:
|
| 1072 |
-
logger.error("No answers were successfully processed")
|
| 1073 |
-
if results_log:
|
| 1074 |
-
return "No answers were successfully processed - check results table for errors", pd.DataFrame(results_log)
|
| 1075 |
-
return "No answers were successfully processed - no questions were valid", None
|
| 1076 |
-
|
| 1077 |
-
# Submit answers
|
| 1078 |
-
submission_result = await api_submit_answers(processed_answers, profile.username)
|
| 1079 |
-
|
| 1080 |
-
status_message = (
|
| 1081 |
-
f"Successfully processed {len(processed_answers)} questions\n"
|
| 1082 |
-
f"Username: {profile.username}\n"
|
| 1083 |
-
f"Submission Result: {submission_result.get('message', 'No message')}\n"
|
| 1084 |
-
f"Total Questions: {len(questions)}, Successfully Processed: {len(processed_answers)}"
|
| 1085 |
-
)
|
| 1086 |
-
|
| 1087 |
-
return status_message, pd.DataFrame(results_log)
|
| 1088 |
-
|
| 1089 |
-
except Exception as e:
|
| 1090 |
-
error_msg = f"Error in processing: {str(e)}"
|
| 1091 |
-
logger.error(error_msg)
|
| 1092 |
-
# Log the full traceback for debugging
|
| 1093 |
-
import traceback
|
| 1094 |
-
logger.error(f"Full traceback: {traceback.format_exc()}")
|
| 1095 |
-
return error_msg, pd.DataFrame([{
|
| 1096 |
-
'Task ID': 'Error',
|
| 1097 |
-
'Question': 'Error occurred during processing',
|
| 1098 |
-
'Answer': str(e),
|
| 1099 |
-
'Confidence': '0.00',
|
| 1100 |
-
'Processing Time': '0.00s'
|
| 1101 |
-
}])
|
| 1102 |
-
|
| 1103 |
-
# Create Gradio interface
|
| 1104 |
-
with gr.Blocks() as demo:
|
| 1105 |
-
gr.Markdown("# Improved GAIA Agent")
|
| 1106 |
-
gr.Markdown("Login and run the improved agent to process questions.")
|
| 1107 |
-
|
| 1108 |
-
gr.LoginButton()
|
| 1109 |
-
run_button = gr.Button("Process Questions")
|
| 1110 |
-
status_output = gr.Textbox(label="Status", lines=4)
|
| 1111 |
-
results_table = gr.DataFrame(
|
| 1112 |
-
headers=['Task ID', 'Question', 'Answer', 'Confidence', 'Processing Time'],
|
| 1113 |
-
label="Results"
|
| 1114 |
-
)
|
| 1115 |
-
|
| 1116 |
-
run_button.click(
|
| 1117 |
-
fn=run_and_submit_all,
|
| 1118 |
-
outputs=[status_output, results_table]
|
| 1119 |
-
)
|
| 1120 |
-
|
| 1121 |
-
# Mount Gradio app to FastAPI
|
| 1122 |
-
app = gr.mount_gradio_app(app, demo, path="/")
|
| 1123 |
|
| 1124 |
-
|
| 1125 |
-
|
| 1126 |
-
# import uvicorn
|
| 1127 |
-
# uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
+
from llama_index.llms.openai import OpenAI
|
| 2 |
+
from llama_index.core.agent.workflow import AgentWorkflow
|
| 3 |
+
from llama_index.core.tools import FunctionTool
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
import asyncio
|
| 5 |
+
import json
|
| 6 |
+
from typing import Optional, Dict, Any, List, Union
|
| 7 |
+
import os
|
| 8 |
from datetime import datetime
|
| 9 |
+
import yt_dlp
|
| 10 |
+
import whisper
|
| 11 |
+
import tempfile
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
import re
|
| 13 |
import aiohttp
|
| 14 |
+
from dotenv import load_dotenv
|
| 15 |
+
import math
|
| 16 |
+
import operator
|
| 17 |
+
from llama_index.core.workflow import (
|
| 18 |
+
Event,
|
| 19 |
+
Workflow,
|
| 20 |
+
StopEvent
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
)
|
| 22 |
+
from enum import Enum
|
| 23 |
|
| 24 |
+
# Update the input document path
|
| 25 |
+
INPUT_DOC_PATH = "/home/nik/HF FINAL MAIN/response_1747248836022.json"
|
| 26 |
+
OUTPUT_DOC_PATH = "/home/nik/HF FINAL MAIN/agent_answers.jsonl"
|
| 27 |
+
|
| 28 |
+
SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template:
|
| 29 |
+
FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
|
| 30 |
+
If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise.
|
| 31 |
+
If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise.
|
| 32 |
+
If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string."""
|
| 33 |
+
|
| 34 |
+
# Load environment variables
|
| 35 |
+
load_dotenv()
|
| 36 |
+
SERPER_API_KEY = os.getenv('SERPER_API_KEY')
|
| 37 |
+
|
| 38 |
+
def extract_youtube_url(text: str) -> Optional[str]:
|
| 39 |
+
"""Extract YouTube URL from text if present."""
|
| 40 |
+
# Regular expressions for different YouTube URL formats
|
| 41 |
+
youtube_patterns = [
|
| 42 |
+
r'https?://(?:www\.)?youtube\.com/watch\?v=[\w-]+',
|
| 43 |
+
r'https?://(?:www\.)?youtube\.com/v/[\w-]+',
|
| 44 |
+
r'https?://youtu\.be/[\w-]+',
|
| 45 |
+
r'https?://(?:www\.)?youtube\.com/embed/[\w-]+',
|
| 46 |
+
]
|
| 47 |
|
| 48 |
+
for pattern in youtube_patterns:
|
| 49 |
+
match = re.search(pattern, text)
|
| 50 |
+
if match:
|
| 51 |
+
return match.group(0)
|
| 52 |
+
return None
|
| 53 |
|
| 54 |
+
class YouTubeAnalyzer:
|
| 55 |
+
def __init__(self):
|
| 56 |
+
self.model = whisper.load_model("base")
|
| 57 |
+
self.ydl_opts = {
|
| 58 |
+
'format': 'bestaudio/best',
|
| 59 |
+
'postprocessors': [{
|
| 60 |
+
'key': 'FFmpegExtractAudio',
|
| 61 |
+
'preferredcodec': 'mp3',
|
| 62 |
+
'preferredquality': '192',
|
| 63 |
+
}],
|
| 64 |
+
}
|
| 65 |
|
| 66 |
+
def get_video_info(self, url: str) -> Dict[str, Any]:
|
| 67 |
+
"""Get basic information about the video."""
|
| 68 |
+
with yt_dlp.YoutubeDL({'quiet': True}) as ydl:
|
| 69 |
+
try:
|
| 70 |
+
info = ydl.extract_info(url, download=False)
|
| 71 |
+
return {
|
| 72 |
+
'title': info.get('title', ''),
|
| 73 |
+
'description': info.get('description', ''),
|
| 74 |
+
'duration': info.get('duration', 0),
|
| 75 |
+
'view_count': info.get('view_count', 0),
|
| 76 |
+
'upload_date': info.get('upload_date', ''),
|
| 77 |
+
}
|
| 78 |
+
except Exception as e:
|
| 79 |
+
return {'error': f"Error fetching video info: {str(e)}"}
|
|
|
|
| 80 |
|
| 81 |
+
def get_transcript(self, url: str) -> str:
|
| 82 |
+
"""Download video audio and transcribe it."""
|
| 83 |
+
try:
|
| 84 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
| 85 |
+
print(f"Starting video download: {url}")
|
| 86 |
+
self.ydl_opts['outtmpl'] = os.path.join(temp_dir, '%(title)s.%(ext)s')
|
| 87 |
+
|
| 88 |
+
# Download audio
|
| 89 |
+
with yt_dlp.YoutubeDL(self.ydl_opts) as ydl:
|
| 90 |
+
info = ydl.extract_info(url, download=True)
|
| 91 |
+
audio_file = os.path.join(temp_dir, f"{info['title']}.mp3")
|
| 92 |
+
print(f"Audio downloaded successfully: {audio_file}")
|
| 93 |
+
|
| 94 |
+
# Transcribe audio
|
| 95 |
+
print("Starting transcription...")
|
| 96 |
+
result = self.model.transcribe(audio_file)
|
| 97 |
+
print("Transcription completed successfully")
|
| 98 |
+
return result["text"]
|
| 99 |
+
except Exception as e:
|
| 100 |
+
print(f"Detailed error in transcript generation: {str(e)}")
|
| 101 |
+
return f"Error transcribing video: {str(e)}"
|
| 102 |
|
| 103 |
+
async def analyze_youtube_video(url: str) -> Dict[str, Any]:
|
| 104 |
+
"""Analyze a YouTube video and return information and transcript."""
|
| 105 |
+
print(f"Analyzing YouTube video: {url}")
|
| 106 |
+
analyzer = YouTubeAnalyzer()
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
+
# Get video information
|
| 109 |
+
info = analyzer.get_video_info(url)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
+
# Get transcript if video info was successfully retrieved
|
| 112 |
+
if 'error' not in info:
|
| 113 |
+
transcript = analyzer.get_transcript(url)
|
| 114 |
+
info['transcript'] = transcript
|
| 115 |
+
print("Successfully analyzed video and generated transcript")
|
| 116 |
+
else:
|
| 117 |
+
print(f"Error analyzing video: {info.get('error')}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
+
return info
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
|
| 121 |
+
def save_response_to_jsonl(response: Dict[str, str], output_file: str):
|
| 122 |
+
"""Save response to a JSONL file."""
|
| 123 |
+
try:
|
| 124 |
+
json_line = json.dumps(response, ensure_ascii=False)
|
| 125 |
+
with open(output_file, 'a', encoding='utf-8') as f:
|
| 126 |
+
f.write(json_line + '\n')
|
| 127 |
+
print(f"Response saved to {output_file}")
|
| 128 |
+
except Exception as e:
|
| 129 |
+
print(f"Error saving response: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
+
def load_document(file_path: str) -> List[Dict[str, Any]]:
|
| 132 |
+
"""Load and parse the JSON document."""
|
| 133 |
+
try:
|
| 134 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
| 135 |
+
document = json.load(f)
|
| 136 |
+
if isinstance(document, list):
|
| 137 |
+
return document
|
| 138 |
+
return [document] # Convert single document to list
|
| 139 |
+
except Exception as e:
|
| 140 |
+
print(f"Error loading document: {str(e)}")
|
| 141 |
+
return []
|
| 142 |
+
|
| 143 |
+
async def serper_search(query: str) -> str:
|
| 144 |
+
"""
|
| 145 |
+
Perform a web search using Serper API.
|
| 146 |
+
Returns formatted search results as a string.
|
| 147 |
+
"""
|
| 148 |
+
if not SERPER_API_KEY:
|
| 149 |
+
return "Error: Serper API key not found in environment variables"
|
| 150 |
+
|
| 151 |
+
url = "https://google.serper.dev/search"
|
| 152 |
+
headers = {
|
| 153 |
+
'X-API-KEY': SERPER_API_KEY,
|
| 154 |
+
'Content-Type': 'application/json'
|
| 155 |
+
}
|
| 156 |
+
payload = {
|
| 157 |
+
'q': query,
|
| 158 |
+
'num': 5 # Number of results to return
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
try:
|
| 162 |
+
async with aiohttp.ClientSession() as session:
|
| 163 |
+
async with session.post(url, headers=headers, json=payload) as response:
|
| 164 |
+
if response.status == 200:
|
| 165 |
+
data = await response.json()
|
| 166 |
+
|
| 167 |
+
# Format the results
|
| 168 |
+
results = []
|
| 169 |
+
|
| 170 |
+
# Process organic results
|
| 171 |
+
if 'organic' in data:
|
| 172 |
+
for result in data['organic']:
|
| 173 |
+
title = result.get('title', '')
|
| 174 |
+
snippet = result.get('snippet', '')
|
| 175 |
+
results.append(f"Title: {title}\nSnippet: {snippet}\n")
|
| 176 |
+
|
| 177 |
+
# Process knowledge graph if available
|
| 178 |
+
if 'knowledgeGraph' in data:
|
| 179 |
+
kg = data['knowledgeGraph']
|
| 180 |
+
if 'title' in kg:
|
| 181 |
+
results.append(f"Knowledge Graph: {kg['title']}\n{kg.get('description', '')}\n")
|
| 182 |
+
|
| 183 |
+
# Join all results
|
| 184 |
+
return "\n".join(results) if results else "No results found"
|
| 185 |
+
else:
|
| 186 |
+
return f"Error: API returned status code {response.status}"
|
| 187 |
+
except Exception as e:
|
| 188 |
+
return f"Error performing search: {str(e)}"
|
| 189 |
|
| 190 |
+
async def web_search_tool(query: str, max_retries: int = 3, delay: float = 1.0) -> str:
|
| 191 |
+
"""Search the web for information using Serper with retry logic and rate limiting."""
|
| 192 |
+
print(f"Searching web for: {query}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
|
| 194 |
+
for attempt in range(max_retries):
|
|
|
|
| 195 |
try:
|
| 196 |
+
results = await serper_search(query)
|
| 197 |
+
print("Search completed")
|
| 198 |
+
return results
|
|
|
|
|
|
|
| 199 |
except Exception as e:
|
| 200 |
+
print(f"Search attempt {attempt + 1}/{max_retries} failed: {str(e)}")
|
| 201 |
+
if attempt < max_retries - 1:
|
| 202 |
+
await asyncio.sleep(delay * (attempt + 1)) # Exponential backoff
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
else:
|
| 204 |
+
return f"Search failed after {max_retries} attempts"
|
| 205 |
+
|
| 206 |
+
def format_response(task_id: str, answer: str) -> Dict[str, str]:
|
| 207 |
+
"""Format the response in the required JSON-line structure."""
|
| 208 |
+
return {
|
| 209 |
+
"task_id": task_id,
|
| 210 |
+
"model_answer": answer.strip()
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
def truncate_text(text: str, max_tokens: int = 4000) -> str:
|
| 214 |
+
"""Roughly truncate text to stay within token limit."""
|
| 215 |
+
# Approximate tokens (rough estimate: 4 chars = 1 token)
|
| 216 |
+
chars_per_token = 4
|
| 217 |
+
max_chars = max_tokens * chars_per_token
|
| 218 |
+
if len(text) > max_chars:
|
| 219 |
+
return text[:max_chars] + "..."
|
| 220 |
+
return text
|
| 221 |
+
|
| 222 |
+
def get_answer(question: str, llm, search_results: str, video_info: Optional[Dict[str, Any]] = None) -> str:
|
| 223 |
+
"""Get direct answer from the model with token management."""
|
| 224 |
+
# Truncate search results and video information
|
| 225 |
+
truncated_search = truncate_text(search_results, 2000)
|
| 226 |
|
| 227 |
+
context = f"Question: {question}\n\nWeb search results:\n{truncated_search}\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
|
| 229 |
+
if video_info:
|
| 230 |
+
# Truncate video information
|
| 231 |
+
truncated_transcript = truncate_text(video_info.get('transcript', ''), 3000)
|
| 232 |
+
truncated_description = truncate_text(video_info.get('description', ''), 500)
|
| 233 |
+
|
| 234 |
+
context += f"""
|
| 235 |
+
Video Information:
|
| 236 |
+
Title: {video_info.get('title', '')}
|
| 237 |
+
Description: {truncated_description}
|
| 238 |
+
Transcript: {truncated_transcript}
|
| 239 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
|
| 241 |
+
thinking_prompt = f"""
|
| 242 |
+
Based on this information:
|
| 243 |
+
{context}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
|
| 245 |
+
Provide ONLY the answer with no explanation. The answer should be just a number or as few words as possible.
|
| 246 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
|
| 248 |
+
return llm.complete(thinking_prompt).strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
+
class ResponseManager:
|
| 251 |
+
def __init__(self, output_file: str):
|
| 252 |
+
self.output_file = output_file
|
| 253 |
+
self.current_task_id = 0
|
| 254 |
+
|
| 255 |
+
# Create new file or clear existing one
|
| 256 |
+
with open(self.output_file, 'w', encoding='utf-8') as f:
|
| 257 |
+
f.write('')
|
| 258 |
+
|
| 259 |
+
def get_next_task_id(self) -> str:
|
| 260 |
+
"""Generate the next task ID in the format task_id_#"""
|
| 261 |
+
self.current_task_id += 1
|
| 262 |
+
return f"task_id_{self.current_task_id}"
|
| 263 |
|
| 264 |
+
def save_response(self, answer: str):
|
| 265 |
+
"""Save a response with auto-generated task ID"""
|
| 266 |
+
response = {
|
| 267 |
+
"task_id": self.get_next_task_id(),
|
| 268 |
+
"model_answer": answer.strip()
|
| 269 |
+
}
|
| 270 |
|
| 271 |
+
# Write response in JSON Lines format
|
| 272 |
+
with open(self.output_file, 'a', encoding='utf-8') as f:
|
| 273 |
+
f.write(json.dumps(response, ensure_ascii=False) + '\n')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 274 |
|
| 275 |
+
return response
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
|
| 277 |
+
class Calculator:
|
| 278 |
+
def __init__(self):
|
| 279 |
+
self.operations = {
|
| 280 |
+
'+': operator.add,
|
| 281 |
+
'-': operator.sub,
|
| 282 |
+
'*': operator.mul,
|
| 283 |
+
'/': operator.truediv,
|
| 284 |
+
'^': operator.pow,
|
| 285 |
+
'sqrt': math.sqrt,
|
| 286 |
+
'abs': abs
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
def calculate(self, expression: str) -> Union[float, str]:
|
| 290 |
+
"""
|
| 291 |
+
Safely evaluate a mathematical expression.
|
| 292 |
+
Returns result or error message if invalid.
|
| 293 |
+
"""
|
| 294 |
try:
|
| 295 |
+
# Convert expression to Python-safe math expression
|
| 296 |
+
safe_expr = self._prepare_expression(expression)
|
| 297 |
+
result = eval(safe_expr, {"__builtins__": None}, self.operations)
|
| 298 |
+
return float(result)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
except Exception as e:
|
| 300 |
+
return f"Error: {str(e)}"
|
| 301 |
+
|
| 302 |
+
def _prepare_expression(self, expression: str) -> str:
|
| 303 |
+
"""Prepare expression for safe evaluation."""
|
| 304 |
+
# Remove any dangerous characters or functions
|
| 305 |
+
safe_chars = set("0123456789+-*/^(). ")
|
| 306 |
+
cleaned = ''.join(c for c in expression if c in safe_chars)
|
| 307 |
+
return cleaned
|
| 308 |
+
|
| 309 |
+
async def analyze_document(question: str, context: Optional[Dict[str, Any]] = None) -> Dict[str, str]:
|
| 310 |
+
"""Analyze question and produce answer in JSON-line format."""
|
| 311 |
+
try:
|
| 312 |
+
if not context or 'document' not in context:
|
| 313 |
+
return {"error": "No document provided in context"}
|
| 314 |
+
|
| 315 |
+
document = context.get('document', {})
|
| 316 |
+
question = document.get('question', '')
|
| 317 |
|
| 318 |
+
if not question:
|
| 319 |
+
return {"error": "No question found in document"}
|
| 320 |
|
| 321 |
+
calculator = Calculator()
|
| 322 |
+
video_info = None
|
| 323 |
+
search_results = ""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
|
| 325 |
+
# Check for YouTube URL in the question
|
| 326 |
+
youtube_url = extract_youtube_url(question)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 327 |
|
| 328 |
+
# Try YouTube analysis first if URL exists
|
| 329 |
+
if youtube_url:
|
| 330 |
+
print(f"Processing YouTube video: {youtube_url}")
|
| 331 |
+
try:
|
| 332 |
+
video_info = await analyze_youtube_video(youtube_url)
|
| 333 |
+
if 'error' in video_info:
|
| 334 |
+
print(f"YouTube analysis failed, falling back to web search")
|
| 335 |
+
# Modify question to search for video content
|
| 336 |
+
video_search_query = f"transcript summary {youtube_url}"
|
| 337 |
+
video_search_results = await web_search_tool(video_search_query)
|
| 338 |
+
search_results += f"\nVideo-related search results:\n{video_search_results}"
|
| 339 |
+
except Exception as e:
|
| 340 |
+
print(f"Error in YouTube analysis: {str(e)}")
|
| 341 |
+
# Fallback to web search
|
| 342 |
+
video_search_query = f"transcript summary {youtube_url}"
|
| 343 |
+
video_search_results = await web_search_tool(video_search_query)
|
| 344 |
+
search_results += f"\nVideo-related search results:\n{video_search_results}"
|
| 345 |
|
| 346 |
+
# Perform general web search
|
|
|
|
|
|
|
|
|
|
| 347 |
try:
|
| 348 |
+
general_search_results = await web_search_tool(question)
|
| 349 |
+
search_results += f"\nGeneral search results:\n{general_search_results}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
except Exception as e:
|
| 351 |
+
print(f"Web search error: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 352 |
|
| 353 |
+
# Check if question involves calculations
|
| 354 |
+
if any(op in question for op in ['+', '-', '*', '/', '^']):
|
| 355 |
+
# Extract numerical expression from question
|
| 356 |
+
# This is a simple example - you might need more sophisticated parsing
|
| 357 |
+
numbers = re.findall(r'[-+]?\d*\.?\d+', question)
|
| 358 |
+
operators = re.findall(r'[\+\-\*\/\^]', question)
|
| 359 |
+
if numbers and operators:
|
| 360 |
+
expression = ''.join([f"{n}{o}" for n, o in zip(numbers, operators + [''])])
|
| 361 |
+
calc_result = calculator.calculate(expression)
|
| 362 |
+
search_results += f"\nCalculation result: {calc_result}"
|
| 363 |
|
| 364 |
+
# Get answer using all available information
|
| 365 |
+
answer = get_answer(question, llm, search_results, video_info)
|
|
|
|
| 366 |
|
| 367 |
+
return {"answer": answer.strip()}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
|
| 369 |
+
except Exception as e:
|
| 370 |
+
return {"error": f"Error processing question: {str(e)}"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 371 |
|
| 372 |
+
# initialize llm
|
| 373 |
+
llm = OpenAI(
|
| 374 |
+
model="gpt-4o",
|
| 375 |
+
temperature=0,
|
| 376 |
+
system_prompt=SYSTEM_PROMPT
|
| 377 |
+
)
|
| 378 |
|
| 379 |
+
# initialize agent with web search and YouTube analysis capability
|
| 380 |
+
agent = AgentWorkflow.from_tools_or_functions(
|
| 381 |
+
[
|
| 382 |
+
FunctionTool.from_defaults(analyze_document),
|
| 383 |
+
FunctionTool.from_defaults(web_search_tool),
|
| 384 |
+
FunctionTool.from_defaults(analyze_youtube_video),
|
| 385 |
+
FunctionTool.from_defaults(Calculator().calculate)
|
| 386 |
+
],
|
| 387 |
+
llm=llm
|
| 388 |
)
|
| 389 |
|
| 390 |
+
async def main():
|
| 391 |
+
from llama_index.core.workflow import Context
|
| 392 |
+
ctx = Context(agent)
|
| 393 |
+
|
| 394 |
+
# Initialize response manager
|
| 395 |
+
response_manager = ResponseManager(OUTPUT_DOC_PATH)
|
| 396 |
+
|
| 397 |
+
# Load documents into context using the new path
|
| 398 |
+
if os.path.exists(INPUT_DOC_PATH):
|
| 399 |
+
documents = load_document(INPUT_DOC_PATH)
|
| 400 |
+
if documents:
|
| 401 |
+
# Process each question in the document
|
| 402 |
+
for doc in documents:
|
| 403 |
+
# Set current document in context
|
| 404 |
+
await ctx.set('document', doc)
|
| 405 |
+
|
| 406 |
+
try:
|
| 407 |
+
# Get agent response
|
| 408 |
+
agent_output = await agent.run(doc['question'], ctx=ctx)
|
| 409 |
+
|
| 410 |
+
# Format and save response using the document's task_id
|
| 411 |
+
response = {
|
| 412 |
+
"task_id": doc['task_id'],
|
| 413 |
+
"model_answer": str(agent_output).strip()
|
| 414 |
+
}
|
| 415 |
+
|
| 416 |
+
# Save to file and print
|
| 417 |
+
with open(OUTPUT_DOC_PATH, 'a', encoding='utf-8') as f:
|
| 418 |
+
f.write(json.dumps(response, ensure_ascii=False) + '\n')
|
| 419 |
+
print(json.dumps(response))
|
| 420 |
+
|
| 421 |
+
except Exception as e:
|
| 422 |
+
error_response = {
|
| 423 |
+
"task_id": doc.get('task_id', 'unknown'),
|
| 424 |
+
"model_answer": f"Error processing question: {str(e)}"
|
| 425 |
+
}
|
| 426 |
+
with open(OUTPUT_DOC_PATH, 'a', encoding='utf-8') as f:
|
| 427 |
+
f.write(json.dumps(error_response, ensure_ascii=False) + '\n')
|
| 428 |
+
print(json.dumps(error_response))
|
| 429 |
+
else:
|
| 430 |
+
error_response = {
|
| 431 |
+
"task_id": "error",
|
| 432 |
+
"model_answer": "Failed to load document"
|
| 433 |
+
}
|
| 434 |
+
with open(OUTPUT_DOC_PATH, 'a', encoding='utf-8') as f:
|
| 435 |
+
f.write(json.dumps(error_response, ensure_ascii=False) + '\n')
|
| 436 |
+
print(json.dumps(error_response))
|
| 437 |
else:
|
| 438 |
+
error_response = {
|
| 439 |
+
"task_id": "error",
|
| 440 |
+
"model_answer": f"Document not found at {INPUT_DOC_PATH}"
|
| 441 |
+
}
|
| 442 |
+
with open(OUTPUT_DOC_PATH, 'a', encoding='utf-8') as f:
|
| 443 |
+
f.write(json.dumps(error_response, ensure_ascii=False) + '\n')
|
| 444 |
+
print(json.dumps(error_response))
|
| 445 |
+
|
| 446 |
+
if __name__ == "__main__":
|
| 447 |
+
asyncio.run(main())
|
| 448 |
+
|
| 449 |
+
class QuestionType(Enum):
|
| 450 |
+
YOUTUBE = "youtube"
|
| 451 |
+
CALCULATION = "calculation"
|
| 452 |
+
WEB_SEARCH = "web_search"
|
| 453 |
+
MULTIPLE = "multiple"
|
| 454 |
+
|
| 455 |
+
# Define our event classes
|
| 456 |
+
class BaseEvent(Event):
|
| 457 |
+
question: str
|
| 458 |
+
task_id: str
|
| 459 |
+
search_results: Optional[str] = None
|
| 460 |
+
youtube_results: Optional[Dict[str, Any]] = None
|
| 461 |
+
calculation_results: Optional[Dict[str, Any]] = None
|
| 462 |
+
errors: List[str] = []
|
| 463 |
+
|
| 464 |
+
class AgentStopEvent(StopEvent):
|
| 465 |
+
answer: str # Use 'answer' instead of 'result' to avoid shadowing
|
| 466 |
+
|
| 467 |
+
class AgentWorkflow(Workflow):
|
| 468 |
+
def __init__(self, llm, verbose=False, max_search_attempts: int = 3):
|
| 469 |
+
self.llm = llm
|
| 470 |
+
self.calculator = Calculator()
|
| 471 |
+
self.max_search_attempts = max_search_attempts
|
| 472 |
+
super().__init__(verbose=verbose)
|
| 473 |
+
|
| 474 |
+
async def process_question(self, ev: Event) -> AgentStopEvent:
|
| 475 |
+
"""Single step that processes the question and returns a StopEvent"""
|
| 476 |
+
try:
|
| 477 |
+
question = ev.input.get('question', '')
|
| 478 |
+
task_id = ev.input.get('task_id', '')
|
| 479 |
+
|
| 480 |
+
if not question:
|
| 481 |
+
return AgentStopEvent(answer="No question provided")
|
| 482 |
+
|
| 483 |
+
# Initialize results
|
| 484 |
+
search_results = ""
|
| 485 |
+
youtube_results = None
|
| 486 |
+
calculation_results = None
|
| 487 |
+
errors = []
|
| 488 |
+
|
| 489 |
+
# Check for YouTube URL
|
| 490 |
+
youtube_url = extract_youtube_url(question)
|
| 491 |
+
if youtube_url:
|
| 492 |
+
try:
|
| 493 |
+
youtube_results = await analyze_youtube_video(youtube_url)
|
| 494 |
+
if 'error' in youtube_results:
|
| 495 |
+
errors.append(f"YouTube analysis failed: {youtube_results['error']}")
|
| 496 |
+
# Fallback to web search
|
| 497 |
+
video_search = await web_search_tool(f"transcript summary {youtube_url}")
|
| 498 |
+
search_results += f"\nVideo search results:\n{video_search}"
|
| 499 |
+
except Exception as e:
|
| 500 |
+
errors.append(f"YouTube analysis error: {str(e)}")
|
| 501 |
+
|
| 502 |
+
# Perform web search
|
| 503 |
+
try:
|
| 504 |
+
search_result = await web_search_tool(question)
|
| 505 |
+
search_results += f"\nGeneral search results:\n{search_result}"
|
| 506 |
+
except Exception as e:
|
| 507 |
+
errors.append(f"Web search error: {str(e)}")
|
| 508 |
+
|
| 509 |
+
# Check for calculations
|
| 510 |
+
if any(op in question for op in ['+', '-', '*', '/', '^']):
|
| 511 |
+
try:
|
| 512 |
+
numbers = re.findall(r'[-+]?\d*\.?\d+', question)
|
| 513 |
+
operators = re.findall(r'[\+\-\*\/\^]', question)
|
| 514 |
+
if numbers and operators:
|
| 515 |
+
expression = ''.join([f"{n}{o}" for n, o in zip(numbers, operators + [''])])
|
| 516 |
+
calc_result = self.calculator.calculate(expression)
|
| 517 |
+
calculation_results = {expression: calc_result}
|
| 518 |
+
except Exception as e:
|
| 519 |
+
errors.append(f"Calculation error: {str(e)}")
|
| 520 |
+
|
| 521 |
+
# Generate answer
|
| 522 |
+
context = f"Question: {question}\n\n"
|
| 523 |
+
|
| 524 |
+
if search_results:
|
| 525 |
+
context += f"Search Results:\n{truncate_text(search_results, 2000)}\n\n"
|
| 526 |
+
|
| 527 |
+
if youtube_results:
|
| 528 |
+
context += f"""
|
| 529 |
+
Video Information:
|
| 530 |
+
Title: {youtube_results.get('title', '')}
|
| 531 |
+
Description: {truncate_text(youtube_results.get('description', ''), 500)}
|
| 532 |
+
Transcript: {truncate_text(youtube_results.get('transcript', ''), 3000)}
|
| 533 |
+
"""
|
| 534 |
+
|
| 535 |
+
if calculation_results:
|
| 536 |
+
context += "Calculations:\n"
|
| 537 |
+
for expr, result in calculation_results.items():
|
| 538 |
+
context += f"{expr} = {result}\n"
|
| 539 |
+
|
| 540 |
+
if errors:
|
| 541 |
+
context += "\nErrors encountered:\n" + "\n".join(errors)
|
| 542 |
+
|
| 543 |
+
prompt = f"""
|
| 544 |
+
Based on this information:
|
| 545 |
+
{context}
|
| 546 |
+
|
| 547 |
+
Provide ONLY the answer with no explanation. The answer should be just a number or as few words as possible.
|
| 548 |
+
If the information is insufficient or unclear, respond with 'Information not found'.
|
| 549 |
+
"""
|
| 550 |
+
|
| 551 |
+
final_answer = self.llm.complete(prompt).strip()
|
| 552 |
+
|
| 553 |
+
return AgentStopEvent(answer=final_answer)
|
| 554 |
|
| 555 |
+
except Exception as e:
|
| 556 |
+
return AgentStopEvent(answer=f"Error processing question: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 557 |
|
| 558 |
+
# Update the process_questions function
|
| 559 |
+
async def process_questions(input_path: str, output_path: str):
|
| 560 |
+
llm = OpenAI(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 561 |
model="gpt-4",
|
| 562 |
+
temperature=0,
|
| 563 |
+
system_prompt=SYSTEM_PROMPT
|
| 564 |
)
|
|
|
|
| 565 |
|
| 566 |
+
workflow = AgentWorkflow(llm=llm, verbose=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 567 |
|
| 568 |
+
if os.path.exists(input_path):
|
| 569 |
+
documents = load_document(input_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 570 |
|
| 571 |
+
for doc in documents:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 572 |
try:
|
| 573 |
+
result = await workflow.run(
|
| 574 |
+
input={
|
| 575 |
+
'question': doc['question'],
|
| 576 |
+
'task_id': doc['task_id']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 577 |
}
|
| 578 |
)
|
| 579 |
|
| 580 |
+
response = {
|
| 581 |
+
"task_id": doc['task_id'],
|
| 582 |
+
"model_answer": result.answer # Using answer instead of result
|
| 583 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 584 |
|
| 585 |
+
with open(output_path, 'a', encoding='utf-8') as f:
|
| 586 |
+
f.write(json.dumps(response, ensure_ascii=False) + '\n')
|
| 587 |
+
print(json.dumps(response))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 588 |
|
|
|
|
| 589 |
except Exception as e:
|
| 590 |
+
error_response = {
|
| 591 |
+
"task_id": doc.get('task_id', 'unknown'),
|
| 592 |
+
"model_answer": f"Error processing question: {str(e)}"
|
| 593 |
+
}
|
| 594 |
+
with open(output_path, 'a', encoding='utf-8') as f:
|
| 595 |
+
f.write(json.dumps(error_response, ensure_ascii=False) + '\n')
|
| 596 |
+
print(json.dumps(error_response))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 597 |
|
| 598 |
+
if __name__ == "__main__":
|
| 599 |
+
asyncio.run(process_questions(INPUT_DOC_PATH, OUTPUT_DOC_PATH))
|
|
|
|
|
|