jonathan9879 commited on
Commit
30ab757
·
verified ·
1 Parent(s): e3c5ce5

gemini 2.5 pro

Browse files
Files changed (1) hide show
  1. app.py +41 -66
app.py CHANGED
@@ -8,12 +8,12 @@ import re
8
  import time
9
  from google.api_core import exceptions
10
 
11
- # --- Constants (No Changes) ---
12
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
  MAX_ITERATIONS = 7
14
  MAX_RETRIES = 5
15
 
16
- # --- Tool Definitions (No Changes) ---
17
  class WebSearchTool:
18
  def __init__(self, api_key):
19
  self.api_key = api_key
@@ -23,7 +23,7 @@ class WebSearchTool:
23
  payload = {"model": "llama-3-sonar-small-32k-online", "messages": [{"role": "system", "content": "You are a world-class research assistant. Answer the user's query based on verifiable public information. Be precise and comprehensive."}, {"role": "user", "content": query}]}
24
  headers = {"accept": "application/json", "content-type": "application/json", "Authorization": f"Bearer {self.api_key}"}
25
  try:
26
- response = requests.post(self.url, json=payload, headers=headers, timeout=30)
27
  response.raise_for_status()
28
  return response.json()['choices'][0]['message']['content']
29
  except requests.exceptions.RequestException as e:
@@ -51,87 +51,77 @@ class GAIAAgent:
51
  def __init__(self, gemini_api_key: str, pplx_api_key: str, api_url: str):
52
  print("Initializing GAIAAgent...")
53
  genai.configure(api_key=gemini_api_key)
54
- self.model = genai.GenerativeModel('gemini-1.5-flash-latest')
 
 
 
 
 
55
  self.tools = {"WebSearch": WebSearchTool(api_key=pplx_api_key), "FileDownloader": FileDownloaderTool(api_url=api_url)}
56
 
57
- # MODIFIED: Made the zero-shot prompt even stricter to prevent conversational filler.
58
  self.zero_shot_prompt_template = """
59
- You are a highly intelligent question-answering bot. Follow these instructions precisely.
60
- 1. Analyze the user's question.
61
- 2. If the question is simple and you are 100% certain of the answer without needing any tools, provide ONLY the answer and nothing else.
62
- 3. If the question requires web searches, file access, or complex reasoning, respond with the single word: UNSURE.
63
- Do not add any explanations or introductory phrases.
64
 
65
  Question: {question}
66
  Answer:"""
67
 
68
- # MODIFIED: Added a new, explicit rule for how to fail gracefully.
69
  self.react_prompt_template = """
70
- You are a helpful assistant designed to answer questions accurately.
71
-
72
- To solve the user's question, you must use a sequence of thoughts and actions.
73
- You have access to the following tools:
74
 
75
- - **WebSearch[query]**: Use this to search the internet for up-to-date information.
76
- - **FileDownloader[task_id]**: Use this to download a file associated with the current task. The task_id is '{task_id}'.
 
77
 
78
- Your reasoning process should follow this format:
79
-
80
- Thought: I need to figure out what information is missing. I will use a tool to find it.
81
- Action: ToolName[input for the tool]
82
  Observation: [The result from the tool will be inserted here]
83
- ... (this Thought/Action/Observation cycle can repeat)
84
-
85
- Thought: I have now gathered enough information to answer the user's question.
86
- Final Answer: The final answer to the original question.
87
 
88
- **Important Rules:**
89
- 1. The `Action` line must be *exactly* in the format `ToolName[input]`.
90
- 2. The `task_id` for the current question is '{task_id}'. Use it ONLY with the FileDownloader tool.
91
- 3. **CRITICAL RULE:** If you determine that the question cannot be answered with your tools (e.g., a required file is missing, the information is not on the web), you MUST conclude with: `Final Answer: I am unable to answer this question.` Do not make up an answer.
92
 
93
- Here is the question:
94
- {question}"""
95
- print("GAIAAgent initialized successfully.")
96
 
97
  def _call_gemini_api_with_backoff(self, prompt_text):
98
  retries = 0
