dawid-lorek commited on
Commit
fdb94f8
·
verified ·
1 Parent(s): b93c01e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -23
app.py CHANGED
@@ -5,13 +5,14 @@ import requests
5
  import pandas as pd
6
 
7
  from smolagents import CodeAgent, OpenAIServerModel
8
- from smolagents.tools.web_search import WebSearchTool
9
 
10
  # Constants
11
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
  MAX_QUESTION_LENGTH = 4000
13
 
14
- class RetryableWebSearchTool(WebSearchTool):
 
15
  def run(self, query: str) -> str:
16
  for attempt in range(3):
17
  try:
@@ -22,8 +23,9 @@ class RetryableWebSearchTool(WebSearchTool):
22
  time.sleep(2 * (attempt + 1))
23
  else:
24
  raise
25
- raise RuntimeError("Web search failed after retries")
26
 
 
27
  class SmartGAIAAgent:
28
  def __init__(self):
29
  key = os.getenv("OPENAI_API_KEY")
@@ -31,19 +33,20 @@ class SmartGAIAAgent:
31
  raise ValueError("Missing OPENAI_API_KEY")
32
  model = OpenAIServerModel(model_id="gpt-4", api_key=key)
33
  self.agent = CodeAgent(
 
34
  model=model,
35
- tools=[RetryableWebSearchTool()],
36
  add_base_tools=True
37
  )
38
 
39
  def __call__(self, question: str) -> str:
40
- question = question[:MAX_QUESTION_LENGTH]
41
  try:
42
- return self.agent.run(question).strip()
43
  except Exception as e:
44
  print("Agent error:", e)
45
  return "error"
46
 
 
47
  def run_and_submit_all(profile: gr.OAuthProfile | None):
48
  username = profile.username if profile else None
49
  if not username:
@@ -54,34 +57,30 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
54
  except Exception as e:
55
  return f"Error initializing agent: {e}", None
56
 
57
- response = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15)
58
- response.raise_for_status()
59
- questions = response.json()
60
-
61
- payload = []
62
- logs = []
63
 
 
 
64
  for item in questions:
65
  tid = item.get("task_id")
66
- q = item.get("question", "")
67
- if not tid or not q or len(q) > MAX_QUESTION_LENGTH:
68
  continue
69
- if any(skip in q.lower() for skip in ['.mp3', '.wav', '.jpg', '.png', 'youtube', 'video', 'watch', 'listen']):
70
- continue
71
- answer = agent(q)
72
- payload.append({"task_id": tid, "submitted_answer": answer})
73
- logs.append({"Task ID": tid, "Question": q, "Submitted Answer": answer})
74
 
75
  if not payload:
76
  return "No valid questions to submit.", pd.DataFrame(logs)
77
 
78
- submission = {
79
  "username": username,
80
  "agent_code": f"https://huggingface.co/spaces/{os.getenv('SPACE_ID')}/tree/main",
81
- "answers": payload,
82
  }
83
-
84
- resp = requests.post(f"{DEFAULT_API_URL}/submit", json=submission, timeout=30)
85
  resp.raise_for_status()
86
  result = resp.json()
87
  status = f"Score: {result.get('score')}% ({result.get('correct_count')}/{result.get('total_attempted')})"
 
5
  import pandas as pd
6
 
7
  from smolagents import CodeAgent, OpenAIServerModel
8
+ from smolagents.tools import WebSearchTool, BaseTools
9
 
10
  # Constants
11
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
  MAX_QUESTION_LENGTH = 4000
13
 
14
+ # Reliable search tool with retry
15
+ class ReliableWebSearch(WebSearchTool):
16
  def run(self, query: str) -> str:
17
  for attempt in range(3):
18
  try:
 
23
  time.sleep(2 * (attempt + 1))
24
  else:
25
  raise
26
+ raise RuntimeError("WebSearchTool failed after retries")
27
 
28
+ # Main agent using GPT-4 & tools
29
  class SmartGAIAAgent:
30
  def __init__(self):
31
  key = os.getenv("OPENAI_API_KEY")
 
33
  raise ValueError("Missing OPENAI_API_KEY")
34
  model = OpenAIServerModel(model_id="gpt-4", api_key=key)
35
  self.agent = CodeAgent(
36
+ tools=[ReliableWebSearch()],
37
  model=model,
 
38
  add_base_tools=True
39
  )
40
 
41
  def __call__(self, question: str) -> str:
42
+ q = question[:MAX_QUESTION_LENGTH]
43
  try:
44
+ return self.agent.run(q).strip()
45
  except Exception as e:
46
  print("Agent error:", e)
47
  return "error"
48
 
49
+ # Fetch, filter, run, and submit answers
50
  def run_and_submit_all(profile: gr.OAuthProfile | None):
51
  username = profile.username if profile else None
52
  if not username:
 
57
  except Exception as e:
58
  return f"Error initializing agent: {e}", None
59
 
60
+ resp = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15)
61
+ resp.raise_for_status()
62
+ questions = resp.json()
 
 
 
63
 
64
+ payload, logs = [], []
65
+ skip_kw = ['.mp3','.wav','.png','.jpg','youtube','video','watch','listen']
66
  for item in questions:
67
  tid = item.get("task_id")
68
+ q = item.get("question","")
69
+ if not tid or not q or len(q)>MAX_QUESTION_LENGTH or any(k in q.lower() for k in skip_kw):
70
  continue
71
+ ans = agent(q)
72
+ payload.append({"task_id": tid, "submitted_answer": ans})
73
+ logs.append({"Task ID": tid, "Question": q, "Submitted Answer": ans})
 
 
74
 
75
  if not payload:
76
  return "No valid questions to submit.", pd.DataFrame(logs)
77
 
78
+ sub = {
79
  "username": username,
80
  "agent_code": f"https://huggingface.co/spaces/{os.getenv('SPACE_ID')}/tree/main",
81
+ "answers": payload
82
  }
83
+ resp = requests.post(f"{DEFAULT_API_URL}/submit", json=sub, timeout=60)
 
84
  resp.raise_for_status()
85
  result = resp.json()
86
  status = f"Score: {result.get('score')}% ({result.get('correct_count')}/{result.get('total_attempted')})"