GoodLuckChuck commited on
Commit
c08b13c
·
verified ·
1 Parent(s): 77fd299

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +284 -503
app.py CHANGED
@@ -1,538 +1,319 @@
1
- import os
2
- import json
3
- import requests
4
  from typing import List, Dict, Any, Optional
5
  from pydantic import BaseModel, Field
6
- import openai
7
- from dotenv import load_dotenv
8
- from fastapi import FastAPI, HTTPException
9
- from fastapi.middleware.cors import CORSMiddleware
10
- import uvicorn
11
  from datetime import datetime
12
- import gradio as gr
13
- import inspect
14
- import pandas as pd
15
-
16
- # --- API Configuration ---
17
- API_BASE_URL = "https://agents-course-unit4-scoring.hf.space"
18
- HEADERS = {"Content-Type": "application/json", "accept": "application/json"}
19
-
20
- # --- Constants ---
21
- USERNAME = "GoodLuckChuck"
22
- AGENT_CODE_IDENTIFIER = "GoodLuckChuck_Agent_v1"
23
-
24
- # --- API Interaction Functions ---
25
- def api_get_questions() -> List[Dict[str, Any]]:
26
- """Fetch questions from the course API."""
27
- try:
28
- print(f"Attempting to fetch questions from: {API_BASE_URL}/questions")
29
- response = requests.get(f"{API_BASE_URL}/questions", headers=HEADERS)
30
- print(f"API Response Status Code: {response.status_code}")
31
-
32
- response.raise_for_status()
33
- questions = response.json()
34
- if not questions:
35
- print("Warning: API returned empty questions list")
36
- return questions
37
- except requests.exceptions.RequestException as e:
38
- print(f"Error fetching questions from API: {e}")
39
- return []
40
- except json.JSONDecodeError as e:
41
- print(f"Error decoding API response: {e}")
42
- print(f"Response content: {response.text[:500]}...")
43
- return []
44
-
45
- def api_download_file(task_id: str, file_name: str, download_dir: str = "downloaded_gaia_files") -> Optional[str]:
46
- """Download a file associated with a task from the course API."""
47
- try:
48
- os.makedirs(download_dir, exist_ok=True)
49
- download_url = f"{API_BASE_URL}/file/{task_id}"
50
-
51
- response = requests.get(download_url, headers=HEADERS)
52
- response.raise_for_status()
53
-
54
- local_file_path = os.path.join(download_dir, file_name)
55
- with open(local_file_path, 'wb') as f:
56
- f.write(response.content)
57
-
58
- print(f"Successfully downloaded file to: {local_file_path}")
59
- return local_file_path
 
 
 
 
 
60
 
61
- except requests.exceptions.RequestException as e:
62
- print(f"Error downloading file for task {task_id}: {e}")
63
- return None
64
- except IOError as e:
65
- print(f"Error saving file for task {task_id}: {e}")
66
- return None
67
 
68
- def api_submit_answers(processed_answers: List[Dict[str, Any]]) -> Dict[str, Any]:
69
- """Submit processed answers to the course API."""
70
- try:
71
- # Format answers for submission
72
- submission_data = {
73
- "username": USERNAME,
74
- "agent_code": AGENT_CODE_IDENTIFIER,
75
- "answers": processed_answers
76
- }
77
-
78
- print("\n=== Submission Details ===")
79
- print(f"Username: {USERNAME}")
80
- print(f"Agent Code: {AGENT_CODE_IDENTIFIER}")
81
- print(f"Number of Answers: {len(processed_answers)}")
82
- print(f"Full Submission Data:\n{json.dumps(submission_data, indent=2)}")
83
-
84
- response = requests.post(
85
- f"{API_BASE_URL}/submit",
86
- headers=HEADERS,
87
- json=submission_data
88
  )
89
- response.raise_for_status()
90
-
91
- result = response.json()
92
- print(f"\nSubmission Response:\n{json.dumps(result, indent=2)}")
93
- return result
94
 
