Update app.py
#155
by
joshuarebo
- opened
app.py
CHANGED
@@ -3,32 +3,53 @@ import gradio as gr
|
|
3 |
import requests
|
4 |
import inspect
|
5 |
import pandas as pd
|
|
|
|
|
6 |
|
7 |
-
# (Keep Constants as is)
|
8 |
# --- Constants ---
|
9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
10 |
|
11 |
-
# ---
|
12 |
-
|
13 |
-
class BasicAgent:
|
14 |
def __init__(self):
|
15 |
-
print("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
def __call__(self, question: str) -> str:
|
17 |
-
print(f"Agent received question
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
|
30 |
if profile:
|
31 |
-
username= f"{profile.username}"
|
32 |
print(f"User logged in: {username}")
|
33 |
else:
|
34 |
print("User not logged in.")
|
@@ -38,66 +59,47 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
38 |
questions_url = f"{api_url}/questions"
|
39 |
submit_url = f"{api_url}/submit"
|
40 |
|
41 |
-
# 1. Instantiate Agent ( modify this part to create your agent)
|
42 |
try:
|
43 |
-
agent =
|
44 |
except Exception as e:
|
45 |
-
print(f"Error instantiating agent: {e}")
|
46 |
return f"Error initializing agent: {e}", None
|
47 |
-
|
48 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
49 |
print(agent_code)
|
50 |
|
51 |
-
# 2. Fetch Questions
|
52 |
-
print(f"Fetching questions from: {questions_url}")
|
53 |
try:
|
54 |
response = requests.get(questions_url, timeout=15)
|
55 |
response.raise_for_status()
|
56 |
questions_data = response.json()
|
57 |
if not questions_data:
|
58 |
-
|
59 |
-
return "Fetched questions list is empty or invalid format.", None
|
60 |
print(f"Fetched {len(questions_data)} questions.")
|
61 |
except requests.exceptions.RequestException as e:
|
62 |
-
print(f"Error fetching questions: {e}")
|
63 |
return f"Error fetching questions: {e}", None
|
64 |
except requests.exceptions.JSONDecodeError as e:
|
65 |
-
|
66 |
-
print(f"Response text: {response.text[:500]}")
|
67 |
-
return f"Error decoding server response for questions: {e}", None
|
68 |
-
except Exception as e:
|
69 |
-
print(f"An unexpected error occurred fetching questions: {e}")
|
70 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
71 |
|
72 |
-
# 3. Run your Agent
|
73 |
results_log = []
|
74 |
answers_payload = []
|
75 |
-
|
76 |
for item in questions_data:
|
77 |
task_id = item.get("task_id")
|
78 |
question_text = item.get("question")
|
79 |
if not task_id or question_text is None:
|
80 |
-
print(f"Skipping item with missing task_id or question: {item}")
|
81 |
continue
|
82 |
try:
|
83 |
submitted_answer = agent(question_text)
|
84 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
85 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
86 |
except Exception as e:
|
87 |
-
|
88 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
89 |
|
90 |
if not answers_payload:
|
91 |
-
print("Agent did not produce any answers to submit.")
|
92 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
93 |
|
94 |
-
# 4. Prepare Submission
|
95 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
96 |
-
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
97 |
-
print(status_update)
|
98 |
-
|
99 |
-
# 5. Submit
|
100 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
|
|
101 |
try:
|
102 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
103 |
response.raise_for_status()
|
@@ -109,61 +111,33 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
109 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
110 |
f"Message: {result_data.get('message', 'No message received.')}"
|
111 |
)
|
112 |
-
print("Submission successful.")
|
113 |
results_df = pd.DataFrame(results_log)
|
114 |
return final_status, results_df
|
115 |
-
except requests.exceptions.HTTPError as e:
|
116 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
117 |
-
try:
|
118 |
-
error_json = e.response.json()
|
119 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
120 |
-
except requests.exceptions.JSONDecodeError:
|
121 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
122 |
-
status_message = f"Submission Failed: {error_detail}"
|
123 |
-
print(status_message)
|
124 |
-
results_df = pd.DataFrame(results_log)
|
125 |
-
return status_message, results_df
|
126 |
-
except requests.exceptions.Timeout:
|
127 |
-
status_message = "Submission Failed: The request timed out."
|
128 |
-
print(status_message)
|
129 |
-
results_df = pd.DataFrame(results_log)
|
130 |
-
return status_message, results_df
|
131 |
except requests.exceptions.RequestException as e:
|
132 |
-
|
133 |
-
print(status_message)
|
134 |
-
results_df = pd.DataFrame(results_log)
|
135 |
-
return status_message, results_df
|
136 |
except Exception as e:
|
137 |
-
|
138 |
-
print(status_message)
|
139 |
-
results_df = pd.DataFrame(results_log)
|
140 |
-
return status_message, results_df
|
141 |
-
|
142 |
|
143 |
-
# ---
|
144 |
with gr.Blocks() as demo:
|
145 |
-
gr.Markdown("#
|
146 |
gr.Markdown(
|
147 |
"""
|
148 |
**Instructions:**
|
149 |
|
150 |
-
1.
|
151 |
-
2.
|
152 |
-
3.
|
153 |
|
154 |
---
|
155 |
-
|
156 |
-
Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
|
157 |
-
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
|
158 |
"""
|
159 |
)
|
160 |
|
161 |
gr.LoginButton()
|
162 |
-
|
163 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
164 |
|
165 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
166 |
-
# Removed max_rows=10 from DataFrame constructor
|
167 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
168 |
|
169 |
run_button.click(
|
@@ -173,24 +147,20 @@ with gr.Blocks() as demo:
|
|
173 |
|
174 |
if __name__ == "__main__":
|
175 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
176 |
-
# Check for SPACE_HOST and SPACE_ID at startup for information
|
177 |
space_host_startup = os.getenv("SPACE_HOST")
|
178 |
-
space_id_startup = os.getenv("SPACE_ID")
|
179 |
|
180 |
if space_host_startup:
|
181 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
182 |
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
183 |
else:
|
184 |
-
print("ℹ️ SPACE_HOST
|
185 |
|
186 |
-
if space_id_startup:
|
187 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
188 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
189 |
-
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
190 |
else:
|
191 |
-
print("ℹ️ SPACE_ID
|
192 |
|
193 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
194 |
-
|
195 |
-
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
196 |
-
demo.launch(debug=True, share=False)
|
|
|
3 |
import requests
|
4 |
import inspect
|
5 |
import pandas as pd
|
6 |
+
from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
|
7 |
+
import torch
|
8 |
|
|
|
9 |
# --- Constants ---
|
10 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
11 |
|
12 |
+
# --- Advanced GAIA-Ready Agent ---
|
13 |
+
class GaiaAgent:
|
|
|
14 |
def __init__(self):
|
15 |
+
print("Initializing GaiaAgent with open-source model...")
|
16 |
+
|
17 |
+
model_name = "google/flan-t5-large" # Good balance between size and reasoning quality
|
18 |
+
auth_token = os.getenv("HF_TOKEN")
|
19 |
+
|
20 |
+
self.device = 0 if torch.cuda.is_available() else -1
|
21 |
+
self.pipe = pipeline(
|
22 |
+
"text2text-generation",
|
23 |
+
model=model_name,
|
24 |
+
tokenizer=model_name,
|
25 |
+
token=auth_token,
|
26 |
+
device=self.device
|
27 |
+
)
|
28 |
+
print("Model and tokenizer loaded.")
|
29 |
+
|
30 |
def __call__(self, question: str) -> str:
|
31 |
+
print(f"Agent received question: {question[:60]}...")
|
32 |
+
prompt = (
|
33 |
+
f"Answer the following question as accurately as possible.\n"
|
34 |
+
f"Question: {question}\n"
|
35 |
+
f"Answer:"
|
36 |
+
)
|
37 |
+
try:
|
38 |
+
result = self.pipe(prompt, max_new_tokens=64, clean_up_tokenization_spaces=True)[0]["generated_text"]
|
39 |
+
# Ensure clean return without "Answer:" prefix
|
40 |
+
answer = result.strip().replace("Answer:", "").strip()
|
41 |
+
print(f"Agent returned: {answer}")
|
42 |
+
return answer
|
43 |
+
except Exception as e:
|
44 |
+
print(f"Error during model inference: {e}")
|
45 |
+
return f"AGENT ERROR: {e}"
|
46 |
+
|
47 |
+
# --- Evaluation & Submission Logic ---
|
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 |
print(f"User logged in: {username}")
|
54 |
else:
|
55 |
print("User not logged in.")
|
|
|
59 |
questions_url = f"{api_url}/questions"
|
60 |
submit_url = f"{api_url}/submit"
|
61 |
|
|
|
62 |
try:
|
63 |
+
agent = GaiaAgent()
|
64 |
except Exception as e:
|
|
|
65 |
return f"Error initializing agent: {e}", None
|
66 |
+
|
67 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
68 |
print(agent_code)
|
69 |
|
|
|
|
|
70 |
try:
|
71 |
response = requests.get(questions_url, timeout=15)
|
72 |
response.raise_for_status()
|
73 |
questions_data = response.json()
|
74 |
if not questions_data:
|
75 |
+
return "Fetched questions list is empty or invalid format.", None
|
|
|
76 |
print(f"Fetched {len(questions_data)} questions.")
|
77 |
except requests.exceptions.RequestException as e:
|
|
|
78 |
return f"Error fetching questions: {e}", None
|
79 |
except requests.exceptions.JSONDecodeError as e:
|
80 |
+
return f"Error decoding server response for questions: {e}", None
|
|
|
|
|
|
|
|
|
|
|
81 |
|
|
|
82 |
results_log = []
|
83 |
answers_payload = []
|
84 |
+
|
85 |
for item in questions_data:
|
86 |
task_id = item.get("task_id")
|
87 |
question_text = item.get("question")
|
88 |
if not task_id or question_text is None:
|
|
|
89 |
continue
|
90 |
try:
|
91 |
submitted_answer = agent(question_text)
|
92 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
93 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
94 |
except Exception as e:
|
95 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
|
|
96 |
|
97 |
if not answers_payload:
|
|
|
98 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
99 |
|
|
|
100 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
|
|
|
|
|
|
|
|
101 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
102 |
+
|
103 |
try:
|
104 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
105 |
response.raise_for_status()
|
|
|
111 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
112 |
f"Message: {result_data.get('message', 'No message received.')}"
|
113 |
)
|
|
|
114 |
results_df = pd.DataFrame(results_log)
|
115 |
return final_status, results_df
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
116 |
except requests.exceptions.RequestException as e:
|
117 |
+
return f"Submission Failed: {e}", pd.DataFrame(results_log)
|
|
|
|
|
|
|
118 |
except Exception as e:
|
119 |
+
return f"An unexpected error occurred during submission: {e}", pd.DataFrame(results_log)
|
|
|
|
|
|
|
|
|
120 |
|
121 |
+
# --- Gradio UI ---
|
122 |
with gr.Blocks() as demo:
|
123 |
+
gr.Markdown("# GAIA-Level Agent Evaluation Runner")
|
124 |
gr.Markdown(
|
125 |
"""
|
126 |
**Instructions:**
|
127 |
|
128 |
+
1. Modify and extend the agent in the code section.
|
129 |
+
2. Login with your Hugging Face account to submit answers.
|
130 |
+
3. Click the button to run and submit.
|
131 |
|
132 |
---
|
133 |
+
*This agent uses `google/flan-t5-large` from Hugging Face to answer questions.*
|
|
|
|
|
134 |
"""
|
135 |
)
|
136 |
|
137 |
gr.LoginButton()
|
|
|
138 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
139 |
|
140 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
|
|
141 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
142 |
|
143 |
run_button.click(
|
|
|
147 |
|
148 |
if __name__ == "__main__":
|
149 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
|
|
150 |
space_host_startup = os.getenv("SPACE_HOST")
|
151 |
+
space_id_startup = os.getenv("SPACE_ID")
|
152 |
|
153 |
if space_host_startup:
|
154 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
155 |
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
156 |
else:
|
157 |
+
print("ℹ️ SPACE_HOST not found.")
|
158 |
|
159 |
+
if space_id_startup:
|
160 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
161 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
|
|
162 |
else:
|
163 |
+
print("ℹ️ SPACE_ID not found.")
|
164 |
|
165 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
166 |
+
demo.launch(debug=True, share=False)
|
|
|
|