Spaces:
No application file
No application file
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
-
from typing import List, Dict, Any, Optional
|
| 2 |
-
from pydantic import BaseModel, Field
|
| 3 |
import logging
|
| 4 |
from pathlib import Path
|
| 5 |
import json
|
|
@@ -10,157 +10,214 @@ from enum import Enum
|
|
| 10 |
import numpy as np
|
| 11 |
from functools import lru_cache
|
| 12 |
import gradio as gr
|
| 13 |
-
from fastapi import FastAPI
|
| 14 |
from fastapi.middleware.cors import CORSMiddleware
|
| 15 |
import os
|
| 16 |
import pandas as pd
|
| 17 |
import openai
|
| 18 |
import requests
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
# Configure logging
|
| 21 |
logging.basicConfig(
|
| 22 |
level=logging.INFO,
|
| 23 |
-
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
)
|
| 25 |
logger = logging.getLogger("gaia_agent")
|
| 26 |
|
| 27 |
-
#
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
#
|
| 34 |
-
|
| 35 |
-
"""Load test questions from a JSONL file"""
|
| 36 |
-
questions = []
|
| 37 |
-
try:
|
| 38 |
-
with open(file_path, 'r', encoding='utf-8') as f:
|
| 39 |
-
for line in f:
|
| 40 |
-
if line.strip():
|
| 41 |
-
questions.append(json.loads(line))
|
| 42 |
-
return questions
|
| 43 |
-
except Exception as e:
|
| 44 |
-
logger.error(f"Error loading test questions: {e}")
|
| 45 |
-
return []
|
| 46 |
|
| 47 |
class ToolType(str, Enum):
|
| 48 |
CALCULATOR = "calculator"
|
| 49 |
LOCAL_SEARCH = "local_search"
|
| 50 |
REASONING = "reasoning"
|
| 51 |
FILE_PROCESSOR = "file_processor"
|
|
|
|
| 52 |
|
| 53 |
class AgentState(BaseModel):
|
| 54 |
-
"""
|
| 55 |
current_step: int = 0
|
| 56 |
max_steps: int = 5
|
| 57 |
intermediate_results: List[Dict[str, Any]] = Field(default_factory=list)
|
| 58 |
tools_used: List[str] = Field(default_factory=list)
|
| 59 |
confidence_score: float = 0.0
|
|
|
|
| 60 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
class ToolResult(BaseModel):
|
| 62 |
-
"""
|
| 63 |
success: bool
|
| 64 |
result: Any
|
| 65 |
error_message: Optional[str] = None
|
| 66 |
metadata: Dict[str, Any] = Field(default_factory=dict)
|
|
|
|
|
|
|
| 67 |
|
| 68 |
class Question(BaseModel):
|
| 69 |
-
"""
|
| 70 |
text: str
|
| 71 |
context: Optional[str] = None
|
| 72 |
attachments: Optional[List[str]] = None
|
| 73 |
metadata: Dict[str, Any] = Field(default_factory=dict)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
class Answer(BaseModel):
|
| 76 |
-
"""
|
| 77 |
text: str
|
| 78 |
confidence: float
|
| 79 |
reasoning_trace: List[str]
|
| 80 |
tools_used: List[str]
|
| 81 |
processing_time: float
|
| 82 |
timestamp: datetime = Field(default_factory=datetime.now)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
class Tool(BaseModel):
|
| 85 |
-
"""
|
| 86 |
name: str = Field(..., description="Name of the tool")
|
| 87 |
description: str = Field(..., description="Description of what the tool does")
|
| 88 |
type: ToolType = Field(..., description="Type of tool")
|
|
|
|
| 89 |
|
| 90 |
class Config:
|
| 91 |
-
arbitrary_types_allowed = True
|
| 92 |
-
extra = "allow"
|
| 93 |
|
| 94 |
async def execute(self, input_data: Any) -> ToolResult:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
raise NotImplementedError
|
| 96 |
|
| 97 |
class Calculator(Tool):
|
| 98 |
-
"""
|
| 99 |
def __init__(self):
|
| 100 |
super().__init__(
|
| 101 |
name="calculator",
|
| 102 |
-
description="Performs safe mathematical calculations",
|
| 103 |
type=ToolType.CALCULATOR
|
| 104 |
)
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
allowed_names = {
|
| 110 |
-
'abs': abs, 'round': round,
|
| 111 |
-
'min': min, 'max': max,
|
| 112 |
-
'sum': sum, 'pow': pow
|
| 113 |
}
|
|
|
|
|
|
|
| 114 |
code = compile(expr, '<string>', 'eval')
|
| 115 |
for name in code.co_names:
|
| 116 |
-
if name not in
|
| 117 |
raise NameError(f"Use of {name} not allowed")
|
| 118 |
-
return eval(expr, {"__builtins__": {}},
|
| 119 |
|
| 120 |
-
async def
|
| 121 |
-
|
| 122 |
-
result = self._safe_eval(input_data)
|
| 123 |
-
return ToolResult(
|
| 124 |
-
success=True,
|
| 125 |
-
result=result,
|
| 126 |
-
metadata={"operation": input_data}
|
| 127 |
-
)
|
| 128 |
-
except Exception as e:
|
| 129 |
-
return ToolResult(
|
| 130 |
-
success=False,
|
| 131 |
-
result=None,
|
| 132 |
-
error_message=str(e)
|
| 133 |
-
)
|
| 134 |
|
| 135 |
class LocalSearch(Tool):
|
| 136 |
-
"""
|
| 137 |
def __init__(self, knowledge_base_path: Path):
|
| 138 |
super().__init__(
|
| 139 |
name="local_search",
|
| 140 |
-
description="
|
| 141 |
-
type=ToolType.LOCAL_SEARCH
|
| 142 |
-
knowledge_base_path=knowledge_base_path
|
| 143 |
)
|
|
|
|
| 144 |
self._load_knowledge_base()
|
| 145 |
-
|
| 146 |
def _load_knowledge_base(self):
|
| 147 |
-
|
| 148 |
-
# For now, just create the directory if it doesn't exist
|
| 149 |
-
if self.knowledge_base_path:
|
| 150 |
os.makedirs(self.knowledge_base_path, exist_ok=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
@lru_cache(maxsize=1000)
|
| 153 |
-
async def
|
| 154 |
-
# Implement vector search
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
class ImprovedAgent:
|
| 163 |
-
"""Enhanced GAIA agent implementation"""
|
| 164 |
def __init__(self, openai_module, tools: List[Tool]):
|
| 165 |
self.openai = openai_module
|
| 166 |
self.tools = {tool.name: tool for tool in tools}
|
|
@@ -176,9 +233,175 @@ REASONING: [Your step-by-step thought process]
|
|
| 176 |
TOOL USAGE: [If any tools were used, explain how and why]
|
| 177 |
CONFIDENCE: [0-1 score with explanation]
|
| 178 |
FINAL ANSWER: [Your conclusive answer]"""
|
| 179 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
async def _process_step(self, question: Question) -> Optional[Answer]:
|
| 181 |
-
"""Process a single step
|
| 182 |
try:
|
| 183 |
# Prepare the context for the model
|
| 184 |
context = self._prepare_context(question)
|
|
@@ -189,15 +412,25 @@ FINAL ANSWER: [Your conclusive answer]"""
|
|
| 189 |
# Parse the response to extract reasoning and tool requests
|
| 190 |
parsed = self._parse_model_response(response)
|
| 191 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
# If tools are requested, execute them
|
| 193 |
if parsed.get('tool_requests'):
|
| 194 |
tool_results = await self._execute_tools(parsed['tool_requests'])
|
| 195 |
# Add tool results to state
|
| 196 |
self.state.tools_used.extend([req['tool'] for req in parsed['tool_requests']])
|
| 197 |
-
self.state.intermediate_results
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
# If we need more processing, return None to continue
|
| 203 |
if not parsed.get('is_final', False):
|
|
@@ -208,155 +441,24 @@ FINAL ANSWER: [Your conclusive answer]"""
|
|
| 208 |
return Answer(
|
| 209 |
text=parsed['final_answer'],
|
| 210 |
confidence=parsed.get('confidence', 0.0),
|
| 211 |
-
reasoning_trace=self.state.intermediate_results,
|
| 212 |
tools_used=self.state.tools_used,
|
| 213 |
-
processing_time=0.0 # Will be updated in process_question
|
|
|
|
| 214 |
)
|
| 215 |
|
| 216 |
return None
|
| 217 |
|
| 218 |
except Exception as e:
|
| 219 |
-
logger.error(f"Error in processing step: {e}")
|
| 220 |
return None
|
| 221 |
-
|
| 222 |
-
def _prepare_context(self, question: Question) -> str:
|
| 223 |
-
"""Prepare the context for the model including question and state"""
|
| 224 |
-
context = [
|
| 225 |
-
self.system_prompt,
|
| 226 |
-
f"\nCurrent question: {question.text}"
|
| 227 |
-
]
|
| 228 |
-
|
| 229 |
-
if question.context:
|
| 230 |
-
context.append(f"Additional context: {question.context}")
|
| 231 |
-
|
| 232 |
-
if self.state.intermediate_results:
|
| 233 |
-
context.append("\nPrevious steps:")
|
| 234 |
-
for result in self.state.intermediate_results:
|
| 235 |
-
context.append(f"Step {result['step']}: {json.dumps(result['tool_results'])}")
|
| 236 |
-
|
| 237 |
-
return "\n".join(context)
|
| 238 |
-
|
| 239 |
-
async def _get_model_response(self, context: str) -> str:
|
| 240 |
-
"""Get the model's response using GPT-4"""
|
| 241 |
-
try:
|
| 242 |
-
response = self.openai.ChatCompletion.create(
|
| 243 |
-
model="gpt-4",
|
| 244 |
-
messages=[
|
| 245 |
-
{"role": "system", "content": self.system_prompt},
|
| 246 |
-
{"role": "user", "content": context}
|
| 247 |
-
],
|
| 248 |
-
temperature=0.1,
|
| 249 |
-
max_tokens=1000
|
| 250 |
-
)
|
| 251 |
-
return response.choices[0].message['content']
|
| 252 |
-
except Exception as e:
|
| 253 |
-
logger.error(f"Error getting model response: {e}")
|
| 254 |
-
return ""
|
| 255 |
-
|
| 256 |
-
def _parse_model_response(self, response: str) -> Dict[str, Any]:
|
| 257 |
-
"""Parse the model's response to extract reasoning and actions"""
|
| 258 |
-
result = {
|
| 259 |
-
'tool_requests': [],
|
| 260 |
-
'is_final': False,
|
| 261 |
-
'final_answer': None,
|
| 262 |
-
'confidence': 0.0
|
| 263 |
-
}
|
| 264 |
-
|
| 265 |
-
# Parse response sections
|
| 266 |
-
sections = response.split('\n')
|
| 267 |
-
current_section = None
|
| 268 |
-
|
| 269 |
-
for line in sections:
|
| 270 |
-
if line.startswith('REASONING:'):
|
| 271 |
-
current_section = 'reasoning'
|
| 272 |
-
continue
|
| 273 |
-
elif line.startswith('TOOL USAGE:'):
|
| 274 |
-
current_section = 'tool_usage'
|
| 275 |
-
continue
|
| 276 |
-
elif line.startswith('CONFIDENCE:'):
|
| 277 |
-
try:
|
| 278 |
-
confidence = float(line.split(':')[1].strip().split()[0])
|
| 279 |
-
result['confidence'] = min(max(confidence, 0.0), 1.0)
|
| 280 |
-
except:
|
| 281 |
-
pass
|
| 282 |
-
continue
|
| 283 |
-
elif line.startswith('FINAL ANSWER:'):
|
| 284 |
-
result['is_final'] = True
|
| 285 |
-
result['final_answer'] = line.split(':')[1].strip()
|
| 286 |
-
continue
|
| 287 |
-
|
| 288 |
-
# Parse tool requests from TOOL USAGE section
|
| 289 |
-
if current_section == 'tool_usage' and line.strip():
|
| 290 |
-
tool_match = line.strip()
|
| 291 |
-
if any(tool.name in tool_match.lower() for tool in self.tools.values()):
|
| 292 |
-
tool_name = next(name for name in self.tools.keys()
|
| 293 |
-
if name in tool_match.lower())
|
| 294 |
-
result['tool_requests'].append({
|
| 295 |
-
'tool': tool_name,
|
| 296 |
-
'input': tool_match.split(tool_name)[1].strip()
|
| 297 |
-
})
|
| 298 |
-
|
| 299 |
-
return result
|
| 300 |
-
|
| 301 |
-
async def _execute_tools(self, tool_requests: List[Dict[str, str]]) -> List[Dict[str, Any]]:
|
| 302 |
-
"""Execute requested tools in parallel"""
|
| 303 |
-
results = []
|
| 304 |
-
|
| 305 |
-
async def execute_tool(request):
|
| 306 |
-
tool = self.tools.get(request['tool'])
|
| 307 |
-
if tool:
|
| 308 |
-
result = await tool.execute(request['input'])
|
| 309 |
-
return {
|
| 310 |
-
'tool': request['tool'],
|
| 311 |
-
'input': request['input'],
|
| 312 |
-
'result': result
|
| 313 |
-
}
|
| 314 |
-
return None
|
| 315 |
-
|
| 316 |
-
# Execute tools in parallel
|
| 317 |
-
tasks = [execute_tool(req) for req in tool_requests]
|
| 318 |
-
tool_results = await asyncio.gather(*tasks)
|
| 319 |
-
|
| 320 |
-
return [r for r in tool_results if r is not None]
|
| 321 |
-
|
| 322 |
-
async def process_question(self, question: str, context: Optional[str] = None) -> Answer:
|
| 323 |
-
"""Main entry point for question processing"""
|
| 324 |
-
start_time = datetime.now()
|
| 325 |
-
|
| 326 |
-
question_obj = Question(
|
| 327 |
-
text=question,
|
| 328 |
-
context=context
|
| 329 |
-
)
|
| 330 |
-
|
| 331 |
-
self.state = AgentState() # Reset state
|
| 332 |
-
|
| 333 |
-
final_answer = None
|
| 334 |
-
while self.state.current_step < self.state.max_steps and not final_answer:
|
| 335 |
-
step_result = await self._process_step(question_obj)
|
| 336 |
-
if step_result:
|
| 337 |
-
final_answer = step_result
|
| 338 |
-
self.state.current_step += 1
|
| 339 |
-
|
| 340 |
-
if not final_answer:
|
| 341 |
-
# Fallback handling
|
| 342 |
-
final_answer = Answer(
|
| 343 |
-
text="Unable to process question",
|
| 344 |
-
confidence=0.0,
|
| 345 |
-
reasoning_trace=["Processing failed"],
|
| 346 |
-
tools_used=[],
|
| 347 |
-
processing_time=0.0
|
| 348 |
-
)
|
| 349 |
-
|
| 350 |
-
processing_time = (datetime.now() - start_time).total_seconds()
|
| 351 |
-
final_answer.processing_time = processing_time
|
| 352 |
-
|
| 353 |
-
return final_answer
|
| 354 |
|
| 355 |
def create_agent(openai_module, knowledge_base_path: Path) -> ImprovedAgent:
|
| 356 |
"""Factory function to create a configured agent"""
|
| 357 |
tools = [
|
| 358 |
Calculator(),
|
| 359 |
-
LocalSearch(knowledge_base_path)
|
|
|
|
| 360 |
]
|
| 361 |
return ImprovedAgent(openai_module, tools)
|
| 362 |
|
|
@@ -397,169 +499,174 @@ except Exception as e:
|
|
| 397 |
print(f"Error initializing OpenAI or agent: {e}")
|
| 398 |
|
| 399 |
# Add API interaction functions
|
| 400 |
-
|
| 401 |
-
|
|
|
|
| 402 |
try:
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 419 |
|
| 420 |
-
|
| 421 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 422 |
try:
|
| 423 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 424 |
submission_data = {
|
| 425 |
"username": username,
|
| 426 |
-
"agent_code":
|
| 427 |
"answers": processed_answers
|
| 428 |
}
|
| 429 |
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 442 |
)
|
| 443 |
-
|
| 444 |
-
print(f"\nResponse status code: {response.status_code}")
|
| 445 |
-
print(f"Response headers: {dict(response.headers)}")
|
| 446 |
-
|
| 447 |
-
try:
|
| 448 |
-
response_text = response.text
|
| 449 |
-
print(f"Raw response: {response_text}")
|
| 450 |
-
response.raise_for_status()
|
| 451 |
-
result = response.json()
|
| 452 |
-
print(f"Parsed response: {json.dumps(result, indent=2)}")
|
| 453 |
-
return result
|
| 454 |
-
except json.JSONDecodeError as je:
|
| 455 |
-
print(f"Failed to parse response as JSON: {je}")
|
| 456 |
-
return {"error": "Invalid JSON response", "raw_response": response_text}
|
| 457 |
-
except requests.exceptions.HTTPError as he:
|
| 458 |
-
print(f"HTTP error occurred: {he}")
|
| 459 |
-
return {"error": f"HTTP {response.status_code}", "raw_response": response_text}
|
| 460 |
-
|
| 461 |
-
except requests.exceptions.RequestException as e:
|
| 462 |
-
error_msg = f"Request error: {str(e)}"
|
| 463 |
-
print(f"\nError submitting answers to API: {error_msg}")
|
| 464 |
-
if hasattr(e, 'response') and e.response is not None:
|
| 465 |
-
print(f"Response status code: {e.response.status_code}")
|
| 466 |
-
print(f"Response text: {e.response.text}")
|
| 467 |
-
return {"error": error_msg}
|
| 468 |
except Exception as e:
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
|
|
|
|
|
|
| 472 |
|
| 473 |
-
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 474 |
-
"""Process
|
| 475 |
if not profile:
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
|
| 481 |
try:
|
| 482 |
-
# Get questions
|
| 483 |
-
questions = api_get_questions()
|
| 484 |
if not questions:
|
| 485 |
-
|
|
|
|
| 486 |
|
| 487 |
-
|
|
|
|
| 488 |
|
| 489 |
# Process questions
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
for q in questions:
|
| 494 |
try:
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
"task_id": task_id,
|
| 504 |
-
"submitted_answer": answer.text # Changed from model_answer to submitted_answer
|
| 505 |
-
}
|
| 506 |
-
answers_payload.append(answer_entry)
|
| 507 |
-
print(f"Formatted answer: {json.dumps(answer_entry, indent=2)}")
|
| 508 |
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
"Question": question_text,
|
| 513 |
-
"Answer": answer.text,
|
| 514 |
-
"Confidence": answer.confidence,
|
| 515 |
-
"Processing Time": f"{answer.processing_time:.2f}s"
|
| 516 |
})
|
| 517 |
|
| 518 |
-
|
| 519 |
-
print(f"Confidence: {answer.confidence}")
|
| 520 |
|
| 521 |
except Exception as e:
|
| 522 |
-
|
| 523 |
-
#
|
| 524 |
-
answers_payload.append({
|
| 525 |
-
"task_id": task_id,
|
| 526 |
-
"submitted_answer": f"Error processing question: {str(e)}"
|
| 527 |
-
})
|
| 528 |
continue
|
| 529 |
|
| 530 |
-
if not
|
| 531 |
-
|
|
|
|
| 532 |
|
| 533 |
# Submit answers
|
| 534 |
-
|
| 535 |
-
submission_result = api_submit_answers(answers_payload, profile.username)
|
| 536 |
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
f"Submission Successful!\n"
|
| 547 |
-
f"User: {submission_result.get('username')}\n"
|
| 548 |
-
f"Score: {submission_result.get('score', 'N/A')}% "
|
| 549 |
-
f"({submission_result.get('correct_count', '?')}/{submission_result.get('total_attempted', '?')} correct)\n"
|
| 550 |
-
f"Message: {submission_result.get('message', 'No message received.')}"
|
| 551 |
-
)
|
| 552 |
-
else:
|
| 553 |
-
status = "Submission failed: No response from API"
|
| 554 |
-
|
| 555 |
-
return status, pd.DataFrame(results_log)
|
| 556 |
|
| 557 |
except Exception as e:
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
|
| 564 |
# Create Gradio interface
|
| 565 |
with gr.Blocks() as demo:
|
|
|
|
| 1 |
+
from typing import List, Dict, Any, Optional, Union
|
| 2 |
+
from pydantic import BaseModel, Field, validator
|
| 3 |
import logging
|
| 4 |
from pathlib import Path
|
| 5 |
import json
|
|
|
|
| 10 |
import numpy as np
|
| 11 |
from functools import lru_cache
|
| 12 |
import gradio as gr
|
| 13 |
+
from fastapi import FastAPI, HTTPException
|
| 14 |
from fastapi.middleware.cors import CORSMiddleware
|
| 15 |
import os
|
| 16 |
import pandas as pd
|
| 17 |
import openai
|
| 18 |
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(
|
| 25 |
level=logging.INFO,
|
| 26 |
+
format='%(asctime)s - %(name)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s',
|
| 27 |
+
handlers=[
|
| 28 |
+
logging.FileHandler("agent.log"),
|
| 29 |
+
logging.StreamHandler()
|
| 30 |
+
]
|
| 31 |
)
|
| 32 |
logger = logging.getLogger("gaia_agent")
|
| 33 |
|
| 34 |
+
# Configuration class for better organization
|
| 35 |
+
class Config(BaseModel):
|
| 36 |
+
api_base_url: str = "https://agents-course-unit4-scoring.hf.space"
|
| 37 |
+
headers: Dict[str, str] = {"Content-Type": "application/json", "accept": "application/json"}
|
| 38 |
+
username: str = "GoodLuckChuck"
|
| 39 |
+
agent_code_identifier: str = "GoodLuckChuck_Agent_v1"
|
| 40 |
+
max_retries: int = 3
|
| 41 |
+
timeout: int = 30
|
| 42 |
+
|
| 43 |
+
class Config:
|
| 44 |
+
frozen = True
|
| 45 |
|
| 46 |
+
# Global config instance
|
| 47 |
+
config = Config()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
class ToolType(str, Enum):
|
| 50 |
CALCULATOR = "calculator"
|
| 51 |
LOCAL_SEARCH = "local_search"
|
| 52 |
REASONING = "reasoning"
|
| 53 |
FILE_PROCESSOR = "file_processor"
|
| 54 |
+
MEMORY = "memory" # New tool type for persistent memory
|
| 55 |
|
| 56 |
class AgentState(BaseModel):
|
| 57 |
+
"""Enhanced agent state tracking"""
|
| 58 |
current_step: int = 0
|
| 59 |
max_steps: int = 5
|
| 60 |
intermediate_results: List[Dict[str, Any]] = Field(default_factory=list)
|
| 61 |
tools_used: List[str] = Field(default_factory=list)
|
| 62 |
confidence_score: float = 0.0
|
| 63 |
+
memory: Dict[str, Any] = Field(default_factory=dict) # Persistent memory across steps
|
| 64 |
|
| 65 |
+
@validator('confidence_score')
|
| 66 |
+
def validate_confidence(cls, v):
|
| 67 |
+
if not 0 <= v <= 1:
|
| 68 |
+
raise ValueError("Confidence score must be between 0 and 1")
|
| 69 |
+
return v
|
| 70 |
+
|
| 71 |
class ToolResult(BaseModel):
|
| 72 |
+
"""Enhanced tool result with more metadata"""
|
| 73 |
success: bool
|
| 74 |
result: Any
|
| 75 |
error_message: Optional[str] = None
|
| 76 |
metadata: Dict[str, Any] = Field(default_factory=dict)
|
| 77 |
+
execution_time: float = 0.0
|
| 78 |
+
timestamp: datetime = Field(default_factory=datetime.now)
|
| 79 |
|
| 80 |
class Question(BaseModel):
|
| 81 |
+
"""Enhanced question structure with validation"""
|
| 82 |
text: str
|
| 83 |
context: Optional[str] = None
|
| 84 |
attachments: Optional[List[str]] = None
|
| 85 |
metadata: Dict[str, Any] = Field(default_factory=dict)
|
| 86 |
+
priority: int = Field(default=1, ge=1, le=5)
|
| 87 |
+
|
| 88 |
+
@validator('text')
|
| 89 |
+
def validate_text(cls, v):
|
| 90 |
+
if not v.strip():
|
| 91 |
+
raise ValueError("Question text cannot be empty")
|
| 92 |
+
return v.strip()
|
| 93 |
|
| 94 |
class Answer(BaseModel):
|
| 95 |
+
"""Enhanced answer structure with validation"""
|
| 96 |
text: str
|
| 97 |
confidence: float
|
| 98 |
reasoning_trace: List[str]
|
| 99 |
tools_used: List[str]
|
| 100 |
processing_time: float
|
| 101 |
timestamp: datetime = Field(default_factory=datetime.now)
|
| 102 |
+
metadata: Dict[str, Any] = Field(default_factory=dict)
|
| 103 |
+
|
| 104 |
+
@validator('confidence')
|
| 105 |
+
def validate_confidence(cls, v):
|
| 106 |
+
if not 0 <= v <= 1:
|
| 107 |
+
raise ValueError("Confidence must be between 0 and 1")
|
| 108 |
+
return v
|
| 109 |
|
| 110 |
class Tool(BaseModel):
|
| 111 |
+
"""Enhanced base tool class with error handling"""
|
| 112 |
name: str = Field(..., description="Name of the tool")
|
| 113 |
description: str = Field(..., description="Description of what the tool does")
|
| 114 |
type: ToolType = Field(..., description="Type of tool")
|
| 115 |
+
version: str = "1.0.0"
|
| 116 |
|
| 117 |
class Config:
|
| 118 |
+
arbitrary_types_allowed = True
|
| 119 |
+
extra = "allow"
|
| 120 |
|
| 121 |
async def execute(self, input_data: Any) -> ToolResult:
|
| 122 |
+
start_time = datetime.now()
|
| 123 |
+
try:
|
| 124 |
+
result = await self._execute_impl(input_data)
|
| 125 |
+
execution_time = (datetime.now() - start_time).total_seconds()
|
| 126 |
+
return ToolResult(
|
| 127 |
+
success=True,
|
| 128 |
+
result=result,
|
| 129 |
+
execution_time=execution_time,
|
| 130 |
+
metadata={"tool_version": self.version}
|
| 131 |
+
)
|
| 132 |
+
except Exception as e:
|
| 133 |
+
logger.error(f"Tool execution error in {self.name}: {str(e)}")
|
| 134 |
+
return ToolResult(
|
| 135 |
+
success=False,
|
| 136 |
+
result=None,
|
| 137 |
+
error_message=str(e),
|
| 138 |
+
execution_time=(datetime.now() - start_time).total_seconds()
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
async def _execute_impl(self, input_data: Any) -> Any:
|
| 142 |
raise NotImplementedError
|
| 143 |
|
| 144 |
class Calculator(Tool):
|
| 145 |
+
"""Enhanced calculator with more operations"""
|
| 146 |
def __init__(self):
|
| 147 |
super().__init__(
|
| 148 |
name="calculator",
|
| 149 |
+
description="Performs safe mathematical calculations with advanced operations",
|
| 150 |
type=ToolType.CALCULATOR
|
| 151 |
)
|
| 152 |
+
self.allowed_funcs = {
|
| 153 |
+
'abs': abs, 'round': round, 'min': min, 'max': max,
|
| 154 |
+
'sum': sum, 'pow': pow, 'len': len,
|
| 155 |
+
'sorted': sorted, 'any': any, 'all': all
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
}
|
| 157 |
+
|
| 158 |
+
def _safe_eval(self, expr: str) -> float:
|
| 159 |
code = compile(expr, '<string>', 'eval')
|
| 160 |
for name in code.co_names:
|
| 161 |
+
if name not in self.allowed_funcs:
|
| 162 |
raise NameError(f"Use of {name} not allowed")
|
| 163 |
+
return eval(expr, {"__builtins__": {}}, self.allowed_funcs)
|
| 164 |
|
| 165 |
+
async def _execute_impl(self, input_data: str) -> Any:
|
| 166 |
+
return self._safe_eval(input_data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
|
| 168 |
class LocalSearch(Tool):
|
| 169 |
+
"""Enhanced local search with vector storage"""
|
| 170 |
def __init__(self, knowledge_base_path: Path):
|
| 171 |
super().__init__(
|
| 172 |
name="local_search",
|
| 173 |
+
description="Vector-based local knowledge base search",
|
| 174 |
+
type=ToolType.LOCAL_SEARCH
|
|
|
|
| 175 |
)
|
| 176 |
+
self.knowledge_base_path = knowledge_base_path
|
| 177 |
self._load_knowledge_base()
|
| 178 |
+
|
| 179 |
def _load_knowledge_base(self):
|
| 180 |
+
if not self.knowledge_base_path.exists():
|
|
|
|
|
|
|
| 181 |
os.makedirs(self.knowledge_base_path, exist_ok=True)
|
| 182 |
+
# Initialize empty vector store
|
| 183 |
+
self._initialize_vector_store()
|
| 184 |
+
|
| 185 |
+
def _initialize_vector_store(self):
|
| 186 |
+
# Implementation for vector store initialization
|
| 187 |
+
pass
|
| 188 |
|
| 189 |
@lru_cache(maxsize=1000)
|
| 190 |
+
async def _execute_impl(self, query: str) -> Any:
|
| 191 |
+
# Implement actual vector search
|
| 192 |
+
return f"Search result for: {query}"
|
| 193 |
+
|
| 194 |
+
class Memory(Tool):
|
| 195 |
+
"""New tool for persistent memory across agent steps"""
|
| 196 |
+
def __init__(self):
|
| 197 |
+
super().__init__(
|
| 198 |
+
name="memory",
|
| 199 |
+
description="Persistent memory storage for the agent",
|
| 200 |
+
type=ToolType.MEMORY
|
| 201 |
)
|
| 202 |
+
self._memory = {}
|
| 203 |
+
|
| 204 |
+
async def _execute_impl(self, input_data: Dict[str, Any]) -> Any:
|
| 205 |
+
operation = input_data.get("operation")
|
| 206 |
+
key = input_data.get("key")
|
| 207 |
+
value = input_data.get("value")
|
| 208 |
+
|
| 209 |
+
if operation == "store":
|
| 210 |
+
self._memory[key] = value
|
| 211 |
+
return {"stored": key}
|
| 212 |
+
elif operation == "retrieve":
|
| 213 |
+
return self._memory.get(key)
|
| 214 |
+
elif operation == "list":
|
| 215 |
+
return list(self._memory.keys())
|
| 216 |
+
else:
|
| 217 |
+
raise ValueError(f"Unknown memory operation: {operation}")
|
| 218 |
|
| 219 |
class ImprovedAgent:
|
| 220 |
+
"""Enhanced GAIA agent implementation with improved error handling and processing"""
|
| 221 |
def __init__(self, openai_module, tools: List[Tool]):
|
| 222 |
self.openai = openai_module
|
| 223 |
self.tools = {tool.name: tool for tool in tools}
|
|
|
|
| 233 |
TOOL USAGE: [If any tools were used, explain how and why]
|
| 234 |
CONFIDENCE: [0-1 score with explanation]
|
| 235 |
FINAL ANSWER: [Your conclusive answer]"""
|
| 236 |
+
|
| 237 |
+
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
|
| 238 |
+
async def _get_model_response(self, context: str) -> str:
|
| 239 |
+
"""Get model response with retry logic for API failures"""
|
| 240 |
+
try:
|
| 241 |
+
response = await asyncio.to_thread(
|
| 242 |
+
self.openai.ChatCompletion.create,
|
| 243 |
+
model="gpt-4",
|
| 244 |
+
messages=[
|
| 245 |
+
{"role": "system", "content": self.system_prompt},
|
| 246 |
+
{"role": "user", "content": context}
|
| 247 |
+
],
|
| 248 |
+
temperature=0.1,
|
| 249 |
+
max_tokens=1000
|
| 250 |
+
)
|
| 251 |
+
return response.choices[0].message.content
|
| 252 |
+
except Exception as e:
|
| 253 |
+
logger.error(f"Error getting model response: {str(e)}")
|
| 254 |
+
raise
|
| 255 |
+
|
| 256 |
+
def _prepare_context(self, question: Question) -> str:
|
| 257 |
+
"""Prepare enhanced context for the model including state and memory"""
|
| 258 |
+
context_parts = [
|
| 259 |
+
self.system_prompt,
|
| 260 |
+
f"\nCurrent question: {question.text}"
|
| 261 |
+
]
|
| 262 |
+
|
| 263 |
+
if question.context:
|
| 264 |
+
context_parts.append(f"Additional context: {question.context}")
|
| 265 |
+
|
| 266 |
+
if question.attachments:
|
| 267 |
+
context_parts.append(f"Available attachments: {', '.join(question.attachments)}")
|
| 268 |
+
|
| 269 |
+
if self.state.memory:
|
| 270 |
+
context_parts.append("\nRelevant memory items:")
|
| 271 |
+
for key, value in self.state.memory.items():
|
| 272 |
+
context_parts.append(f"- {key}: {value}")
|
| 273 |
+
|
| 274 |
+
if self.state.intermediate_results:
|
| 275 |
+
context_parts.append("\nPrevious reasoning steps:")
|
| 276 |
+
for result in self.state.intermediate_results:
|
| 277 |
+
context_parts.append(f"Step {result['step']}: {json.dumps(result['tool_results'])}")
|
| 278 |
+
|
| 279 |
+
return "\n".join(context_parts)
|
| 280 |
+
|
| 281 |
+
def _parse_model_response(self, response: str) -> Dict[str, Any]:
|
| 282 |
+
"""Enhanced response parser with better error handling"""
|
| 283 |
+
try:
|
| 284 |
+
lines = response.split('\n')
|
| 285 |
+
parsed = {
|
| 286 |
+
'reasoning': [],
|
| 287 |
+
'tool_requests': [],
|
| 288 |
+
'confidence': 0.0,
|
| 289 |
+
'final_answer': None,
|
| 290 |
+
'is_final': False
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
current_section = None
|
| 294 |
+
for line in lines:
|
| 295 |
+
line = line.strip()
|
| 296 |
+
if not line:
|
| 297 |
+
continue
|
| 298 |
+
|
| 299 |
+
if line.startswith('REASONING:'):
|
| 300 |
+
current_section = 'reasoning'
|
| 301 |
+
continue
|
| 302 |
+
elif line.startswith('TOOL USAGE:'):
|
| 303 |
+
current_section = 'tool_usage'
|
| 304 |
+
continue
|
| 305 |
+
elif line.startswith('CONFIDENCE:'):
|
| 306 |
+
try:
|
| 307 |
+
confidence = float(line.split(':')[1].strip().split()[0])
|
| 308 |
+
parsed['confidence'] = max(0.0, min(1.0, confidence))
|
| 309 |
+
except (ValueError, IndexError):
|
| 310 |
+
logger.warning("Could not parse confidence score, defaulting to 0.0")
|
| 311 |
+
continue
|
| 312 |
+
elif line.startswith('FINAL ANSWER:'):
|
| 313 |
+
current_section = 'final_answer'
|
| 314 |
+
parsed['is_final'] = True
|
| 315 |
+
parsed['final_answer'] = line.split(':', 1)[1].strip()
|
| 316 |
+
continue
|
| 317 |
+
|
| 318 |
+
if current_section == 'reasoning':
|
| 319 |
+
parsed['reasoning'].append(line)
|
| 320 |
+
elif current_section == 'tool_usage' and 'use' in line.lower():
|
| 321 |
+
tool_match = re.search(r'use (\w+) tool', line.lower())
|
| 322 |
+
if tool_match and tool_match.group(1) in self.tools:
|
| 323 |
+
parsed['tool_requests'].append({
|
| 324 |
+
'tool': tool_match.group(1),
|
| 325 |
+
'input': line
|
| 326 |
+
})
|
| 327 |
+
|
| 328 |
+
return parsed
|
| 329 |
+
except Exception as e:
|
| 330 |
+
logger.error(f"Error parsing model response: {str(e)}")
|
| 331 |
+
return {'is_final': True, 'final_answer': "Error processing response"}
|
| 332 |
+
|
| 333 |
+
async def _execute_tools(self, tool_requests: List[Dict[str, str]]) -> List[Dict[str, Any]]:
|
| 334 |
+
"""Execute tools with concurrent processing"""
|
| 335 |
+
async def execute_tool(request):
|
| 336 |
+
tool_name = request['tool']
|
| 337 |
+
tool = self.tools.get(tool_name)
|
| 338 |
+
if not tool:
|
| 339 |
+
return {
|
| 340 |
+
'tool': tool_name,
|
| 341 |
+
'status': 'error',
|
| 342 |
+
'error': f"Tool {tool_name} not found"
|
| 343 |
+
}
|
| 344 |
+
|
| 345 |
+
try:
|
| 346 |
+
result = await tool.execute(request['input'])
|
| 347 |
+
return {
|
| 348 |
+
'tool': tool_name,
|
| 349 |
+
'status': 'success',
|
| 350 |
+
'result': result
|
| 351 |
+
}
|
| 352 |
+
except Exception as e:
|
| 353 |
+
logger.error(f"Error executing tool {tool_name}: {str(e)}")
|
| 354 |
+
return {
|
| 355 |
+
'tool': tool_name,
|
| 356 |
+
'status': 'error',
|
| 357 |
+
'error': str(e)
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
return await asyncio.gather(
|
| 361 |
+
*(execute_tool(req) for req in tool_requests)
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
async def process_question(self, question: Union[str, Question], context: Optional[str] = None) -> Answer:
|
| 365 |
+
"""Process a question with enhanced error handling and state management"""
|
| 366 |
+
start_time = datetime.now()
|
| 367 |
+
|
| 368 |
+
# Convert string question to Question object if needed
|
| 369 |
+
if isinstance(question, str):
|
| 370 |
+
question = Question(text=question, context=context)
|
| 371 |
+
|
| 372 |
+
try:
|
| 373 |
+
self.state = AgentState() # Reset state for new question
|
| 374 |
+
|
| 375 |
+
while self.state.current_step < self.state.max_steps:
|
| 376 |
+
step_result = await self._process_step(question)
|
| 377 |
+
if step_result:
|
| 378 |
+
processing_time = (datetime.now() - start_time).total_seconds()
|
| 379 |
+
step_result.processing_time = processing_time
|
| 380 |
+
return step_result
|
| 381 |
+
|
| 382 |
+
self.state.current_step += 1
|
| 383 |
+
|
| 384 |
+
# If we reach max steps without an answer
|
| 385 |
+
return Answer(
|
| 386 |
+
text="Maximum steps reached without conclusive answer",
|
| 387 |
+
confidence=0.0,
|
| 388 |
+
reasoning_trace=self.state.intermediate_results,
|
| 389 |
+
tools_used=self.state.tools_used,
|
| 390 |
+
processing_time=(datetime.now() - start_time).total_seconds()
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
except Exception as e:
|
| 394 |
+
logger.error(f"Error processing question: {str(e)}")
|
| 395 |
+
return Answer(
|
| 396 |
+
text=f"Error processing question: {str(e)}",
|
| 397 |
+
confidence=0.0,
|
| 398 |
+
reasoning_trace=[],
|
| 399 |
+
tools_used=[],
|
| 400 |
+
processing_time=(datetime.now() - start_time).total_seconds()
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
async def _process_step(self, question: Question) -> Optional[Answer]:
|
| 404 |
+
"""Process a single step with enhanced error handling"""
|
| 405 |
try:
|
| 406 |
# Prepare the context for the model
|
| 407 |
context = self._prepare_context(question)
|
|
|
|
| 412 |
# Parse the response to extract reasoning and tool requests
|
| 413 |
parsed = self._parse_model_response(response)
|
| 414 |
|
| 415 |
+
# Update state with reasoning
|
| 416 |
+
self.state.intermediate_results.append({
|
| 417 |
+
'step': self.state.current_step,
|
| 418 |
+
'reasoning': parsed.get('reasoning', [])
|
| 419 |
+
})
|
| 420 |
+
|
| 421 |
# If tools are requested, execute them
|
| 422 |
if parsed.get('tool_requests'):
|
| 423 |
tool_results = await self._execute_tools(parsed['tool_requests'])
|
| 424 |
# Add tool results to state
|
| 425 |
self.state.tools_used.extend([req['tool'] for req in parsed['tool_requests']])
|
| 426 |
+
self.state.intermediate_results[-1]['tool_results'] = tool_results
|
| 427 |
+
|
| 428 |
+
# Store results in memory if needed
|
| 429 |
+
if any(result['tool'] == 'memory' for result in tool_results):
|
| 430 |
+
memory_results = [r for r in tool_results if r['tool'] == 'memory']
|
| 431 |
+
for mem_result in memory_results:
|
| 432 |
+
if mem_result['status'] == 'success':
|
| 433 |
+
self.state.memory.update(mem_result['result'])
|
| 434 |
|
| 435 |
# If we need more processing, return None to continue
|
| 436 |
if not parsed.get('is_final', False):
|
|
|
|
| 441 |
return Answer(
|
| 442 |
text=parsed['final_answer'],
|
| 443 |
confidence=parsed.get('confidence', 0.0),
|
| 444 |
+
reasoning_trace=[step['reasoning'] for step in self.state.intermediate_results],
|
| 445 |
tools_used=self.state.tools_used,
|
| 446 |
+
processing_time=0.0, # Will be updated in process_question
|
| 447 |
+
metadata={'memory_used': bool(self.state.memory)}
|
| 448 |
)
|
| 449 |
|
| 450 |
return None
|
| 451 |
|
| 452 |
except Exception as e:
|
| 453 |
+
logger.error(f"Error in processing step: {str(e)}")
|
| 454 |
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 455 |
|
| 456 |
def create_agent(openai_module, knowledge_base_path: Path) -> ImprovedAgent:
|
| 457 |
"""Factory function to create a configured agent"""
|
| 458 |
tools = [
|
| 459 |
Calculator(),
|
| 460 |
+
LocalSearch(knowledge_base_path),
|
| 461 |
+
Memory()
|
| 462 |
]
|
| 463 |
return ImprovedAgent(openai_module, tools)
|
| 464 |
|
|
|
|
| 499 |
print(f"Error initializing OpenAI or agent: {e}")
|
| 500 |
|
| 501 |
# Add API interaction functions
|
| 502 |
+
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
|
| 503 |
+
async def api_get_questions() -> List[Dict[str, Any]]:
|
| 504 |
+
"""Fetch questions from the course API with retry logic."""
|
| 505 |
try:
|
| 506 |
+
logger.info(f"Fetching questions from: {config.api_base_url}/questions")
|
| 507 |
+
async with aiohttp.ClientSession() as session:
|
| 508 |
+
async with session.get(
|
| 509 |
+
f"{config.api_base_url}/questions",
|
| 510 |
+
headers=config.headers,
|
| 511 |
+
timeout=config.timeout
|
| 512 |
+
) as response:
|
| 513 |
+
if response.status != 200:
|
| 514 |
+
error_text = await response.text()
|
| 515 |
+
logger.error(f"API error (status {response.status}): {error_text}")
|
| 516 |
+
raise HTTPException(
|
| 517 |
+
status_code=response.status,
|
| 518 |
+
detail=f"API error: {error_text}"
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
questions = await response.json()
|
| 522 |
+
logger.info(f"Successfully fetched {len(questions)} questions")
|
| 523 |
+
return questions
|
| 524 |
+
|
| 525 |
+
except asyncio.TimeoutError:
|
| 526 |
+
logger.error("Timeout while fetching questions")
|
| 527 |
+
raise HTTPException(
|
| 528 |
+
status_code=504,
|
| 529 |
+
detail="Timeout while fetching questions"
|
| 530 |
+
)
|
| 531 |
+
except Exception as e:
|
| 532 |
+
logger.error(f"Error fetching questions: {str(e)}")
|
| 533 |
+
raise HTTPException(
|
| 534 |
+
status_code=500,
|
| 535 |
+
detail=f"Error fetching questions: {str(e)}"
|
| 536 |
+
)
|
| 537 |
|
| 538 |
+
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
|
| 539 |
+
async def api_submit_answers(
|
| 540 |
+
processed_answers: List[Dict[str, Any]],
|
| 541 |
+
username: str = config.username
|
| 542 |
+
) -> Dict[str, Any]:
|
| 543 |
+
"""Submit answers to the course API with retry logic."""
|
| 544 |
try:
|
| 545 |
+
# Validate answers format
|
| 546 |
+
for answer in processed_answers:
|
| 547 |
+
if 'task_id' not in answer or 'submitted_answer' not in answer:
|
| 548 |
+
raise ValueError(
|
| 549 |
+
"Invalid answer format. Each answer must contain 'task_id' and 'submitted_answer'"
|
| 550 |
+
)
|
| 551 |
+
|
| 552 |
submission_data = {
|
| 553 |
"username": username,
|
| 554 |
+
"agent_code": config.agent_code_identifier,
|
| 555 |
"answers": processed_answers
|
| 556 |
}
|
| 557 |
|
| 558 |
+
logger.info("=== Submission Details ===")
|
| 559 |
+
logger.info(f"Username: {username}")
|
| 560 |
+
logger.info(f"Agent Code: {config.agent_code_identifier}")
|
| 561 |
+
logger.info(f"Number of Answers: {len(processed_answers)}")
|
| 562 |
+
logger.debug(f"Sample answer format: {json.dumps(processed_answers[0], indent=2) if processed_answers else 'No answers'}")
|
| 563 |
+
logger.debug(f"Full submission data: {json.dumps(submission_data, indent=2)}")
|
| 564 |
|
| 565 |
+
async with aiohttp.ClientSession() as session:
|
| 566 |
+
async with session.post(
|
| 567 |
+
f"{config.api_base_url}/submit",
|
| 568 |
+
headers=config.headers,
|
| 569 |
+
json=submission_data,
|
| 570 |
+
timeout=config.timeout
|
| 571 |
+
) as response:
|
| 572 |
+
if response.status != 200:
|
| 573 |
+
error_text = await response.text()
|
| 574 |
+
logger.error(f"Submission error (status {response.status}): {error_text}")
|
| 575 |
+
raise HTTPException(
|
| 576 |
+
status_code=response.status,
|
| 577 |
+
detail=f"Submission error: {error_text}"
|
| 578 |
+
)
|
| 579 |
+
|
| 580 |
+
result = await response.json()
|
| 581 |
+
logger.info("Submission successful")
|
| 582 |
+
logger.debug(f"Submission response: {json.dumps(result, indent=2)}")
|
| 583 |
+
return result
|
| 584 |
+
|
| 585 |
+
except asyncio.TimeoutError:
|
| 586 |
+
logger.error("Timeout while submitting answers")
|
| 587 |
+
raise HTTPException(
|
| 588 |
+
status_code=504,
|
| 589 |
+
detail="Timeout while submitting answers"
|
| 590 |
+
)
|
| 591 |
+
except ValueError as e:
|
| 592 |
+
logger.error(f"Validation error: {str(e)}")
|
| 593 |
+
raise HTTPException(
|
| 594 |
+
status_code=400,
|
| 595 |
+
detail=str(e)
|
| 596 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 597 |
except Exception as e:
|
| 598 |
+
logger.error(f"Error submitting answers: {str(e)}")
|
| 599 |
+
raise HTTPException(
|
| 600 |
+
status_code=500,
|
| 601 |
+
detail=f"Error submitting answers: {str(e)}"
|
| 602 |
+
)
|
| 603 |
|
| 604 |
+
async def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 605 |
+
"""Process and submit all questions with enhanced error handling."""
|
| 606 |
if not profile:
|
| 607 |
+
raise HTTPException(
|
| 608 |
+
status_code=401,
|
| 609 |
+
detail="Authentication required"
|
| 610 |
+
)
|
| 611 |
|
| 612 |
try:
|
| 613 |
+
# Get questions
|
| 614 |
+
questions = await api_get_questions()
|
| 615 |
if not questions:
|
| 616 |
+
logger.warning("No questions received from API")
|
| 617 |
+
return {"status": "warning", "message": "No questions available"}
|
| 618 |
|
| 619 |
+
# Create agent
|
| 620 |
+
agent = create_agent(openai, Path("knowledge_base"))
|
| 621 |
|
| 622 |
# Process questions
|
| 623 |
+
processed_answers = []
|
| 624 |
+
for question in questions:
|
|
|
|
|
|
|
| 625 |
try:
|
| 626 |
+
answer = await agent.process_question(
|
| 627 |
+
Question(
|
| 628 |
+
text=question['text'],
|
| 629 |
+
context=question.get('context'),
|
| 630 |
+
attachments=question.get('attachments', []),
|
| 631 |
+
metadata=question.get('metadata', {})
|
| 632 |
+
)
|
| 633 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 634 |
|
| 635 |
+
processed_answers.append({
|
| 636 |
+
'task_id': question['task_id'],
|
| 637 |
+
'submitted_answer': answer.text
|
|
|
|
|
|
|
|
|
|
|
|
|
| 638 |
})
|
| 639 |
|
| 640 |
+
logger.info(f"Processed question {question['task_id']} with confidence {answer.confidence}")
|
|
|
|
| 641 |
|
| 642 |
except Exception as e:
|
| 643 |
+
logger.error(f"Error processing question {question.get('task_id', 'unknown')}: {str(e)}")
|
| 644 |
+
# Continue with other questions
|
|
|
|
|
|
|
|
|
|
|
|
|
| 645 |
continue
|
| 646 |
|
| 647 |
+
if not processed_answers:
|
| 648 |
+
logger.error("No answers were successfully processed")
|
| 649 |
+
return {"status": "error", "message": "No answers were successfully processed"}
|
| 650 |
|
| 651 |
# Submit answers
|
| 652 |
+
submission_result = await api_submit_answers(processed_answers, profile.username)
|
|
|
|
| 653 |
|
| 654 |
+
return {
|
| 655 |
+
"status": "success",
|
| 656 |
+
"message": "Successfully processed and submitted answers",
|
| 657 |
+
"details": {
|
| 658 |
+
"total_questions": len(questions),
|
| 659 |
+
"processed_answers": len(processed_answers),
|
| 660 |
+
"submission_result": submission_result
|
| 661 |
+
}
|
| 662 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 663 |
|
| 664 |
except Exception as e:
|
| 665 |
+
logger.error(f"Error in run_and_submit_all: {str(e)}")
|
| 666 |
+
raise HTTPException(
|
| 667 |
+
status_code=500,
|
| 668 |
+
detail=f"Error processing questions: {str(e)}"
|
| 669 |
+
)
|
| 670 |
|
| 671 |
# Create Gradio interface
|
| 672 |
with gr.Blocks() as demo:
|