95
- except requests.exceptions.RequestException as e:
96
- print(f"\nError submitting answers to API: {str(e)}")
97
- if hasattr(e.response, 'text'):
98
- print(f"API Error Response: {e.response.text}")
99
- return {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
- # --- OpenAI Client Configuration ---
102
- try:
103
- OPENAI_API_KEY_VALUE = os.environ.get("OPENAI_API_KEY", "").strip()
104
- if not OPENAI_API_KEY_VALUE:
105
- raise ValueError("OPENAI_API_KEY not found in environment variables")
 
 
 
 
 
106
 
107
- # Configure OpenAI client
108
- openai.api_key = OPENAI_API_KEY_VALUE
 
109
 
110
- # Test the API key with a simple completion to verify it works
111
- test_response = openai.ChatCompletion.create(
112
- model="gpt-3.5-turbo",
113
- messages=[{"role": "user", "content": "test"}],
114
- max_tokens=5
115
- )
116
- print("OpenAI client initialized and tested successfully.")
117
- except Exception as e:
118
- print(f"Error initializing OpenAI client: {str(e)}")
119
- print("Please ensure OPENAI_API_KEY is properly set in environment variables")
120
- openai.api_key = None
121
-
122
- # --- Constants ---
123
- LLM_MODEL = "gpt-3.5-turbo"
124
-
125
- # --- GAIA System Prompt ---
126
- GAIA_FINAL_ANSWER_SYSTEM_PROMPT = """You are a precise AI assistant focused on providing accurate, concise answers. Follow these rules strictly:
127
-
128
- 1. For numerical answers:
129
- - Use plain numbers without commas or units (unless specifically requested)
130
- - Example: "FINAL ANSWER: 42" (not "FINAL ANSWER: 42%" or "FINAL ANSWER: 42.00")
131
-
132
- 2. For text answers:
133
- - Provide the shortest possible answer without articles or abbreviations
134
- - Use full names for cities, countries, and proper nouns
135
- - Example: "FINAL ANSWER: Paris" (not "FINAL ANSWER: The city of Paris")
136
-
137
- 3. For list answers:
138
- - Use comma-separated values without spaces after commas
139
- - Follow number and text rules for each element
140
- - Example: "FINAL ANSWER: 1,Paris,42,London"
141
-
142
- Always end your response with:
143
- FINAL ANSWER: [your answer following the above rules]"""
144
-
145
- # --- Pydantic Models ---
146
- class WebSearchInput(BaseModel):
147
- query: str = Field(..., description="The search query to find information on the web.")
148
-
149
- class CalculatorInput(BaseModel):
150
- expression: str = Field(..., description="The mathematical expression to evaluate.")
151
-
152
- class ImageAnalysisInput(BaseModel):
153
- image_url: Optional[str] = Field(None, description="The URL of the image to analyze.")
154
- file_name: Optional[str] = Field(None, description="The file name of the image.")
155
- prompt: str = Field(..., description="Specific question or instruction for analyzing the image.")
156
-
157
- # --- Tool Functions ---
158
- def execute_web_search(query: str) -> Dict[str, Any]:
159
- """Mock web search tool."""
160
- print(f" 🔎 [Tool Called] WebSearch with query: '{query}'")
161
- if "capital of france" in query.lower():
162
- return {"result": "Paris is the capital of France.", "source": "mock_wikipedia.org"}
163
- elif "tallest building" in query.lower():
164
- return {"result": "The Burj Khalifa is currently the tallest building in the world.", "source": "mock_guinnessworldrecords.com"}
165
- return {"result": f"No specific information found for '{query}'.", "source": "mock_search_engine.com"}
166
-
167
- def execute_calculator(expression: str) -> Dict[str, Any]:
168
- """Mock calculator tool."""
169
- print(f" 🧮 [Tool Called] Calculator with expression: '{expression}'")
170
- try:
171
- result = eval(expression, {"__builtins__": {}}, {})
172
- return {"result": str(result)}
173
- except Exception as e:
174
- return {"error": f"Invalid expression or calculation error: {str(e)}"}
175
-
176
- def execute_image_analysis(image_url: Optional[str], file_name: Optional[str], prompt: str) -> Dict[str, Any]:
177
- """Mock image analysis tool."""
178
- identifier = image_url or file_name
179
- print(f" 🖼️ [Tool Called] ImageAnalysis for '{identifier}' with prompt: '{prompt}'")
180
- if identifier and "cat" in prompt.lower():
181
- return {"description": "The image appears to show a cat sitting on a mat.", "objects_detected": ["cat", "mat"]}
182
- elif identifier and "fruit" in prompt.lower():
183
- return {"description": "The image contains various fruits, possibly apples and bananas.", "objects_detected": ["apple", "banana"]}
184
- return {"description": f"Could not analyze image '{identifier}' for prompt '{prompt}'. Details unavailable.", "objects_detected": []}
185
-
186
- # --- AI Agent Class ---
187
- class AIAgent:
188
- def __init__(self):
189
- """Initialize the AI Agent with OpenAI client."""
190
- self.reasoning_trace = []
191
- # Get API key from environment
192
- api_key = os.environ.get("OPENAI_API_KEY", "").strip()
193
- if not api_key:
194
- raise ValueError("OPENAI_API_KEY not found in environment variables")
195
- openai.api_key = api_key
196
- print("AIAgent initialized with OpenAI client.")
197
-
198
- def _log_step(self, message: str, data: Optional[Dict] = None):
199
- """Log a step in the reasoning process."""
200
- print(message)
201
- entry = {"message": message}
202
- if data:
203
- entry.update(data)
204
- self.reasoning_trace.append(entry)
205
 
206
- def __call__(self, question: str) -> str:
207
- """Process a single question and return an answer."""
208
- self.reasoning_trace = []
 
 
 
 
209
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  try:
211
- self._log_step(f"Processing question: {question[:100]}...")
 
212
 
213
- messages = [
214
- {
215
- "role": "system",
216
- "content": GAIA_FINAL_ANSWER_SYSTEM_PROMPT
217
- },
218
- {
219
- "role": "user",
220
- "content": question
221
- }
222
- ]
223
-
224
- response = openai.ChatCompletion.create(
225
- model=LLM_MODEL,
226
- messages=messages,
227
- temperature=0.1,
228
- max_tokens=1000
229
- )
230
 
231
- assistant_message = response.choices[0].message.content
232
- self._log_step(f"Assistant response: {assistant_message}")
 
 
 
 
 
 
 
 
 
 
 
233
 
234
- # Extract final answer
235
- if "FINAL ANSWER:" in assistant_message:
236
- final_answer = assistant_message.split("FINAL ANSWER:")[-1].strip()
237
- self._log_step(f"Extracted final answer: {final_answer}")
238
- return final_answer
 
 
 
 
239
 
240
- # If no final answer format found, return the full response
241
- return assistant_message.strip()
242
 
243
  except Exception as e:
244
- error_msg = f"Error processing question: {str(e)}"
245
- self._log_step(error_msg)
246
- return f"ERROR: {error_msg}"
247
-
248
- # --- FastAPI App ---
249
- app = FastAPI(title="AI Agent API")
250
-
251
- app.add_middleware(
252
- CORSMiddleware,
253
- allow_origins=["*"],
254
- allow_credentials=True,
255
- allow_methods=["*"],
256
- allow_headers=["*"],
257
- )
258
-
259
- # Initialize the AI Agent globally
260
- if OPENAI_API_KEY_VALUE and openai.api_key:
261
- global_agent = AIAgent()
262
- else:
263
- global_agent = None
264
-
265
- @app.get("/")
266
- async def root():
267
- """Root endpoint to verify the API is running."""
268
- return {
269
- "status": "online",
270
- "timestamp": datetime.now().isoformat(),
271
- "agent_status": "initialized" if openai.api_key else "not initialized",
272
- "openai_key_set": bool(openai.api_key),
273
- "api_base_url": API_BASE_URL
274
- }
275
-
276
- @app.get("/debug")
277
- async def debug():
278
- """Debug endpoint to check configuration."""
279
- return {
280
- "openai_initialized": bool(openai.api_key),
281
- "api_base_url": API_BASE_URL,
282
- "username": USERNAME,
283
- "agent_code": AGENT_CODE_IDENTIFIER,
284
- "timestamp": datetime.now().isoformat()
285
- }
286
-
287
- @app.get("/test-questions")
288
- async def test_questions():
289
- """Test endpoint to fetch questions without processing."""
290
- try:
291
- questions = api_get_questions()
292
- return {
293
- "status": "success",
294
- "question_count": len(questions) if questions else 0,
295
- "questions": questions
296
- }
297
- except Exception as e:
298
- return {
299
- "status": "error",
300
- "error": str(e)
301
- }
302
-
303
- @app.post("/process")
304
- async def process_questions():
305
- """Process all questions and submit answers."""
306
- print("\n=== Starting question processing ===")
307
- try:
308
- # Validate OpenAI API key
309
- if not openai.api_key:
310
- raise HTTPException(
311
- status_code=500,
312
- detail="OpenAI API key not configured. Please set OPENAI_API_KEY environment variable."
313
- )
314
 
315
- print("OpenAI API key validated")
 
316
 
317
- # Initialize agent
318
- agent = AIAgent()
319
- print("AI Agent initialized")
 
320
 
321
- # Fetch questions
322
- print("Fetching questions from API...")
323
- questions = api_get_questions()
324
- if not questions:
325
- raise HTTPException(status_code=500, detail="Failed to fetch questions from API")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326
 
327
- print(f"Successfully fetched {len(questions)} questions")
328
- processed_answers = []
 
329
 
330
- for idx, question in enumerate(questions, 1):
331
- task_id = question.get("task_id")
332
- question_text = question.get("question")
333
- file_name = question.get("file_name")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
334
 
335
- print(f"\nProcessing question {idx}/{len(questions)}")
336
- print(f"Task ID: {task_id}")
337
- print(f"Question: {question_text}")
338
- if file_name:
339
- print(f"File: {file_name}")
340
-
341
- try:
342
- answer = agent(question_text)
343
- processed_answers.append(answer)
344
- print(f"Answer generated: {answer[:100]}...")
345
- except Exception as e:
346
- error_msg = f"Error processing question {task_id}: {str(e)}"
347
- print(error_msg)
348
- processed_answers.append({
349
- "task_id": task_id,
350
- "model_answer": f"ERROR: Failed to process question - {str(e)}",
351
- "reasoning_trace": json.dumps([{"error": str(e)}])
352
- })
353
-
354
- if not processed_answers:
355
- raise HTTPException(
356
- status_code=500,
357
- detail="No answers were generated for any questions"
358
- )
359
 
360
- # Submit answers
361
- print("\nSubmitting answers to API...")
362
- submission_result = api_submit_answers(processed_answers)
363
- if not submission_result:
364
- raise HTTPException(
365
- status_code=500,
366
- detail="Failed to submit answers to API"
367
- )
368
 
369
- print("Submission successful!")
370
- return {
371
- "status": "success",
372
- "message": f"Processed {len(processed_answers)} questions",
373
- "submission_result": submission_result,
374
- "processed_answers": processed_answers
375
- }
 
 
 
376
 
377
- except HTTPException as he:
378
- print(f"HTTP Exception: {he.detail}")
379
- raise he
380
- except Exception as e:
381
- error_msg = f"Error in process_questions: {str(e)}"
382
- print(error_msg)
383
- raise HTTPException(status_code=500, detail=error_msg)
384
-
385
- def run_and_submit_all(profile: gr.OAuthProfile | None):
386
- """
387
- Fetches all questions, runs the AIAgent on them, submits all answers,
388
- and displays the results.
389
- """
390
- # --- Determine HF Space Runtime URL and Repo URL ---
391
- space_id = os.getenv("SPACE_ID")
392
-
393
- if profile:
394
- username = f"{profile.username}"
395
- print(f"User logged in: {username}")
396
- else:
397
- print("User not logged in.")
398
- return "Please Login to Hugging Face with the button.", None
399
-
400
- api_url = API_BASE_URL
401
- questions_url = f"{api_url}/questions"
402
- submit_url = f"{api_url}/submit"
403
-
404
- # 1. Instantiate Agent
405
- try:
406
- agent = AIAgent()
407
- except Exception as e:
408
- print(f"Error instantiating agent: {e}")
409
- return f"Error initializing agent: {e}", None
410
-
411
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
412
- print(f"Agent code URL: {agent_code}")
413
-
414
- # 2. Fetch Questions
415
- print(f"Fetching questions from: {questions_url}")
416
- try:
417
- response = requests.get(questions_url, timeout=15)
418
- response.raise_for_status()
419
- questions_data = response.json()
420
- if not questions_data:
421
- print("Fetched questions list is empty.")
422
- return "Fetched questions list is empty or invalid format.", None
423
- print(f"Fetched {len(questions_data)} questions.")
424
- except Exception as e:
425
- print(f"Error fetching questions: {e}")
426
- return f"Error fetching questions: {e}", None
427
-
428
- # 3. Run Agent
429
- results_log = []
430
- answers_payload = []
431
- print(f"Running agent on {len(questions_data)} questions...")
432
-
433
- for item in questions_data:
434
- task_id = item.get("task_id")
435
- question_text = item.get("question")
436
- if not task_id or question_text is None:
437
- print(f"Skipping item with missing task_id or question: {item}")
438
- continue
439
 
440
- try:
441
- submitted_answer = agent(question_text)
442
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
443
- results_log.append({
444
- "Task ID": task_id,
445
- "Question": question_text,
446
- "Submitted Answer": submitted_answer
447
- })
448
- print(f"Processed task {task_id}: {submitted_answer[:100]}...")
449
- except Exception as e:
450
- print(f"Error running agent on task {task_id}: {e}")
451
- results_log.append({
452
- "Task ID": task_id,
453
- "Question": question_text,
454
- "Submitted Answer": f"AGENT ERROR: {e}"
455
- })
456
-
457
- if not answers_payload:
458
- print("Agent did not produce any answers to submit.")
459
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
460
 
461
- # 4. Submit Answers
462
- submission_data = {
463
- "username": username.strip(),
464
- "agent_code": agent_code,
465
- "answers": answers_payload
466
- }
467
-
468
- print(f"Submitting {len(answers_payload)} answers for user '{username}'...")
469
-
470
- try:
471
- response = requests.post(submit_url, json=submission_data, timeout=60)
472
- response.raise_for_status()
473
- result_data = response.json()
474
 
475
- final_status = (
476
- f"Submission Successful!\n"
477
- f"User: {result_data.get('username')}\n"
478
- f"Overall Score: {result_data.get('score', 'N/A')}% "
479
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
480
- f"Message: {result_data.get('message', 'No message received.')}"
481
  )
482
 
483
- print("Submission successful.")
484
- results_df = pd.DataFrame(results_log)
485
- return final_status, results_df
486
 
487
- except Exception as e:
488
- error_msg = f"Submission failed: {str(e)}"
489
- print(error_msg)
490
- results_df = pd.DataFrame(results_log)
491
- return error_msg, results_df
492
-
493
- # --- Build Gradio Interface using Blocks ---
494
- with gr.Blocks() as demo:
495
- gr.Markdown("# AI Agent Evaluation Runner")
496
- gr.Markdown(
497
- """
498
- **Instructions:**
499
- 1. Log in to your Hugging Face account using the button below.
500
- 2. Click 'Run Evaluation & Submit All Answers' to process all questions and see results.
501
- 3. The agent will use GPT-3.5-turbo to generate answers following strict formatting rules.
502
 
503
- **Note:** Processing may take some time as each question requires an API call.
504
- """
505
- )
506
-
507
- gr.LoginButton()
508
- run_button = gr.Button("Run Evaluation & Submit All Answers")
509
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
510
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
511
-
512
- run_button.click(
513
- fn=run_and_submit_all,
514
- outputs=[status_output, results_table]
515
- )
516
-
517
- if __name__ == "__main__":
518
- print("\n" + "-"*30 + " App Starting " + "-"*30)
519
-
520
- space_host = os.getenv("SPACE_HOST")
521
- space_id = os.getenv("SPACE_ID")
522
-
523
- if space_host:
524
- print(f"✅ SPACE_HOST found: {space_host}")
525
- print(f" Runtime URL should be: https://{space_host}.hf.space")
526
- else:
527
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
528
-
529
- if space_id:
530
- print(f"✅ SPACE_ID found: {space_id}")
531
- print(f" Repo URL: https://huggingface.co/spaces/{space_id}")
532
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id}/tree/main")
533
- else:
534
- print("ℹ️ SPACE_ID environment variable not found (running locally?).")
535
-
536
- print("-"*(60 + len(" App Starting ")) + "\n")
537
- print("Launching Gradio Interface...")
538
- demo.launch(debug=True, share=False)
 
 
 
 
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
6
+ import asyncio
7
+ from concurrent.futures import ThreadPoolExecutor
8
  from datetime import datetime
