GoodLuckChuck commited on
Commit
6765748
·
verified ·
1 Parent(s): fc64cce

serper tool fix

Browse files
Files changed (1) hide show
  1. app.py +47 -41
app.py CHANGED
@@ -174,7 +174,7 @@ print("DEBUG: Utility functions defined.")
174
  # --- Tool Definitions ---
175
  print("DEBUG: Defining GoogleSearchTool.")
176
  class GoogleSearchTool(Tool):
177
- name = "web_search"
178
  description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
179
  inputs = {
180
  "query": {"type": "string", "description": "The search query to execute."},
@@ -186,16 +186,18 @@ class GoogleSearchTool(Tool):
186
  }
187
  }
188
  output_type = "string"
189
- is_async = True
190
 
191
- def __init__(self, session: aiohttp.ClientSession):
 
192
  super().__init__()
193
- self._session = session
194
- print("DEBUG: GoogleSearchTool instance created.")
195
 
 
196
  async def forward(self, query: str, provider: str = "serpapi") -> str:
197
  print(f"DEBUG: GoogleSearchTool.forward called with query: '{query}', provider: '{provider}'")
198
- if provider != "serpapi":
199
  logger.warning(f"GoogleSearchTool called with an unexpected provider: '{provider}'. The system prompt and tool definition instruct the LLM to use 'serpapi'.")
200
  return "Error: Invalid search provider. Only 'serpapi' is supported for the web_search tool as per current agent configuration."
201
 
@@ -209,28 +211,31 @@ class GoogleSearchTool(Tool):
209
  headers = {'X-API-KEY': serper_api_key, 'Content-Type': 'application/json'}
210
  payload = json.dumps({'q': query, 'num': CONFIG.SERPER_API_NUM_RESULTS})
211
 
212
- try:
213
- async with self._session.post(url, headers=headers, data=payload, timeout=aiohttp.ClientTimeout(total=15)) as response:
214
- response.raise_for_status()
215
- data = await response.json()
216
- print(f"DEBUG: GoogleSearchTool.forward received data for query '{query}'.")
217
- return self._format_results(data)
218
- except asyncio.TimeoutError:
219
- logger.error(f"Timeout performing search for '{query}'")
220
- print(f"DEBUG: ERROR - Timeout in GoogleSearchTool for query '{query}'.")
221
- return f"Error: Timeout during web search for '{query}'."
222
- except aiohttp.ClientResponseError as e:
223
- logger.error(f"HTTP Error performing search for '{query}': {e.status} {e.message} - Response: {await e.response.text()[:200]}")
224
- print(f"DEBUG: ERROR - HTTP Error {e.status} in GoogleSearchTool for query '{query}'.")
225
- return f"Error performing search (HTTP {e.status}): {e.message}"
226
- except aiohttp.ClientError as e:
227
- logger.error(f"ClientError performing search for '{query}': {type(e).__name__} - {str(e)}")
228
- print(f"DEBUG: ERROR - ClientError in GoogleSearchTool for query '{query}': {str(e)}.")
229
- return f"Error performing search (client error): {str(e)}"
230
- except Exception as e:
231
- logger.error(f"Unexpected error performing search for '{query}': {type(e).__name__} - {str(e)}", exc_info=True)
232
- print(f"DEBUG: ERROR - Unexpected error in GoogleSearchTool for query '{query}': {str(e)}.")
233
- return f"Error performing search: An unexpected error occurred."
 
 
 
234
 
235
  def _format_results(self, data: Dict[str, Any]) -> str:
236
  results = []
@@ -239,11 +244,11 @@ class GoogleSearchTool(Tool):
239
  title = result.get('title', 'N/A')
240
  snippet = result.get('snippet', 'N/A')
241
  results.append(f"Title: {title}\nSnippet: {snippet}\n---")
242
- if not results and 'knowledgeGraph' in data:
243
  kg = data['knowledgeGraph']
244
  title = kg.get('title', '')
245
  description = kg.get('description', '')
246
- if title or description:
247
  results.append(f"Knowledge Graph: {title}\n{description}\n---")
248
  formatted_output = "\n".join(results) if results else "No relevant search results found."
249
  return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
@@ -251,14 +256,14 @@ class GoogleSearchTool(Tool):
251
  # --- Agent Definition ---
252
  print("DEBUG: Defining QuestionAnsweringAgent.")
253
  class QuestionAnsweringAgent(CodeAgent):
254
- def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
255
  print(f"DEBUG: QuestionAnsweringAgent.__init__ called. http_session: {http_session}, model: {model}")
256
  tools = [
257
- GoogleSearchTool(session=http_session),
258
  ]
259
  print(f"DEBUG: QuestionAnsweringAgent tools: {tools}")
260
-
261
- self.llm_for_fallback = model
262
  if self.llm_for_fallback is None and SMOLAGENTS_LOADED: # Only create if smolagents loaded
263
  print("DEBUG: QuestionAnsweringAgent self.llm_for_fallback is None, creating default OpenAIServerModel.")
