GoodLuckChuck commited on
Commit
d0b368a
·
verified ·
1 Parent(s): b71c860

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +282 -618
app.py CHANGED
@@ -1,655 +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
-
197
- # Initialize available tools
198
- self.tools_available = [
199
- {
200
- "type": "function",
201
- "function": {
202
- "name": "web_search",
203
- "description": "Searches the web for information based on a query.",
204
- "parameters": WebSearchInput.model_json_schema()
205
- }
206
- },
207
- {
208
- "type": "function",
209
- "function": {
210
- "name": "calculator",
211
- "description": "Evaluates mathematical expressions.",
212
- "parameters": CalculatorInput.model_json_schema()
213
- }
214
- },
215
- {
216
- "type": "function",
217
- "function": {
218
- "name": "image_analysis",
219
- "description": "Analyzes an image given its file path.",
220
- "parameters": ImageAnalysisInput.model_json_schema()
221
- }
222
- }
223
- ]
224
-
225
- self.tool_executors = {
226
- "web_search": lambda params: execute_web_search(**params),
227
- "calculator": lambda params: execute_calculator(**params),
228
- "image_analysis": lambda params: execute_image_analysis(**params)
229
- }
230
-
231
- print("AIAgent initialized with OpenAI client and tools.")
232
-
233
- def _log_step(self, message: str, data: Optional[Dict] = None):
234
- """Log a step in the reasoning process."""
235
- print(message)
236
- entry = {"message": message}
237
- if data:
238
- entry.update(data)
239
- self.reasoning_trace.append(entry)
240
 
241
- def __call__(self, question: str, file_name: Optional[str] = None, max_iterations: int = 5) -> str:
242
- """Process a single question and return an answer."""
243
- self.reasoning_trace = []
 
 
 
 
244
 
 
 
 
 
 
 
 
 
 
 
 
 
245
  try:
246
- self._log_step(f"Processing question: {question[:100]}...")
 
247
 
248
- # Update user message to include file information
249
- user_message = question
250
- if file_name:
251
- user_message += f"\n(Note: The file is located at '{file_name}')"
252
 
253
- # Initial system prompt that encourages step-by-step thinking
254
- messages = [
255
- {
256
- "role": "system",
257
- "content": (
258
- "You are a helpful AI assistant. Your goal is to answer the user's question accurately. "
259
- "Think step-by-step and explain your reasoning. If you need information or calculations, "
260
- "use the available tools. After gathering all necessary information, provide your final answer "
261
- "in the exact format specified.\n\n" + GAIA_FINAL_ANSWER_SYSTEM_PROMPT
262
- )
263
- },
264
- {
265
- "role": "user",
266
- "content": user_message
267
- }
268
- ]
269
-
270
- final_answer = None
271
- for iteration in range(max_iterations):
272
- self._log_step(f"\nIteration {iteration + 1}")
273
-
274
- response = openai.ChatCompletion.create(
275
- model=LLM_MODEL,
276
- messages=messages,
277
- tools=self.tools_available,
278
- tool_choice="auto",
279
- temperature=0.1,
280
- max_tokens=1000
281
- )
282
-
283
- response_message = response.choices[0].message
284
-
285
- # Check if the model wants to use tools
286
- if response_message.tool_calls:
287
- self._log_step("Using tools to gather information:")
288
- for tool_call in response_message.tool_calls:
289
- function_name = tool_call.function.name
290
- function_args = json.loads(tool_call.function.arguments)
291
-
292
- self._log_step(f"- Using {function_name} with args: {function_args}")
293
-
294
- if function_name in self.tool_executors:
295
- # Handle file_name for image analysis
296
- if function_name == "image_analysis" and file_name:
297
- function_args["file_name"] = file_name
298
-
299
- tool_result = self.tool_executors[function_name](function_args)
300
- self._log_step(f"Tool result: {tool_result}")
301
-
302
- # Add tool result to messages
303
- messages.append({
304
- "role": "assistant",
305
- "content": None,
306
- "tool_calls": [tool_call]
307
- })
308
- messages.append({
309
- "role": "tool",
310
- "tool_call_id": tool_call.id,
311
- "name": function_name,
312
- "content": json.dumps(tool_result)
313
- })
314
- else:
315
- # Model provided a response without using tools
316
- content = response_message.content
317
- self._log_step(f"Assistant response: {content}")
318
- messages.append({"role": "assistant", "content": content})
319
-
320
- # Check if we have a final answer
321
- if "FINAL ANSWER:" in content:
322
- final_answer = content.split("FINAL ANSWER:")[-1].strip()
323
- self._log_step(f"Found final answer: {final_answer}")
324
- break
325
 