9
+ from enum import Enum
10
+ import numpy as np
11
+ from functools import lru_cache
12
+
13
+ # Configure logging
14
+ logging.basicConfig(
15
+ level=logging.INFO,
16
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
17
+ )
18
+ logger = logging.getLogger("gaia_agent")
19
+
20
+ class ToolType(str, Enum):
21
+ CALCULATOR = "calculator"
22
+ LOCAL_SEARCH = "local_search"
23
+ REASONING = "reasoning"
24
+ FILE_PROCESSOR = "file_processor"
25
+
26
+ class AgentState(BaseModel):
27
+ """Tracks the agent's internal state during processing"""
28
+ current_step: int = 0
29
+ max_steps: int = 5
30
+ intermediate_results: List[Dict[str, Any]] = Field(default_factory=list)
31
+ tools_used: List[str] = Field(default_factory=list)
32
+ confidence_score: float = 0.0
33
+
34
+ class ToolResult(BaseModel):
35
+ """Standardized output format for all tools"""
36
+ success: bool
37
+ result: Any
38
+ error_message: Optional[str] = None
39
+ metadata: Dict[str, Any] = Field(default_factory=dict)
40
+
41
+ class Question(BaseModel):
42
+ """Structure for incoming questions"""
43
+ text: str
44
+ context: Optional[str] = None
45
+ attachments: Optional[List[str]] = None
46
+ metadata: Dict[str, Any] = Field(default_factory=dict)
47
+
48
+ class Answer(BaseModel):
49
+ """Structure for agent responses"""
50
+ text: str
51
+ confidence: float
52
+ reasoning_trace: List[str]
53
+ tools_used: List[str]
54
+ processing_time: float
55
+ timestamp: datetime = Field(default_factory=datetime.now)
56
+
57
+ class Tool(BaseModel):
58
+ """Base class for all tools"""
59
+ name: str
60
+ description: str
61
+ type: ToolType
62
 