264
  openai_api_key = os.environ.get('OPENAI_API_KEY')
@@ -277,18 +282,19 @@ class QuestionAnsweringAgent(CodeAgent):
277
 
278
 
279
  minimal_super_args = {
280
- "model": self.llm_for_fallback,
281
  "tools": tools,
282
  "max_steps": CONFIG.AGENT_MAX_STEPS,
283
  }
 
284
  print(f"DEBUG: QuestionAnsweringAgent minimal_super_args for super().__init__: {minimal_super_args}")
285
  try:
286
  super().__init__(**minimal_super_args)
287
  print("DEBUG: QuestionAnsweringAgent super().__init__ successful (workaround active).")
288
 
289
- self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT
290
  print(f"DEBUG: QuestionAnsweringAgent explicitly set self.system_prompt.")
291
-
292
  if hasattr(self, 'verbosity_level'):
293
  self.verbosity_level = CONFIG.AGENT_VERBOSITY_LEVEL
294
  print(f"DEBUG: QuestionAnsweringAgent set self.verbosity_level to: {self.verbosity_level}")
@@ -297,12 +303,12 @@ class QuestionAnsweringAgent(CodeAgent):
297
  logger.warning("Could not set 'verbosity_level' as an attribute after init. It might be handled internally by CodeAgent.")
298
 
299
  if hasattr(self, 'additional_authorized_imports'):
300
- self.additional_authorized_imports = ["PIL"]
301
  print(f"DEBUG: QuestionAnsweringAgent set self.additional_authorized_imports to: {self.additional_authorized_imports}")
302
  else:
303
  print("DEBUG: WARNING - QuestionAnsweringAgent could not set 'additional_authorized_imports' as an attribute after init.")
304
  logger.warning("Could not set 'additional_authorized_imports' as an attribute after init.")
305
-
306
  if not hasattr(self, 'code_writer') or self.code_writer is None:
307
  print("DEBUG: WARNING - QuestionAnsweringAgent self.code_writer might not be initialized due to the __init__ workaround.")
308
  logger.warning("self.code_writer might not be initialized due to the __init__ workaround. Agent may fail to generate or execute code.")
@@ -315,8 +321,8 @@ class QuestionAnsweringAgent(CodeAgent):
315
  "is incompatible with this workaround or has changed.",
316
  exc_info=True
317
  )
318
- raise
319
- except Exception as e:
320
  print(f"DEBUG: ERROR - QuestionAnsweringAgent Unexpected error during __init__ (possibly from tool validation): {type(e).__name__} - {e}")
321
  logger.error(f"Unexpected error during QuestionAnsweringAgent __init__: {e}", exc_info=True)
322
  raise
 
174
  # --- Tool Definitions ---
175
  print("DEBUG: Defining GoogleSearchTool.")
176
  class GoogleSearchTool(Tool):
177
+ name = "web_search"
178
  description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
179
  inputs = {
180
  "query": {"type": "string", "description": "The search query to execute."},
 
186
  }
187
  }
188
  output_type = "string"
189
+ is_async = True
190
 
191
+ # MODIFIED: __init__ no longer takes a session
192
+ def __init__(self):
193
  super().__init__()
194
+ # self._session = session # REMOVED
195
+ print("DEBUG: GoogleSearchTool instance created (session will be created per-call).")
196
 
197
+ # MODIFIED: forward now creates its own session
198
  async def forward(self, query: str, provider: str = "serpapi") -> str:
199
  print(f"DEBUG: GoogleSearchTool.forward called with query: '{query}', provider: '{provider}'")
200
+ if provider != "serpapi":
201
  logger.warning(f"GoogleSearchTool called with an unexpected provider: '{provider}'. The system prompt and tool definition instruct the LLM to use 'serpapi'.")
202
  return "Error: Invalid search provider. Only 'serpapi' is supported for the web_search tool as per current agent configuration."
203
 
 
211
  headers = {'X-API-KEY': serper_api_key, 'Content-Type': 'application/json'}
212
  payload = json.dumps({'q': query, 'num': CONFIG.SERPER_API_NUM_RESULTS})
213
 