326
- if not final_answer:
327
- # If no final answer found, make one last attempt to format the response
328
- last_prompt = (
329
- "Based on all the information gathered, please provide your final answer "
330
- "in the exact format specified. Remember to start with 'FINAL ANSWER:' "
331
- "and follow the formatting rules strictly."
332
- )
333
- messages.append({"role": "user", "content": last_prompt})
 
334
 
335
- response = openai.ChatCompletion.create(
336
- model=LLM_MODEL,
337
- messages=messages,
338
- temperature=0.1,
339
- max_tokens=1000
 
 
 
 
 
 
 
340
  )
341
-
342
- content = response.choices[0].message.content
343
- if "FINAL ANSWER:" in content:
344
- final_answer = content.split("FINAL ANSWER:")[-1].strip()
345
- else:
346
- final_answer = content.strip()
347
 
348
- return final_answer
349
 
350
  except Exception as e:
351
- error_msg = f"Error processing question: {str(e)}"
352
- self._log_step(error_msg)
353
- return f"ERROR: {error_msg}"
354
-
355
- # --- FastAPI App ---
356
- app = FastAPI(title="AI Agent API")
357
-
358
- app.add_middleware(
359
- CORSMiddleware,
360
- allow_origins=["*"],
361
- allow_credentials=True,
362
- allow_methods=["*"],
363
- allow_headers=["*"],
364
- )
365
-
366
- # Initialize the AI Agent globally
367
- if OPENAI_API_KEY_VALUE and openai.api_key:
368
- global_agent = AIAgent()
369
- else:
370
- global_agent = None
371
-
372
- @app.get("/")
373
- async def root():
374
- """Root endpoint to verify the API is running."""
375
- return {
376
- "status": "online",
377
- "timestamp": datetime.now().isoformat(),
378
- "agent_status": "initialized" if openai.api_key else "not initialized",
379
- "openai_key_set": bool(openai.api_key),
380
- "api_base_url": API_BASE_URL
381
- }
382
-
383
- @app.get("/debug")
384
- async def debug():
385
- """Debug endpoint to check configuration."""
386
- return {
387
- "openai_initialized": bool(openai.api_key),
388
- "api_base_url": API_BASE_URL,
389
- "username": USERNAME,
390
- "agent_code": AGENT_CODE_IDENTIFIER,
391
- "timestamp": datetime.now().isoformat()
392
- }
393
-
394
- @app.get("/test-questions")
395
- async def test_questions():
396
- """Test endpoint to fetch questions without processing."""
397
- try:
398
- questions = api_get_questions()
399
- return {
400
- "status": "success",
401
- "question_count": len(questions) if questions else 0,
402
- "questions": questions
403
- }
404
- except Exception as e:
405
- return {
406
- "status": "error",
407
- "error": str(e)
408
- }
409
-
410
- @app.post("/process")
411
- async def process_questions():
412
- """Process all questions and submit answers."""
413
- print("\n=== Starting question processing ===")
414
- try:
415
- # Validate OpenAI API key
416
- if not openai.api_key:
417
- raise HTTPException(
418
- status_code=500,
419
- detail="OpenAI API key not configured. Please set OPENAI_API_KEY environment variable."
420
- )
421
 
422
- print("OpenAI API key validated")
 
423
 
424
- # Initialize agent
425
- agent = AIAgent()
426
- print("AI Agent initialized")
 