63
+ async def execute(self, input_data: Any) -> ToolResult:
64
+ raise NotImplementedError
 
 
 
 
65
 
66
+ class Calculator(Tool):
67
+ """Safe calculator implementation"""
68
+ def __init__(self):
69
+ super().__init__(
70
+ name="calculator",
71
+ description="Performs safe mathematical calculations",
72
+ type=ToolType.CALCULATOR
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  )
 
 
 
 
 
74
 
75
+ @staticmethod
76
+ def _safe_eval(expr: str) -> float:
77
+ # Implement safe math evaluation here
78
+ allowed_names = {
79
+ 'abs': abs, 'round': round,
80
+ 'min': min, 'max': max,
81
+ 'sum': sum, 'pow': pow
82
+ }
83
+ code = compile(expr, '<string>', 'eval')
84
+ for name in code.co_names:
85
+ if name not in allowed_names:
86
+ raise NameError(f"Use of {name} not allowed")
87
+ return eval(expr, {"__builtins__": {}}, allowed_names)
88
+
89
+ async def execute(self, input_data: str) -> ToolResult:
90
+ try:
91
+ result = self._safe_eval(input_data)
92
+ return ToolResult(
93
+ success=True,
94
+ result=result,
95
+ metadata={"operation": input_data}
96
+ )
97
+ except Exception as e:
98
+ return ToolResult(
99
+ success=False,
100
+ result=None,
101
+ error_message=str(e)
102
+ )
103
 
