rate limit avoiding
Browse files
app.py
CHANGED
|
@@ -6,12 +6,14 @@ import pandas as pd
|
|
| 6 |
import google.generativeai as genai
|
| 7 |
import re
|
| 8 |
import time
|
|
|
|
| 9 |
|
| 10 |
# --- Constants ---
|
| 11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 12 |
-
MAX_ITERATIONS = 7 #
|
|
|
|
| 13 |
|
| 14 |
-
# --- Tool Definitions ---
|
| 15 |
|
| 16 |
class WebSearchTool:
|
| 17 |
"""
|
|
@@ -28,7 +30,8 @@ class WebSearchTool:
|
|
| 28 |
payload = {
|
| 29 |
"model": "llama-3-sonar-small-32k-online",
|
| 30 |
"messages": [
|
| 31 |
-
|
|
|
|
| 32 |
{"role": "user", "content": query}
|
| 33 |
]
|
| 34 |
}
|
|
@@ -63,10 +66,8 @@ class FileDownloaderTool:
|
|
| 63 |
try:
|
| 64 |
response = requests.get(file_url, timeout=20)
|
| 65 |
response.raise_for_status()
|
| 66 |
-
# Assuming the file content is text
|
| 67 |
content = response.text
|
| 68 |
print(f"FileDownloaderTool successfully read file for task {task_id}. Content length: {len(content)}")
|
| 69 |
-
# Return a summary or a portion if the content is too long
|
| 70 |
if len(content) > 5000:
|
| 71 |
return f"File content (first 5000 chars):\n{content[:5000]}"
|
| 72 |
return f"File content:\n{content}"
|
|
@@ -86,18 +87,27 @@ class FileDownloaderTool:
|
|
| 86 |
class GAIAAgent:
|
| 87 |
def __init__(self, gemini_api_key: str, pplx_api_key: str, api_url: str):
|
| 88 |
print("Initializing GAIAAgent...")
|
| 89 |
-
# Configure Gemini
|
| 90 |
genai.configure(api_key=gemini_api_key)
|
| 91 |
self.model = genai.GenerativeModel('gemini-1.5-flash-latest')
|
| 92 |
|
| 93 |
-
# Initialize Tools
|
| 94 |
self.tools = {
|
| 95 |
"WebSearch": WebSearchTool(api_key=pplx_api_key),
|
| 96 |
"FileDownloader": FileDownloaderTool(api_url=api_url),
|
| 97 |
}
|
| 98 |
|
| 99 |
-
#
|
| 100 |
-
self.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
You are a helpful assistant designed to answer questions accurately.
|
| 102 |
|
| 103 |
To solve the user's question, you must use a sequence of thoughts and actions.
|
|
@@ -111,7 +121,6 @@ Your reasoning process should follow this format:
|
|
| 111 |
Thought: I need to figure out what information is missing. I will use a tool to find it.
|
| 112 |
Action: ToolName[input for the tool]
|
| 113 |
Observation: [The result from the tool will be inserted here]
|
| 114 |
-
|
| 115 |
... (this Thought/Action/Observation cycle can repeat multiple times)
|
| 116 |
|
| 117 |
Thought: I have now gathered enough information to answer the user's question.
|
|
@@ -120,46 +129,68 @@ Final Answer: The final answer to the original question.
|
|
| 120 |
**Important Rules:**
|
| 121 |
1. The `Action` line must be *exactly* in the format `ToolName[input]`. For example: `WebSearch[When was the Eiffel Tower built?]`.
|
| 122 |
2. The `task_id` for the current question is '{task_id}'. Use it ONLY with the FileDownloader tool.
|
| 123 |
-
3.
|
| 124 |
-
4. Once you have the final answer, do not use any more tools. State the final answer clearly after "Final Answer:".
|
| 125 |
|
| 126 |
Here is the question:
|
| 127 |
{question}
|
| 128 |
"""
|
| 129 |
print("GAIAAgent initialized successfully.")
|
| 130 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
def __call__(self, question: str, task_id: str) -> str:
|
| 132 |
-
print(f"
|
| 133 |
|
| 134 |
-
#
|
| 135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
-
# Start the ReAct loop
|
| 138 |
for i in range(MAX_ITERATIONS):
|
| 139 |
-
print(f"\n--- Iteration {i+1} ---")
|
| 140 |
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
# Add a small delay to avoid hitting rate limits too quickly
|
| 144 |
-
time.sleep(1)
|
| 145 |
-
response = self.model.generate_content(prompt)
|
| 146 |
-
response_text = response.text
|
| 147 |
-
print(f"LLM Response:\n{response_text}")
|
| 148 |
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
return f"Error: Could not get a response from the reasoning model. {e}"
|
| 152 |
|
| 153 |
-
# Check for Final Answer
|
| 154 |
final_answer_match = re.search(r"Final Answer:\s*(.*)", response_text, re.DOTALL)
|
| 155 |
if final_answer_match:
|
| 156 |
final_answer = final_answer_match.group(1).strip()
|
| 157 |
print(f"Found Final Answer: {final_answer}")
|
| 158 |
-
# Per instructions, return only the answer itself
|
| 159 |
return final_answer
|
| 160 |
|
| 161 |
-
|
| 162 |
-
action_match = re.search(r"Action:\s*(\w+)\[(.*?)\]", response_text)
|
| 163 |
if action_match:
|
| 164 |
tool_name = action_match.group(1).strip()
|
| 165 |
tool_input = action_match.group(2).strip()
|
|
@@ -168,7 +199,6 @@ Here is the question:
|
|
| 168 |
print(f"Executing tool '{tool_name}' with input '{tool_input}'")
|
| 169 |
tool = self.tools[tool_name]
|
| 170 |
try:
|
| 171 |
-
# Special handling for FileDownloader which needs task_id
|
| 172 |
if tool_name == "FileDownloader":
|
| 173 |
observation = tool.execute(task_id)
|
| 174 |
else:
|
|
@@ -176,26 +206,20 @@ Here is the question:
|
|
| 176 |
except Exception as e:
|
| 177 |
observation = f"Error executing tool: {e}"
|
| 178 |
|
| 179 |
-
|
| 180 |
-
prompt += f"{response_text}\nObservation: {observation}\n"
|
| 181 |
else:
|
| 182 |
print(f"Error: Agent tried to use an unknown tool: {tool_name}")
|
| 183 |
-
|
| 184 |
else:
|
| 185 |
-
print("Error: Agent did not provide a valid Action or Final Answer.
|
| 186 |
-
# If the model just gives a response without the proper format, return it as a last resort.
|
| 187 |
return response_text.strip()
|
| 188 |
|
| 189 |
print("Agent reached max iterations without finding a final answer.")
|
| 190 |
-
return "Agent could not determine the answer within the allowed number of steps."
|
| 191 |
|
| 192 |
|
| 193 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 194 |
-
|
| 195 |
-
Fetches all questions, runs the GAIAAgent on them, submits all answers,
|
| 196 |
-
and displays the results.
|
| 197 |
-
"""
|
| 198 |
-
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 199 |
space_id = os.getenv("SPACE_ID")
|
| 200 |
|
| 201 |
if profile:
|
|
@@ -205,12 +229,11 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 205 |
print("User not logged in.")
|
| 206 |
return "Please Login to Hugging Face with the button.", None
|
| 207 |
|
| 208 |
-
# --- Get API Keys from Secrets ---
|
| 209 |
pplx_key = os.getenv("PPLX_API_KEY")
|
| 210 |
gemini_key = os.getenv("GEMINI_API_KEY")
|
| 211 |
|
| 212 |
if not pplx_key or not gemini_key:
|
| 213 |
-
error_msg = "API keys not found in Space secrets. Please set PPLX_API_KEY and GEMINI_API_KEY
|
| 214 |
print(error_msg)
|
| 215 |
return error_msg, None
|
| 216 |
|
|
@@ -218,7 +241,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 218 |
questions_url = f"{api_url}/questions"
|
| 219 |
submit_url = f"{api_url}/submit"
|
| 220 |
|
| 221 |
-
# 1. Instantiate Agent
|
| 222 |
try:
|
| 223 |
agent = GAIAAgent(gemini_api_key=gemini_key, pplx_api_key=pplx_key, api_url=api_url)
|
| 224 |
except Exception as e:
|
|
@@ -228,28 +250,16 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 228 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 229 |
print(f"Agent code link: {agent_code}")
|
| 230 |
|
| 231 |
-
# 2. Fetch Questions
|
| 232 |
-
print(f"Fetching questions from: {questions_url}")
|
| 233 |
try:
|
| 234 |
response = requests.get(questions_url, timeout=15)
|
| 235 |
response.raise_for_status()
|
| 236 |
questions_data = response.json()
|
| 237 |
if not questions_data:
|
| 238 |
-
print("Fetched questions list is empty.")
|
| 239 |
return "Fetched questions list is empty or invalid format.", None
|
| 240 |
print(f"Fetched {len(questions_data)} questions.")
|
| 241 |
-
except requests.exceptions.RequestException as e:
|
| 242 |
-
print(f"Error fetching questions: {e}")
|
| 243 |
-
return f"Error fetching questions: {e}", None
|
| 244 |
-
except requests.exceptions.JSONDecodeError as e:
|
| 245 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 246 |
-
print(f"Response text: {response.text[:500]}")
|
| 247 |
-
return f"Error decoding server response for questions: {e}", None
|
| 248 |
except Exception as e:
|
| 249 |
-
|
| 250 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
| 251 |
|
| 252 |
-
# 3. Run your Agent
|
| 253 |
results_log = []
|
| 254 |
answers_payload = []
|
| 255 |
print(f"Running agent on {len(questions_data)} questions...")
|
|
@@ -257,30 +267,29 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 257 |
task_id = item.get("task_id")
|
| 258 |
question_text = item.get("question")
|
| 259 |
if not task_id or question_text is None:
|
| 260 |
-
print(f"Skipping item with missing task_id or question: {item}")
|
| 261 |
continue
|
| 262 |
try:
|
| 263 |
-
# Pass both question and task_id to the agent
|
| 264 |
submitted_answer = agent(question_text, task_id)
|
| 265 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 266 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 267 |
except Exception as e:
|
| 268 |
print(f"Error running agent on task {task_id}: {e}")
|
| 269 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 270 |
|
| 271 |
if not answers_payload:
|
| 272 |
-
print("Agent did not produce any answers to submit.")
|
| 273 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 274 |
|
| 275 |
-
# 4. Prepare Submission
|
| 276 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 277 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 278 |
print(status_update)
|
| 279 |
|
| 280 |
-
# 5. Submit
|
| 281 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 282 |
try:
|
| 283 |
-
response = requests.post(submit_url, json=submission_data, timeout=120)
|
| 284 |
response.raise_for_status()
|
| 285 |
result_data = response.json()
|
| 286 |
final_status = (
|
|
@@ -304,24 +313,13 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 304 |
print(status_message)
|
| 305 |
results_df = pd.DataFrame(results_log)
|
| 306 |
return status_message, results_df
|
| 307 |
-
except requests.exceptions.Timeout:
|
| 308 |
-
status_message = "Submission Failed: The request timed out."
|
| 309 |
-
print(status_message)
|
| 310 |
-
results_df = pd.DataFrame(results_log)
|
| 311 |
-
return status_message, results_df
|
| 312 |
-
except requests.exceptions.RequestException as e:
|
| 313 |
-
status_message = f"Submission Failed: Network error - {e}"
|
| 314 |
-
print(status_message)
|
| 315 |
-
results_df = pd.DataFrame(results_log)
|
| 316 |
-
return status_message, results_df
|
| 317 |
except Exception as e:
|
| 318 |
status_message = f"An unexpected error occurred during submission: {e}"
|
| 319 |
print(status_message)
|
| 320 |
results_df = pd.DataFrame(results_log)
|
| 321 |
return status_message, results_df
|
| 322 |
|
| 323 |
-
|
| 324 |
-
# --- Build Gradio Interface using Blocks ---
|
| 325 |
with gr.Blocks() as demo:
|
| 326 |
gr.Markdown("# GAIA Agent Evaluation Runner")
|
| 327 |
gr.Markdown(
|
|
@@ -332,42 +330,18 @@ with gr.Blocks() as demo:
|
|
| 332 |
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 333 |
---
|
| 334 |
**Disclaimers:**
|
| 335 |
-
This process
|
| 336 |
"""
|
| 337 |
)
|
| 338 |
-
|
| 339 |
gr.LoginButton()
|
| 340 |
-
|
| 341 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 342 |
-
|
| 343 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 344 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 345 |
-
|
| 346 |
-
# Add the profile object from the LoginButton to the click function's inputs
|
| 347 |
run_button.click(
|
| 348 |
fn=run_and_submit_all,
|
| 349 |
-
# The login button automatically provides the profile object to functions that need it.
|
| 350 |
-
# We just need to ensure the function signature matches.
|
| 351 |
outputs=[status_output, results_table]
|
| 352 |
)
|
| 353 |
|
| 354 |
if __name__ == "__main__":
|
| 355 |
-
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 356 |
-
space_host_startup = os.getenv("SPACE_HOST")
|
| 357 |
-
space_id_startup = os.getenv("SPACE_ID")
|
| 358 |
-
|
| 359 |
-
if space_host_startup:
|
| 360 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 361 |
-
else:
|
| 362 |
-
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 363 |
-
|
| 364 |
-
if space_id_startup:
|
| 365 |
-
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 366 |
-
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 367 |
-
else:
|
| 368 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally?).")
|
| 369 |
-
|
| 370 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 371 |
-
|
| 372 |
print("Launching Gradio Interface for GAIA Agent Evaluation...")
|
| 373 |
demo.launch(debug=True, share=False)
|
|
|
|
| 6 |
import google.generativeai as genai
|
| 7 |
import re
|
| 8 |
import time
|
| 9 |
+
from google.api_core import exceptions
|
| 10 |
|
| 11 |
# --- Constants ---
|
| 12 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 13 |
+
MAX_ITERATIONS = 7 # Max steps in the ReAct loop
|
| 14 |
+
MAX_RETRIES = 5 # NEW: Max retries for API calls
|
| 15 |
|
| 16 |
+
# --- Tool Definitions (No changes here, kept for completeness) ---
|
| 17 |
|
| 18 |
class WebSearchTool:
|
| 19 |
"""
|
|
|
|
| 30 |
payload = {
|
| 31 |
"model": "llama-3-sonar-small-32k-online",
|
| 32 |
"messages": [
|
| 33 |
+
# MODIFIED: A slightly better prompt for GAIA-style questions
|
| 34 |
+
{"role": "system", "content": "You are a world-class research assistant. Answer the user's query based on verifiable public information. Be precise and comprehensive."},
|
| 35 |
{"role": "user", "content": query}
|
| 36 |
]
|
| 37 |
}
|
|
|
|
| 66 |
try:
|
| 67 |
response = requests.get(file_url, timeout=20)
|
| 68 |
response.raise_for_status()
|
|
|
|
| 69 |
content = response.text
|
| 70 |
print(f"FileDownloaderTool successfully read file for task {task_id}. Content length: {len(content)}")
|
|
|
|
| 71 |
if len(content) > 5000:
|
| 72 |
return f"File content (first 5000 chars):\n{content[:5000]}"
|
| 73 |
return f"File content:\n{content}"
|
|
|
|
| 87 |
class GAIAAgent:
|
| 88 |
def __init__(self, gemini_api_key: str, pplx_api_key: str, api_url: str):
|
| 89 |
print("Initializing GAIAAgent...")
|
|
|
|
| 90 |
genai.configure(api_key=gemini_api_key)
|
| 91 |
self.model = genai.GenerativeModel('gemini-1.5-flash-latest')
|
| 92 |
|
|
|
|
| 93 |
self.tools = {
|
| 94 |
"WebSearch": WebSearchTool(api_key=pplx_api_key),
|
| 95 |
"FileDownloader": FileDownloaderTool(api_url=api_url),
|
| 96 |
}
|
| 97 |
|
| 98 |
+
# MODIFIED: A simpler prompt for the initial zero-shot check
|
| 99 |
+
self.zero_shot_prompt_template = """
|
| 100 |
+
You are a helpful assistant. Your job is to answer the user's question directly and concisely.
|
| 101 |
+
Do not explain your reasoning.
|
| 102 |
+
Do not use tools.
|
| 103 |
+
If you can answer the question with high confidence, provide the answer.
|
| 104 |
+
If the question requires browsing the web, accessing a file, or performing complex calculations, respond with the single word: "UNSURE".
|
| 105 |
+
|
| 106 |
+
Question: {question}
|
| 107 |
+
Answer:
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
self.react_prompt_template = """
|
| 111 |
You are a helpful assistant designed to answer questions accurately.
|
| 112 |
|
| 113 |
To solve the user's question, you must use a sequence of thoughts and actions.
|
|
|
|
| 121 |
Thought: I need to figure out what information is missing. I will use a tool to find it.
|
| 122 |
Action: ToolName[input for the tool]
|
| 123 |
Observation: [The result from the tool will be inserted here]
|
|
|
|
| 124 |
... (this Thought/Action/Observation cycle can repeat multiple times)
|
| 125 |
|
| 126 |
Thought: I have now gathered enough information to answer the user's question.
|
|
|
|
| 129 |
**Important Rules:**
|
| 130 |
1. The `Action` line must be *exactly* in the format `ToolName[input]`. For example: `WebSearch[When was the Eiffel Tower built?]`.
|
| 131 |
2. The `task_id` for the current question is '{task_id}'. Use it ONLY with the FileDownloader tool.
|
| 132 |
+
3. Once you have the final answer, do not use any more tools. State the final answer clearly after "Final Answer:". Your entire response should end here.
|
|
|
|
| 133 |
|
| 134 |
Here is the question:
|
| 135 |
{question}
|
| 136 |
"""
|
| 137 |
print("GAIAAgent initialized successfully.")
|
| 138 |
|
| 139 |
+
# NEW: Function to handle API calls with exponential backoff
|
| 140 |
+
def _call_gemini_api_with_backoff(self, prompt_text):
|
| 141 |
+
retries = 0
|
| 142 |
+
while retries < MAX_RETRIES:
|
| 143 |
+
try:
|
| 144 |
+
print(f"Attempt {retries + 1} to call Gemini API...")
|
| 145 |
+
response = self.model.generate_content(prompt_text)
|
| 146 |
+
return response.text
|
| 147 |
+
except exceptions.ResourceExhausted as e:
|
| 148 |
+
print(f"API Rate Limit Exceeded (429). Waiting to retry... ({e.message})")
|
| 149 |
+
wait_time = (2 ** retries) + 1 # Exponential backoff: 2, 3, 5, 9, 17 seconds
|
| 150 |
+
time.sleep(wait_time)
|
| 151 |
+
retries += 1
|
| 152 |
+
except Exception as e:
|
| 153 |
+
print(f"An unexpected error occurred with Gemini API: {e}")
|
| 154 |
+
return f"AGENT_ERROR: An unexpected error occurred: {e}"
|
| 155 |
+
|
| 156 |
+
print("Max retries reached. Failing.")
|
| 157 |
+
return "AGENT_ERROR: API rate limit exceeded after multiple retries."
|
| 158 |
+
|
| 159 |
def __call__(self, question: str, task_id: str) -> str:
|
| 160 |
+
print(f"\n{'='*20}\nProcessing Task ID: {task_id}\nQuestion: {question[:100]}...")
|
| 161 |
|
| 162 |
+
# === NEW: Step 1 - Zero-Shot Attempt ===
|
| 163 |
+
print("--- Step 1: Zero-Shot Attempt ---")
|
| 164 |
+
zero_shot_prompt = self.zero_shot_prompt_template.format(question=question)
|
| 165 |
+
zero_shot_answer = self._call_gemini_api_with_backoff(zero_shot_prompt).strip()
|
| 166 |
+
|
| 167 |
+
if "AGENT_ERROR" in zero_shot_answer:
|
| 168 |
+
return zero_shot_answer # Propagate API failure
|
| 169 |
+
|
| 170 |
+
if "UNSURE" not in zero_shot_answer.upper():
|
| 171 |
+
print(f"Zero-shot successful! Answer: {zero_shot_answer}")
|
| 172 |
+
return zero_shot_answer
|
| 173 |
+
|
| 174 |
+
# === MODIFIED: Step 2 - ReAct Loop ===
|
| 175 |
+
print("--- Step 2: Zero-shot failed, starting ReAct loop ---")
|
| 176 |
+
react_prompt = self.react_prompt_template.format(question=question, task_id=task_id)
|
| 177 |
|
|
|
|
| 178 |
for i in range(MAX_ITERATIONS):
|
| 179 |
+
print(f"\n--- ReAct Iteration {i+1} ---")
|
| 180 |
|
| 181 |
+
response_text = self._call_gemini_api_with_backoff(react_prompt)
|
| 182 |
+
print(f"LLM Response:\n{response_text}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
|
| 184 |
+
if "AGENT_ERROR" in response_text:
|
| 185 |
+
return response_text # Propagate API failure
|
|
|
|
| 186 |
|
|
|
|
| 187 |
final_answer_match = re.search(r"Final Answer:\s*(.*)", response_text, re.DOTALL)
|
| 188 |
if final_answer_match:
|
| 189 |
final_answer = final_answer_match.group(1).strip()
|
| 190 |
print(f"Found Final Answer: {final_answer}")
|
|
|
|
| 191 |
return final_answer
|
| 192 |
|
| 193 |
+
action_match = re.search(r"Action:\s*(\w+)\[(.*?)\]", response_text, re.DOTALL)
|
|
|
|
| 194 |
if action_match:
|
| 195 |
tool_name = action_match.group(1).strip()
|
| 196 |
tool_input = action_match.group(2).strip()
|
|
|
|
| 199 |
print(f"Executing tool '{tool_name}' with input '{tool_input}'")
|
| 200 |
tool = self.tools[tool_name]
|
| 201 |
try:
|
|
|
|
| 202 |
if tool_name == "FileDownloader":
|
| 203 |
observation = tool.execute(task_id)
|
| 204 |
else:
|
|
|
|
| 206 |
except Exception as e:
|
| 207 |
observation = f"Error executing tool: {e}"
|
| 208 |
|
| 209 |
+
react_prompt += f"{response_text}\nObservation: {observation}\n"
|
|
|
|
| 210 |
else:
|
| 211 |
print(f"Error: Agent tried to use an unknown tool: {tool_name}")
|
| 212 |
+
react_prompt += f"{response_text}\nObservation: Error - The tool '{tool_name}' does not exist.\n"
|
| 213 |
else:
|
| 214 |
+
print("Error: Agent did not provide a valid Action or Final Answer. Returning last response.")
|
|
|
|
| 215 |
return response_text.strip()
|
| 216 |
|
| 217 |
print("Agent reached max iterations without finding a final answer.")
|
| 218 |
+
return "AGENT_ERROR: Agent could not determine the answer within the allowed number of steps."
|
| 219 |
|
| 220 |
|
| 221 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 222 |
+
# This function is mostly the same, with one key change added.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
space_id = os.getenv("SPACE_ID")
|
| 224 |
|
| 225 |
if profile:
|
|
|
|
| 229 |
print("User not logged in.")
|
| 230 |
return "Please Login to Hugging Face with the button.", None
|
| 231 |
|
|
|
|
| 232 |
pplx_key = os.getenv("PPLX_API_KEY")
|
| 233 |
gemini_key = os.getenv("GEMINI_API_KEY")
|
| 234 |
|
| 235 |
if not pplx_key or not gemini_key:
|
| 236 |
+
error_msg = "API keys not found in Space secrets. Please set PPLX_API_KEY and GEMINI_API_KEY."
|
| 237 |
print(error_msg)
|
| 238 |
return error_msg, None
|
| 239 |
|
|
|
|
| 241 |
questions_url = f"{api_url}/questions"
|
| 242 |
submit_url = f"{api_url}/submit"
|
| 243 |
|
|
|
|
| 244 |
try:
|
| 245 |
agent = GAIAAgent(gemini_api_key=gemini_key, pplx_api_key=pplx_key, api_url=api_url)
|
| 246 |
except Exception as e:
|
|
|
|
| 250 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 251 |
print(f"Agent code link: {agent_code}")
|
| 252 |
|
|
|
|
|
|
|
| 253 |
try:
|
| 254 |
response = requests.get(questions_url, timeout=15)
|
| 255 |
response.raise_for_status()
|
| 256 |
questions_data = response.json()
|
| 257 |
if not questions_data:
|
|
|
|
| 258 |
return "Fetched questions list is empty or invalid format.", None
|
| 259 |
print(f"Fetched {len(questions_data)} questions.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
except Exception as e:
|
| 261 |
+
return f"Error fetching questions: {e}", None
|
|
|
|
| 262 |
|
|
|
|
| 263 |
results_log = []
|
| 264 |
answers_payload = []
|
| 265 |
print(f"Running agent on {len(questions_data)} questions...")
|
|
|
|
| 267 |
task_id = item.get("task_id")
|
| 268 |
question_text = item.get("question")
|
| 269 |
if not task_id or question_text is None:
|
|
|
|
| 270 |
continue
|
| 271 |
try:
|
|
|
|
| 272 |
submitted_answer = agent(question_text, task_id)
|
| 273 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 274 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 275 |
except Exception as e:
|
| 276 |
print(f"Error running agent on task {task_id}: {e}")
|
| 277 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 278 |
+
|
| 279 |
+
# NEW: Add a delay between each question to respect rate limits
|
| 280 |
+
print(f"--- Waiting for 5 seconds before next question... ---")
|
| 281 |
+
time.sleep(5)
|
| 282 |
|
| 283 |
if not answers_payload:
|
|
|
|
| 284 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 285 |
|
|
|
|
| 286 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 287 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 288 |
print(status_update)
|
| 289 |
|
|
|
|
| 290 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 291 |
try:
|
| 292 |
+
response = requests.post(submit_url, json=submission_data, timeout=120)
|
| 293 |
response.raise_for_status()
|
| 294 |
result_data = response.json()
|
| 295 |
final_status = (
|
|
|
|
| 313 |
print(status_message)
|
| 314 |
results_df = pd.DataFrame(results_log)
|
| 315 |
return status_message, results_df
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
except Exception as e:
|
| 317 |
status_message = f"An unexpected error occurred during submission: {e}"
|
| 318 |
print(status_message)
|
| 319 |
results_df = pd.DataFrame(results_log)
|
| 320 |
return status_message, results_df
|
| 321 |
|
| 322 |
+
# --- Gradio Interface (No changes here) ---
|
|
|
|
| 323 |
with gr.Blocks() as demo:
|
| 324 |
gr.Markdown("# GAIA Agent Evaluation Runner")
|
| 325 |
gr.Markdown(
|
|
|
|
| 330 |
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 331 |
---
|
| 332 |
**Disclaimers:**
|
| 333 |
+
This process will now be slower due to the added delays to respect API rate limits, but it should be much more reliable. Please be patient.
|
| 334 |
"""
|
| 335 |
)
|
|
|
|
| 336 |
gr.LoginButton()
|
|
|
|
| 337 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
|
|
|
| 338 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 339 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
|
|
|
|
|
|
| 340 |
run_button.click(
|
| 341 |
fn=run_and_submit_all,
|
|
|
|
|
|
|
| 342 |
outputs=[status_output, results_table]
|
| 343 |
)
|
| 344 |
|
| 345 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 346 |
print("Launching Gradio Interface for GAIA Agent Evaluation...")
|
| 347 |
demo.launch(debug=True, share=False)
|