427
 
428
- # Fetch questions
429
- print("Fetching questions from API...")
430
- questions = api_get_questions()
431
- if not questions:
432
- raise HTTPException(status_code=500, detail="Failed to fetch questions from API")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
433
 
434
- print(f"Successfully fetched {len(questions)} questions")
435
- processed_answers = []
 
436
 
437
- for idx, question in enumerate(questions, 1):
438
- task_id = question.get("task_id")
439
- question_text = question.get("question")
440
- file_name = question.get("file_name")
441
-
442
- print(f"\nProcessing question {idx}/{len(questions)}")
443
- print(f"Task ID: {task_id}")
444
- print(f"Question: {question_text}")
445
- if file_name:
446
- print(f"File: {file_name}")
 
 
 
 
 
 
 
 
447
 
448
- try:
449
- # Process question with file if available
450
- answer = agent(question_text, file_name)
451
-
452
- # Format answer for submission
453
- processed_answer = {
454
- "task_id": task_id,
455
- "submitted_answer": answer,
456
- "reasoning_trace": agent.reasoning_trace
457
- }
458
-
459
- processed_answers.append(processed_answer)
460
- print(f"Answer generated: {answer[:100]}...")
461
-
462
- except Exception as e:
463
- error_msg = f"Error processing question {task_id}: {str(e)}"
464
- print(error_msg)
465
- processed_answers.append({
466
- "task_id": task_id,
467
- "submitted_answer": f"ERROR: Failed to process question - {str(e)}",
468
- "reasoning_trace": [{"error": str(e)}]
469
- })
470
 
471
- if not processed_answers:
472
- raise HTTPException(
473
- status_code=500,
474
- detail="No answers were generated for any questions"
475
- )
476
-
477
- # Submit answers
478
- print("\nSubmitting answers to API...")
479
- submission_result = api_submit_answers(processed_answers)
480
- if not submission_result:
481
- raise HTTPException(
482
- status_code=500,
483
- detail="Failed to submit answers to API"
484
- )
485
 
486
- print("Submission successful!")
487
- return {
488
- "status": "success",
489
- "message": f"Processed {len(processed_answers)} questions",
490
- "submission_result": submission_result,
491
- "processed_answers": processed_answers
492
- }
 
 
 
493
 
494
- except HTTPException as he:
495
- print(f"HTTP Exception: {he.detail}")
496
- raise he
497
- except Exception as e:
498
- error_msg = f"Error in process_questions: {str(e)}"
499
- print(error_msg)
500
- raise HTTPException(status_code=500, detail=error_msg)
501
-
502
- def run_and_submit_all(profile: gr.OAuthProfile | None):
503
- """
504
- Fetches all questions, runs the AIAgent on them, submits all answers,
505
- and displays the results.
506
- """
507
- # --- Determine HF Space Runtime URL and Repo URL ---
508
- space_id = os.getenv("SPACE_ID")
509
-
510
- if profile:
511
- username = f"{profile.username}"
512
- print(f"User logged in: {username}")
513
- else:
514
- print("User not logged in.")
515
- return "Please Login to Hugging Face with the button.", None
516
-
517
- api_url = API_BASE_URL
518
- questions_url = f"{api_url}/questions"
519
- submit_url = f"{api_url}/submit"
520
-
521
- # 1. Instantiate Agent
522
- try:
523
- agent = AIAgent()
524
- except Exception as e:
525
- print(f"Error instantiating agent: {e}")
526
- return f"Error initializing agent: {e}", None
527
-
528
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
529
- print(f"Agent code URL: {agent_code}")
530
-
531
- # 2. Fetch Questions
532
- print(f"Fetching questions from: {questions_url}")
533
- try:
534
- response = requests.get(questions_url, timeout=15)
535
- response.raise_for_status()
536
- questions_data = response.json()
537
- if not questions_data:
538
- print("Fetched questions list is empty.")
539
- return "Fetched questions list is empty or invalid format.", None
540
- print(f"Fetched {len(questions_data)} questions.")
541
- except Exception as e:
542
- print(f"Error fetching questions: {e}")
543
- return f"Error fetching questions: {e}", None
544
-
545
- # 3. Run Agent
546
- results_log = []
547
- answers_payload = []
548
- print(f"Running agent on {len(questions_data)} questions...")
549
-
550
- for item in questions_data:
551
- task_id = item.get("task_id")
552
- question_text = item.get("question")
553
- if not task_id or question_text is None:
554
- print(f"Skipping item with missing task_id or question: {item}")
555
- continue
556
 
