sofials commited on
Commit
bc5057d
·
verified ·
1 Parent(s): e4d6348

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +9 -23
app.py CHANGED
@@ -2,23 +2,18 @@ import os
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
 
5
  from smolagents import CodeAgent, DuckDuckGoSearchTool, VisitWebpageTool, InferenceClientModel
6
 
7
- # --- Constants ---
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
10
- # --- Agent Definition ---
11
  class GaiaAgent:
12
  def __init__(self):
13
  print("Initializing GaiaAgent...")
14
-
15
- # Modello HF via API
16
  self.model = InferenceClientModel(
17
  model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
18
  token=os.getenv("HF_TOKEN"),
19
  )
20
-
21
- # Tool
22
  self.agent = CodeAgent(
23
  tools=[
24
  DuckDuckGoSearchTool(),
@@ -31,33 +26,30 @@ class GaiaAgent:
31
  print("GaiaAgent ready!")
32
 
33
  def __call__(self, question: str) -> str:
34
- print(f"Question: {question[:100]}...")
35
-
36
- # Prompt che forza risposta pulita — fondamentale per exact match
37
- prompt = f"""Answer the following question.
38
- Your answer must be as concise as possible — just the final answer, no explanation, no punctuation unless required.
39
  If the answer is a number, return just the number.
40
  If the answer is a name, return just the name.
41
  If the answer is a list, return comma-separated values.
42
 
43
  Question: {question}"""
44
-
45
  try:
46
  response = self.agent.run(prompt)
47
- answer = str(response).strip()
48
- print(f"Answer: {answer}")
49
- return answer
50
  except Exception as e:
51
  print(f"Error: {e}")
52
  return "I don't know"
53
 
 
 
 
 
54
 
55
  def run_and_submit_all(profile: gr.OAuthProfile | None):
56
  space_id = os.getenv("SPACE_ID")
57
 
58
  if profile:
59
  username = f"{profile.username}"
60
- print(f"User logged in: {username}")
61
  else:
62
  return "Please Login to Hugging Face with the button.", None
63
 
@@ -65,7 +57,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
65
  questions_url = f"{api_url}/questions"
66
  submit_url = f"{api_url}/submit"
67
 
68
- # 1. Inizializza agente
69
  try:
70
  agent = GaiaAgent()
71
  except Exception as e:
@@ -73,7 +64,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
73
 
74
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
75
 
76
- # 2. Fetch domande
77
  try:
78
  response = requests.get(questions_url, timeout=15)
79
  response.raise_for_status()
@@ -82,7 +72,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
82
  except Exception as e:
83
  return f"Error fetching questions: {e}", None
84
 
85
- # 3. Esegui agente su ogni domanda
86
  results_log = []
87
  answers_payload = []
88
 
@@ -92,7 +81,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
92
  if not task_id or question_text is None:
93
  continue
94
  try:
95
- submitted_answer = agent(question_text)
96
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
97
  results_log.append({
98
  "Task ID": task_id,
@@ -109,7 +98,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
109
  if not answers_payload:
110
  return "Agent did not produce any answers.", pd.DataFrame(results_log)
111
 
112
- # 4. Submit
113
  submission_data = {
114
  "username": username.strip(),
115
  "agent_code": agent_code,
@@ -132,14 +120,12 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
132
  return f"Submission Failed: {e}", pd.DataFrame(results_log)
133
 
134
 
135
- # --- Gradio Interface ---
136
  with gr.Blocks() as demo:
137
  gr.Markdown("# 🎩 GAIA Agent — sofials")
138
  gr.Markdown("""
139
  **Instructions:**
140
  1. Log in with your Hugging Face account
141
  2. Click 'Run Evaluation & Submit All Answers'
142
- 3. Wait for the agent to answer all questions (may take several minutes)
143
  """)
144
 
145
  gr.LoginButton()
 
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
5
+ import spaces
6
  from smolagents import CodeAgent, DuckDuckGoSearchTool, VisitWebpageTool, InferenceClientModel
7
 
 
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
 
10
  class GaiaAgent:
11
  def __init__(self):
12
  print("Initializing GaiaAgent...")
 
 
13
  self.model = InferenceClientModel(
14
  model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
15
  token=os.getenv("HF_TOKEN"),
16
  )
 
 
17
  self.agent = CodeAgent(
18
  tools=[
19
  DuckDuckGoSearchTool(),
 
26
  print("GaiaAgent ready!")
27
 
28
  def __call__(self, question: str) -> str:
29
+ prompt = f"""Answer the following question.
30
+ Your answer must be as concise as possible — just the final answer, no explanation.
 
 
 
31
  If the answer is a number, return just the number.
32
  If the answer is a name, return just the name.
33
  If the answer is a list, return comma-separated values.
34
 
35
  Question: {question}"""
 
36
  try:
37
  response = self.agent.run(prompt)
38
+ return str(response).strip()
 
 
39
  except Exception as e:
40
  print(f"Error: {e}")
41
  return "I don't know"
42
 
43
+ # Funzione con decoratore GPU — obbligatorio per ZeroGPU
44
+ @spaces.GPU
45
+ def run_agent_on_question(agent, question):
46
+ return agent(question)
47
 
48
  def run_and_submit_all(profile: gr.OAuthProfile | None):
49
  space_id = os.getenv("SPACE_ID")
50
 
51
  if profile:
52
  username = f"{profile.username}"
 
53
  else:
54
  return "Please Login to Hugging Face with the button.", None
55
 
 
57
  questions_url = f"{api_url}/questions"
58
  submit_url = f"{api_url}/submit"
59
 
 
60
  try:
61
  agent = GaiaAgent()
62
  except Exception as e:
 
64
 
65
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
66
 
 
67
  try:
68
  response = requests.get(questions_url, timeout=15)
69
  response.raise_for_status()
 
72
  except Exception as e:
73
  return f"Error fetching questions: {e}", None
74
 
 
75
  results_log = []
76
  answers_payload = []
77
 
 
81
  if not task_id or question_text is None:
82
  continue
83
  try:
84
+ submitted_answer = run_agent_on_question(agent, question_text)
85
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
86
  results_log.append({
87
  "Task ID": task_id,
 
98
  if not answers_payload:
99
  return "Agent did not produce any answers.", pd.DataFrame(results_log)
100
 
 
101
  submission_data = {
102
  "username": username.strip(),
103
  "agent_code": agent_code,
 
120
  return f"Submission Failed: {e}", pd.DataFrame(results_log)
121
 
122
 
 
123
  with gr.Blocks() as demo:
124
  gr.Markdown("# 🎩 GAIA Agent — sofials")
125
  gr.Markdown("""
126
  **Instructions:**
127
  1. Log in with your Hugging Face account
128
  2. Click 'Run Evaluation & Submit All Answers'
 
129
  """)
130
 
131
  gr.LoginButton()