214
+ # MODIFIED: Create and use session locally within the async method
215
+ async with aiohttp.ClientSession() as session:
216
+ try:
217
+ # MODIFIED: Use the local 'session' instead of 'self._session'
218
+ async with session.post(url, headers=headers, data=payload, timeout=aiohttp.ClientTimeout(total=15)) as response:
219
+ response.raise_for_status()
220
+ data = await response.json()
221
+ print(f"DEBUG: GoogleSearchTool.forward received data for query '{query}'.")
222
+ return self._format_results(data)
223
+ except asyncio.TimeoutError:
224
+ logger.error(f"Timeout performing search for '{query}'")
225
+ print(f"DEBUG: ERROR - Timeout in GoogleSearchTool for query '{query}'.")
226
+ return f"Error: Timeout during web search for '{query}'."
227
+ except aiohttp.ClientResponseError as e:
228
+ logger.error(f"HTTP Error performing search for '{query}': {e.status} {e.message} - Response: {await e.response.text()[:200]}")
229
+ print(f"DEBUG: ERROR - HTTP Error {e.status} in GoogleSearchTool for query '{query}'.")
230
+ return f"Error performing search (HTTP {e.status}): {e.message}"
231
+ except aiohttp.ClientError as e:
232
+ logger.error(f"ClientError performing search for '{query}': {type(e).__name__} - {str(e)}")
233
+ print(f"DEBUG: ERROR - ClientError in GoogleSearchTool for query '{query}': {str(e)}.")
234
+ return f"Error performing search (client error): {str(e)}"
235
+ except Exception as e:
236
+ logger.error(f"Unexpected error performing search for '{query}': {type(e).__name__} - {str(e)}", exc_info=True)
237
+ print(f"DEBUG: ERROR - Unexpected error in GoogleSearchTool for query '{query}': {str(e)}.")
238
+ return f"Error performing search: An unexpected error occurred."
239
 
240
  def _format_results(self, data: Dict[str, Any]) -> str:
241
  results = []
 
244
  title = result.get('title', 'N/A')
245
  snippet = result.get('snippet', 'N/A')
246
  results.append(f"Title: {title}\nSnippet: {snippet}\n---")
247
+ if not results and 'knowledgeGraph' in data:
248
  kg = data['knowledgeGraph']
249
  title = kg.get('title', '')
250
  description = kg.get('description', '')
251
+ if title or description:
252
  results.append(f"Knowledge Graph: {title}\n{description}\n---")
253
  formatted_output = "\n".join(results) if results else "No relevant search results found."
254
  return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
 
256
  # --- Agent Definition ---
257
  print("DEBUG: Defining QuestionAnsweringAgent.")
258
  class QuestionAnsweringAgent(CodeAgent):
259
+ def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None): # http_session is still accepted but won't be used by GoogleSearchTool
260
  print(f"DEBUG: QuestionAnsweringAgent.__init__ called. http_session: {http_session}, model: {model}")
261
  tools = [
262
+ GoogleSearchTool(), # MODIFIED: Instantiate without session
263
  ]
264
  print(f"DEBUG: QuestionAnsweringAgent tools: {tools}")
265
+
266
+ self.llm_for_fallback = model
267
  if self.llm_for_fallback is None and SMOLAGENTS_LOADED: # Only create if smolagents loaded
268
  print("DEBUG: QuestionAnsweringAgent self.llm_for_fallback is None, creating default OpenAIServerModel.")
269
  openai_api_key = os.environ.get('OPENAI_API_KEY')
 
282
 
283
 
284
  minimal_super_args = {
285
+ "model": self.llm_for_fallback,
286
  "tools": tools,
287
  "max_steps": CONFIG.AGENT_MAX_STEPS,
288
  }
289
+ # ... (rest of the __init__ method remains the same)
290
  print(f"DEBUG: QuestionAnsweringAgent minimal_super_args for super().__init__: {minimal_super_args}")
291
  try:
292
  super().__init__(**minimal_super_args)
293
  print("DEBUG: QuestionAnsweringAgent super().__init__ successful (workaround active).")
294
 
295
+ self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT
296
  print(f"DEBUG: QuestionAnsweringAgent explicitly set self.system_prompt.")
297
+
298
  if hasattr(self, 'verbosity_level'):
299
  self.verbosity_level = CONFIG.AGENT_VERBOSITY_LEVEL
300
  print(f"DEBUG: QuestionAnsweringAgent set self.verbosity_level to: {self.verbosity_level}")
 
303
  logger.warning("Could not set 'verbosity_level' as an attribute after init. It might be handled internally by CodeAgent.")
304
 
305
  if hasattr(self, 'additional_authorized_imports'):
306
+ self.additional_authorized_imports = ["PIL"]
307
  print(f"DEBUG: QuestionAnsweringAgent set self.additional_authorized_imports to: {self.additional_authorized_imports}")
308
  else:
309
  print("DEBUG: WARNING - QuestionAnsweringAgent could not set 'additional_authorized_imports' as an attribute after init.")
310
  logger.warning("Could not set 'additional_authorized_imports' as an attribute after init.")
311
+
312
  if not hasattr(self, 'code_writer') or self.code_writer is None:
313
  print("DEBUG: WARNING - QuestionAnsweringAgent self.code_writer might not be initialized due to the __init__ workaround.")
314
  logger.warning("self.code_writer might not be initialized due to the __init__ workaround. Agent may fail to generate or execute code.")
 
321
  "is incompatible with this workaround or has changed.",
322
  exc_info=True
323
  )
324
+ raise
325
+ except Exception as e:
326
  print(f"DEBUG: ERROR - QuestionAnsweringAgent Unexpected error during __init__ (possibly from tool validation): {type(e).__name__} - {e}")
327
  logger.error(f"Unexpected error during QuestionAnsweringAgent __init__: {e}", exc_info=True)
328
  raise