557
- try:
558
- submitted_answer = agent(question_text)
559
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
560
- results_log.append({
561
- "Task ID": task_id,
562
- "Question": question_text,
563
- "Submitted Answer": submitted_answer
564
- })
565
- print(f"Processed task {task_id}: {submitted_answer[:100]}...")
566
- except Exception as e:
567
- print(f"Error running agent on task {task_id}: {e}")
568
- results_log.append({
569
- "Task ID": task_id,
570
- "Question": question_text,
571
- "Submitted Answer": f"AGENT ERROR: {e}"
572
- })
573
 
574
- if not answers_payload:
575
- print("Agent did not produce any answers to submit.")
576
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
577
-
578
- # 4. Submit Answers
579
- submission_data = {
580
- "username": username.strip(),
581
- "agent_code": agent_code,
582
- "answers": answers_payload
583
- }
584
-
585
- print(f"Submitting {len(answers_payload)} answers for user '{username}'...")
586
-
587
- try:
588
- response = requests.post(submit_url, json=submission_data, timeout=60)
589
- response.raise_for_status()
590
- result_data = response.json()
591
 
592
- final_status = (
593
- f"Submission Successful!\n"
594
- f"User: {result_data.get('username')}\n"
595
- f"Overall Score: {result_data.get('score', 'N/A')}% "
596
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
597
- f"Message: {result_data.get('message', 'No message received.')}"
598
  )
599
 
600
- print("Submission successful.")
601
- results_df = pd.DataFrame(results_log)
602
- return final_status, results_df
603
 
604
- except Exception as e:
605
- error_msg = f"Submission failed: {str(e)}"
606
- print(error_msg)
607
- results_df = pd.DataFrame(results_log)
608
- return error_msg, results_df
609
-
610
- # --- Build Gradio Interface using Blocks ---
611
- with gr.Blocks() as demo:
612
- gr.Markdown("# AI Agent Evaluation Runner")
613
- gr.Markdown(
614
- """
615
- **Instructions:**
616
- 1. Log in to your Hugging Face account using the button below.
617
- 2. Click 'Run Evaluation & Submit All Answers' to process all questions and see results.
618
- 3. The agent will use GPT-3.5-turbo to generate answers following strict formatting rules.
619
 
620
- **Note:** Processing may take some time as each question requires an API call.
621
- """
622
- )
623
-
624
- gr.LoginButton()
625
- run_button = gr.Button("Run Evaluation & Submit All Answers")
626
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
627
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
628
-
629
- run_button.click(
630
- fn=run_and_submit_all,
631
- outputs=[status_output, results_table]
632
- )
633
-
634
- if __name__ == "__main__":
635
- print("\n" + "-"*30 + " App Starting " + "-"*30)
636
-
637
- space_host = os.getenv("SPACE_HOST")
638
- space_id = os.getenv("SPACE_ID")
639
-
640
- if space_host:
641
- print(f"✅ SPACE_HOST found: {space_host}")
642
- print(f" Runtime URL should be: https://{space_host}.hf.space")
643
- else:
644
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
645
-
646
- if space_id:
647
- print(f"✅ SPACE_ID found: {space_id}")
648
- print(f" Repo URL: https://huggingface.co/spaces/{space_id}")
649
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id}/tree/main")
650
- else:
651
- print("ℹ️ SPACE_ID environment variable not found (running locally?).")
652
-
653
- print("-"*(60 + len(" App Starting ")) + "\n")
654
- print("Launching Gradio Interface...")
655
- 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)