104
+ class LocalSearch(Tool):
105
+ """Vector-based local search implementation"""
106
+ def __init__(self, knowledge_base_path: Path):
107
+ super().__init__(
108
+ name="local_search",
109
+ description="Searches local knowledge base",
110
+ type=ToolType.LOCAL_SEARCH
111
+ )
112
+ self.knowledge_base_path = knowledge_base_path
113
+ self._load_knowledge_base()
114
 
115
+ def _load_knowledge_base(self):
116
+ # Implement knowledge base loading logic
117
+ pass
118
 
119
+ @lru_cache(maxsize=1000)
120
+ async def execute(self, query: str) -> ToolResult:
121
+ # Implement vector search logic
122
+ return ToolResult(
123
+ success=True,
124
+ result="Search result placeholder",
125
+ metadata={"query": query}
126
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
 
128
+ class ImprovedAgent:
129
+ """Enhanced GAIA agent implementation"""
130
+ def __init__(self, model, tools: List[Tool]):
131
+ self.model = model
132
+ self.tools = {tool.name: tool for tool in tools}
133
+ self.state = AgentState()
134
+ self._executor = ThreadPoolExecutor(max_workers=3)
135
 
136
+ self.system_prompt = """You are a highly capable AI assistant focused on solving complex problems.
137
+ Your task is to analyze questions and provide accurate answers using available tools.
138
+ Always show your reasoning process and be explicit about your confidence level.
139
+ When using tools, clearly explain why you chose them and how their results contribute to the answer.
140
+ Format your response as:
141
+ REASONING: [Your step-by-step thought process]
142
+ TOOL USAGE: [If any tools were used, explain how and why]
143
+ CONFIDENCE: [0-1 score with explanation]
144
+ FINAL ANSWER: [Your conclusive answer]"""
145
+
146
+ async def _process_step(self, question: Question) -> Optional[Answer]:
147
+ """Process a single step of reasoning and tool usage"""
148
  try:
149
+ # Prepare the context for the model
150
+ context = self._prepare_context(question)
151
 
152
+ # Get model's analysis of the next step
153
+ response = await self._get_model_response(context)
154
+
155
+ # Parse the response to extract reasoning and tool requests
156
+ parsed = self._parse_model_response(response)
 
 
 
 
 
 
 
 
 
 
 
 
157
 
158
+ # If tools are requested, execute them
159
+ if parsed.get('tool_requests'):
160
+ tool_results = await self._execute_tools(parsed['tool_requests'])
161
+ # Add tool results to state
162
+ self.state.tools_used.extend([req['tool'] for req in parsed['tool_requests']])
163
+ self.state.intermediate_results.append({
164
+ 'step': self.state.current_step,
165
+ 'tool_results': tool_results
166
+ })
167
+
168
+ # If we need more processing, return None to continue
169
+ if not parsed.get('is_final', False):
170
+ return None
171
 
172
+ # If we have a final answer, construct and return it
173
+ if parsed.get('final_answer'):
174
+ return Answer(
175
+ text=parsed['final_answer'],
176
+ confidence=parsed.get('confidence', 0.0),
177
+ reasoning_trace=self.state.intermediate_results,
178
+ tools_used=self.state.tools_used,
179
+ processing_time=0.0 # Will be updated in process_question
180
+ )
181
 
182
+ return None
 
183
 
184
  except Exception as e:
185
+ logger.error(f"Error in processing step: {e}")
186
+ return None
187
+
188
+ def _prepare_context(self, question: Question) -> str:
189
+ """Prepare the context for the model including question and state"""
190
+ context = [
191
+ self.system_prompt,
192
+ f"\nCurrent question: {question.text}"
193
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
 
195
+ if question.context:
196
+ context.append(f"Additional context: {question.context}")
197
 
198
+ if self.state.intermediate_results:
199
+ context.append("\nPrevious steps:")
200
+ for result in self.state.intermediate_results:
201
+ context.append(f"Step {result['step']}: {json.dumps(result['tool_results'])}")
202
 
203
+ return "\n".join(context)
204
+
205
+ async def _get_model_response(self, context: str) -> str:
206
+ """Get the model's response for the current step"""
207
+ try:
208
+ response = await self.model.generate(context)
209
+ return response
210
+ except Exception as e:
211
+ logger.error(f"Error getting model response: {e}")
212
+ return ""
213
+
214
+ def _parse_model_response(self, response: str) -> Dict[str, Any]:
215
+ """Parse the model's response to extract reasoning and actions"""
216
+ result = {
217
+ 'tool_requests': [],
218
+ 'is_final': False,
219
+ 'final_answer': None,
220
+ 'confidence': 0.0
221
+ }
222
 
223
+ # Parse response sections
224
+ sections = response.split('\n')
225
+ current_section = None
226
 
227
+ for line in sections:
228
+ if line.startswith('REASONING:'):
229
+ current_section = 'reasoning'
230
+ continue
231
+ elif line.startswith('TOOL USAGE:'):
232
+ current_section = 'tool_usage'
233
+ continue
234
+ elif line.startswith('CONFIDENCE:'):
235
+ try:
236
+ confidence = float(line.split(':')[1].strip().split()[0])
237
+ result['confidence'] = min(max(confidence, 0.0), 1.0)
238
+ except:
239
+ pass
240
+ continue
241
+ elif line.startswith('FINAL ANSWER:'):
242
+ result['is_final'] = True
243
+ result['final_answer'] = line.split(':')[1].strip()
244
+ continue
245
 
246
+ # Parse tool requests from TOOL USAGE section
247
+ if current_section == 'tool_usage' and line.strip():
248
+ tool_match = line.strip()
249
+ if any(tool.name in tool_match.lower() for tool in self.tools.values()):
250
+ tool_name = next(name for name in self.tools.keys()
251
+ if name in tool_match.lower())
252
+ result['tool_requests'].append({
253
+ 'tool': tool_name,
254
+ 'input': tool_match.split(tool_name)[1].strip()
255
+ })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
 
257
+ return result
258
+
259
+ async def _execute_tools(self, tool_requests: List[Dict[str, str]]) -> List[Dict[str, Any]]:
260
+ """Execute requested tools in parallel"""
261
+ results = []
 
 
 
262
 
263
+ async def execute_tool(request):
264
+ tool = self.tools.get(request['tool'])
265
+ if tool:
266
+ result = await tool.execute(request['input'])
267
+ return {
268
+ 'tool': request['tool'],
269
+ 'input': request['input'],
270
+ 'result': result
271
+ }
272
+ return None
273
 
274
+ # Execute tools in parallel
275
+ tasks = [execute_tool(req) for req in tool_requests]
276
+ tool_results = await asyncio.gather(*tasks)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
 
278
+ return [r for r in tool_results if r is not None]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
279
 
280
+ async def process_question(self, question: str, context: Optional[str] = None) -> Answer:
281
+ """Main entry point for question processing"""
282
+ start_time = datetime.now()
 
 
 
 
 
 
 
 
 
 
283
 
284
+ question_obj = Question(
285
+ text=question,
286
+ context=context
 
 
 
287
  )
288
 
289
+ self.state = AgentState() # Reset state
 
 
290
 
291
+ final_answer = None
292
+ while self.state.current_step < self.state.max_steps and not final_answer:
293
+ step_result = await self._process_step(question_obj)
294
+ if step_result:
295
+ final_answer = step_result
296
+ self.state.current_step += 1
 
 
 
 
 
 
 
 
 
297
 
298
+ if not final_answer:
299
+ # Fallback handling
300
+ final_answer = Answer(
301
+ text="Unable to process question",
302
+ confidence=0.0,
303
+ reasoning_trace=["Processing failed"],
304
+ tools_used=[],
305
+ processing_time=0.0
306
+ )
307
+
308
+ processing_time = (datetime.now() - start_time).total_seconds()
309
+ final_answer.processing_time = processing_time
310
+
311
+ return final_answer
312
+
313
+ def create_agent(model, knowledge_base_path: Path) -> ImprovedAgent:
314
+ """Factory function to create a configured agent"""
315
+ tools = [
316
+ Calculator(),
317
+ LocalSearch(knowledge_base_path)
318
+ ]
319
+ return ImprovedAgent(model, tools)