99
  while retries < MAX_RETRIES:
100
  try:
101
- time.sleep(1) # Add a small base delay
102
  response = self.model.generate_content(prompt_text)
103
  return response.text
104
  except exceptions.ResourceExhausted as e:
105
- wait_time = (2 ** retries)
106
  print(f"API Rate Limit Exceeded (429). Waiting for {wait_time}s to retry...")
107
  time.sleep(wait_time)
108
  retries += 1
109
  except Exception as e:
 
110
  return f"AGENT_ERROR: An unexpected error occurred: {e}"
111
  return "AGENT_ERROR: API rate limit exceeded after multiple retries."
112
 
113
  def __call__(self, question: str, task_id: str) -> str:
114
  print(f"\n{'='*20}\nProcessing Task ID: {task_id}\nQuestion: {question[:100]}...")
 
115
 
116
- print("--- Step 1: Zero-Shot Attempt ---")
117
  zero_shot_prompt = self.zero_shot_prompt_template.format(question=question)
118
  zero_shot_answer = self._call_gemini_api_with_backoff(zero_shot_prompt).strip()
119
-
120
- if "AGENT_ERROR" in zero_shot_answer: return zero_shot_answer
121
-
122
- if "UNSURE" not in zero_shot_answer.upper():
123
  print(f"Zero-shot successful! Answer: {zero_shot_answer}")
124
  return zero_shot_answer
125
 
126
- print("--- Step 2: Zero-shot failed, starting ReAct loop ---")
127
-
128
- # CRITICAL FIX: Reset the prompt history for each question to prevent context bleed.
129
- # This was the cause of the botany/bird video mix-up.
130
  current_prompt_history = self.react_prompt_template.format(question=question, task_id=task_id)
131
 
132
  for i in range(MAX_ITERATIONS):
133
  print(f"\n--- ReAct Iteration {i+1} ---")
134
-
135
  response_text = self._call_gemini_api_with_backoff(current_prompt_history)
136
  print(f"LLM Response:\n{response_text}")
137
 
@@ -147,32 +137,25 @@ Here is the question:
147
  if action_match:
148
  tool_name = action_match.group(1).strip()
149
  tool_input = action_match.group(2).strip()
150
-
151
  if tool_name in self.tools:
152
  tool = self.tools[tool_name]
153
  try:
154
  observation = tool.execute(task_id if tool_name == "FileDownloader" else tool_input)
155
- except Exception as e:
156
- observation = f"Error executing tool: {e}"
157
- # Append the whole thought/action/observation cycle
158
  current_prompt_history += f"\n{response_text}\nObservation: {observation}"
159
  else:
160
  current_prompt_history += f"\n{response_text}\nObservation: Error - The tool '{tool_name}' does not exist."
161
  else:
162
- print("Error: Agent did not provide a valid Action or Final Answer. Returning last response.")
163
  return response_text.strip()
164
-
165
  return "AGENT_ERROR: Agent reached max iterations."
166
 
167
- # --- Main run_and_submit_all function (No significant changes needed here, only added a longer sleep) ---
168
  def run_and_submit_all(profile: gr.OAuthProfile | None):
169
  space_id = os.getenv("SPACE_ID")
170
  if not profile: return "Please Login to Hugging Face with the button.", None
171
  username = f"{profile.username}"
172
- print(f"User logged in: {username}")
173
 
174
- pplx_key = os.getenv("PPLX_API_KEY")
175
- gemini_key = os.getenv("GEMINI_API_KEY")
176
  if not pplx_key or not gemini_key: return "API keys not found in Space secrets.", None
177
 
178
  api_url = DEFAULT_API_URL
@@ -192,8 +175,8 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
192
  except Exception as e:
193
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
194
 
195
- print(f"--- Waiting for 8 seconds before next question to respect rate limits ---")
196
- time.sleep(8) # Increased delay to be safer
197
 
198
  if not answers_payload: return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
199
 
@@ -212,18 +195,10 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
212
  except requests.exceptions.RequestException as e:
213
  return f"Submission Failed: {e}", pd.DataFrame(results_log)
