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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +118 -1
app.py CHANGED
@@ -9,6 +9,11 @@ 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(
@@ -17,6 +22,20 @@ logging.basicConfig(
17
  )
18
  logger = logging.getLogger("gaia_agent")
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  class ToolType(str, Enum):
21
  CALCULATOR = "calculator"
22
  LOCAL_SEARCH = "local_search"
@@ -316,4 +335,102 @@ def create_agent(model, knowledge_base_path: Path) -> ImprovedAgent:
316
  Calculator(),
317
  LocalSearch(knowledge_base_path)
318
  ]
319
- return ImprovedAgent(model, tools)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  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
 
18
  # Configure logging
19
  logging.basicConfig(
 
22
  )
23
  logger = logging.getLogger("gaia_agent")
24
 
25
+ # Add after imports, before ToolType class
26
+ async def load_test_questions(file_path: str) -> List[Dict[str, Any]]:
27
+ """Load test questions from a JSONL file"""
28
+ questions = []
29
+ try:
30
+ with open(file_path, 'r', encoding='utf-8') as f:
31
+ for line in f:
32
+ if line.strip():
33
+ questions.append(json.loads(line))
34
+ return questions
35
+ except Exception as e:
36
+ logger.error(f"Error loading test questions: {e}")
37
+ return []
38
+
39
  class ToolType(str, Enum):
40
  CALCULATOR = "calculator"
41
  LOCAL_SEARCH = "local_search"
 
335
  Calculator(),
336
  LocalSearch(knowledge_base_path)
337
  ]
338
+ return ImprovedAgent(model, tools)
339
+
340
+ # Add after the create_agent function
341
+ app = FastAPI(title="Improved GAIA Agent API")
342
+
343
+ app.add_middleware(
344
+ CORSMiddleware,
345
+ allow_origins=["*"],
346
+ allow_credentials=True,
347
+ allow_methods=["*"],
348
+ allow_headers=["*"],
349
+ )
350
+
351
+ # Initialize agent globally
352
+ agent = None
353
+ try:
354
+ from local_configuration.Local_Server_Connection import model
355
+ knowledge_base_path = Path(__file__).parent / "knowledge_base"
356
+ agent = create_agent(model, knowledge_base_path)
357
+ except Exception as e:
358
+ print(f"Error initializing agent: {e}")
359
+
360
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
361
+ """Process questions and submit answers"""
362
+ if not profile:
363
+ return "Please login to Hugging Face first.", None
364
+
365
+ if not agent:
366
+ return "Agent not properly initialized. Check configuration.", None
367
+
368
+ try:
369
+ # Get Space information
370
+ space_id = os.getenv("SPACE_ID")
371
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
372
+
373
+ # Load and process questions
374
+ test_questions_path = Path(__file__).parent / "metadata.jsonl"
375
+ questions = asyncio.run(load_test_questions(str(test_questions_path)))
376
+
377
+ if not questions:
378
+ return "No questions loaded.", None
379
+
380
+ # Process questions
381
+ results_log = []
382
+ answers_payload = []
383
+
384
+ for q in questions:
385
+ try:
386
+ answer = asyncio.run(agent.process_question(q['Question']))
387
+ answers_payload.append({
388
+ "task_id": q['task_id'],
389
+ "submitted_answer": answer.text,
390
+ "reasoning_trace": answer.reasoning_trace
391
+ })
392
+ results_log.append({
393
+ "Question": q['Question'],
394
+ "Answer": answer.text,
395
+ "Confidence": answer.confidence,
396
+ "Processing Time": f"{answer.processing_time:.2f}s"
397
+ })
398
+ except Exception as e:
399
+ print(f"Error processing question: {e}")
400
+ continue
401
+
402
+ # Submit results
403
+ submission_data = {
404
+ "username": profile.username,
405
+ "agent_code": agent_code,
406
+ "answers": answers_payload
407
+ }
408
+
409
+ # Here you would submit to the actual API
410
+ # For now, return results
411
+ return f"Processed {len(answers_payload)} questions successfully.", pd.DataFrame(results_log)
412
+
413
+ except Exception as e:
414
+ return f"Error: {str(e)}", None
415
+
416
+ # Create Gradio interface
417
+ with gr.Blocks() as demo:
418
+ gr.Markdown("# Improved GAIA Agent")
419
+ gr.Markdown("Login and run the improved agent to process questions.")
420
+
421
+ gr.LoginButton()
422
+ run_button = gr.Button("Process Questions")
423
+ status_output = gr.Textbox(label="Status")
424
+ results_table = gr.DataFrame(label="Results")
425
+
426
+ run_button.click(
427
+ fn=run_and_submit_all,
428
+ outputs=[status_output, results_table]
429
+ )
430
+
431
+ # Add FastAPI endpoint to mount Gradio
432
+ app = gr.mount_gradio_app(app, demo, path="/")
433
+
434
+ if __name__ == "__main__":
435
+ import uvicorn
436
+ uvicorn.run(app, host="0.0.0.0", port=7860)