214
 
215
- # --- Gradio Interface (No changes) ---
216
  with gr.Blocks() as demo:
217
  gr.Markdown("# GAIA Agent Evaluation Runner")
218
- gr.Markdown("""
219
- **Instructions:**
220
- 1. Ensure you have added your `PPLX_API_KEY` and `GEMINI_API_KEY` to this Space's **Settings > Secrets**.
221
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
222
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
223
- ---
224
- **Disclaimers:**
225
- This process is slow due to the added delays to respect API rate limits. Please be patient.
226
- """)
227
  gr.LoginButton()
228
  run_button = gr.Button("Run Evaluation & Submit All Answers")
229
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
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
14
  MAX_RETRIES = 5
15
 
16
+ # --- Tool Definitions (Unchanged) ---
17
  class WebSearchTool:
18
  def __init__(self, api_key):
19
  self.api_key = api_key
 
23
  payload = {"model": "llama-3-sonar-small-32k-online", "messages": [{"role": "system", "content": "You are a world-class research assistant. Answer the user's query based on verifiable public information. Be precise and comprehensive."}, {"role": "user", "content": query}]}
24
  headers = {"accept": "application/json", "content-type": "application/json", "Authorization": f"Bearer {self.api_key}"}
25
  try:
26
+ response = requests.post(self.url, json=payload, headers=headers, timeout=40)
27
  response.raise_for_status()
28
  return response.json()['choices'][0]['message']['content']
29
  except requests.exceptions.RequestException as e:
 
51
  def __init__(self, gemini_api_key: str, pplx_api_key: str, api_url: str):
52
  print("Initializing GAIAAgent...")
53
  genai.configure(api_key=gemini_api_key)
54
+
55
+ # --- CORRECTING THE MODEL TO THE USER'S SPECIFICATION ---
56
+ self.model_name = 'gemini-2.5-pro-preview-06-05'
57
+ self.model = genai.GenerativeModel(self.model_name)
58
+ print(f"Agent equipped with user-specified model: {self.model_name}")
59
+
60
  self.tools = {"WebSearch": WebSearchTool(api_key=pplx_api_key), "FileDownloader": FileDownloaderTool(api_url=api_url)}
61
 
 
62
  self.zero_shot_prompt_template = """
63
+ Analyze the following question. If the answer is self-contained in the question and requires no external tools, provide the answer directly and concisely. Otherwise, respond with the single word: UNSURE.
 
 
 
 
64
 
65
  Question: {question}
66
  Answer:"""
67
 
 
68
  self.react_prompt_template = """
69
+ You are a state-of-the-art reasoning agent. Your goal is to answer the user's question by creating a plan and executing it using the tools provided.
 
 
 
70
 
71
+ **Tools Available:**
72
+ - **WebSearch[query]**: Searches the web for information. Use different queries if initial results are not satisfactory.
73
+ - **FileDownloader[task_id]**: Downloads a file for a specific task. The task_id is '{task_id}'.
74
 
75
+ **Reasoning Format:**
76
+ Thought: My reasoning process and plan to solve the question.
77
+ Action: The tool I will use, in the format `ToolName[input]`.
 
78
  Observation: [The result from the tool will be inserted here]
79
+ ... (The Thought/Action/Observation cycle can repeat)
80
+ Thought: I have sufficient information to provide the final answer.
81
+ Final Answer: The definitive answer to the user's question.
 
82
 
83
+ **Guiding Principles:**
84
+ 1. **Persist:** Do not give up easily. If a search fails, re-evaluate and try a more specific or different query.
85
+ 2. **Conclude:** Once you have the answer, state it clearly with `Final Answer:`.
86
+ 3. **Fail Gracefully:** If, after several genuine attempts, you conclude the answer is unobtainable, state `Final Answer: I am unable to answer this question.`
87
 
88
+ Question: {question}"""
89
+ print("GAIAAgent initialized with refined prompts for the specified model.")
 
90
 
91
  def _call_gemini_api_with_backoff(self, prompt_text):
92
  retries = 0
93
  while retries < MAX_RETRIES:
94
  try:
95
+ time.sleep(2)
96
  response = self.model.generate_content(prompt_text)
97
  return response.text
98
  except exceptions.ResourceExhausted as e:
99
+ wait_time = (2 ** retries) + 2
100
  print(f"API Rate Limit Exceeded (429). Waiting for {wait_time}s to retry...")
101
  time.sleep(wait_time)
102
  retries += 1
103
  except Exception as e:
104
+ print(f"An unexpected error occurred with Gemini API: {e}")
105
  return f"AGENT_ERROR: An unexpected error occurred: {e}"
106
  return "AGENT_ERROR: API rate limit exceeded after multiple retries."
107
 
108
  def __call__(self, question: str, task_id: str) -> str:
109
  print(f"\n{'='*20}\nProcessing Task ID: {task_id}\nQuestion: {question[:100]}...")
110
+ print(f"--- Using model: {self.model_name} ---")
111
 
112
+ # Step 1: Zero-Shot Attempt
113
  zero_shot_prompt = self.zero_shot_prompt_template.format(question=question)
114
  zero_shot_answer = self._call_gemini_api_with_backoff(zero_shot_prompt).strip()
115
+ if "AGENT_ERROR" not in zero_shot_answer and "UNSURE" not in zero_shot_answer.upper():
 
 
 
116
  print(f"Zero-shot successful! Answer: {zero_shot_answer}")
117
  return zero_shot_answer
118
 
119
+ # Step 2: ReAct Loop
120
+ print("--- Zero-shot failed, starting ReAct loop ---")
 
 
121
  current_prompt_history = self.react_prompt_template.format(question=question, task_id=task_id)
122
 
123
  for i in range(MAX_ITERATIONS):
124
  print(f"\n--- ReAct Iteration {i+1} ---")
 
125
  response_text = self._call_gemini_api_with_backoff(current_prompt_history)
126
  print(f"LLM Response:\n{response_text}")
127
 
 
137
  if action_match:
138
  tool_name = action_match.group(1).strip()
139
  tool_input = action_match.group(2).strip()
 
140
  if tool_name in self.tools:
141
  tool = self.tools[tool_name]
142
  try:
143
  observation = tool.execute(task_id if tool_name == "FileDownloader" else tool_input)
144
+ except Exception as e: observation = f"Error executing tool: {e}"
 
 
145
  current_prompt_history += f"\n{response_text}\nObservation: {observation}"
146
  else:
147
  current_prompt_history += f"\n{response_text}\nObservation: Error - The tool '{tool_name}' does not exist."
148
  else:
 
149
  return response_text.strip()
 
150
  return "AGENT_ERROR: Agent reached max iterations."
151
 
152
+ # --- Main run_and_submit_all function ---
153
  def run_and_submit_all(profile: gr.OAuthProfile | None):
154
  space_id = os.getenv("SPACE_ID")
155
  if not profile: return "Please Login to Hugging Face with the button.", None
156
  username = f"{profile.username}"
 
157
 
158
+ pplx_key, gemini_key = os.getenv("PPLX_API_KEY"), os.getenv("GEMINI_API_KEY")
 
159
  if not pplx_key or not gemini_key: return "API keys not found in Space secrets.", None
160
 
161
  api_url = DEFAULT_API_URL
 
175
  except Exception as e:
176
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
177
 
178
+ print(f"--- Waiting for 12 seconds before next question... ---")
179
+ time.sleep(12)
180
 
181
  if not answers_payload: return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
182
 
 
195
  except requests.exceptions.RequestException as e:
196
  return f"Submission Failed: {e}", pd.DataFrame(results_log)
197
 
198
+ # --- Gradio Interface (Unchanged) ---
199
  with gr.Blocks() as demo:
200
  gr.Markdown("# GAIA Agent Evaluation Runner")
201
+ gr.Markdown("Equipped with the user-specified **gemini-2.5-pro-preview-06-05** model.")
 
 
 
 
 
 
 
 
202
  gr.LoginButton()
203
  run_button = gr.Button("Run Evaluation & Submit All Answers")
204
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)