GoodLuckChuck commited on
Commit
be5f4f9
·
verified ·
1 Parent(s): 7253326

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -102
app.py CHANGED
@@ -6,7 +6,6 @@ import asyncio
6
  import re
7
  import json
8
  import logging
9
- import operator # Used by CalculatorTool
10
  import aiohttp
11
  from typing import Optional, Dict, Any, List, Tuple
12
 
@@ -38,34 +37,29 @@ class AppConfig:
38
  SERPER_API_NUM_RESULTS = 3
39
  WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
40
  AGENT_MAX_STEPS = 10
41
- AGENT_VERBOSITY_LEVEL = 2 # Will attempt to set this via workaround
42
 
43
  AGENT_SYSTEM_PROMPT = """You are a highly intelligent and meticulous AI assistant. Your primary goal is to answer the user's question accurately and concisely.
44
  You have access to a specific set of Python tools. You MUST use these exact function names as provided when you decide to use a tool.
45
  When you generate Python code to call a tool, you MUST print the result of the tool call so it can be observed.
46
 
47
  Available Tools:
48
- 1. `web_search(query: str) -> str`: Use this tool to search the internet for current information or information you do not possess. This tool is asynchronous, so your generated code MUST call it using `await`. Example: `search_results = await web_search(query="latest news on AI")\nprint(search_results)`
49
- 2. `calculator(expression: str) -> str`: Use this tool for any mathematical calculations. This tool is synchronous. Example: `result = calculator(expression="((1024 / 8) + 55 - 5) * 2")\nprint(result)`
50
- 3. `image_retriever(url: str) -> str`: Use this tool to retrieve an image from a web URL. Input: a string URL. Output: a status message.
51
-
52
  Follow this process for every question:
53
  1. THOUGHT: Understand the user's question. Identify the core information needed.
54
- 2. THOUGHT: Decide if one of your available tools (`web_search`, `calculator`, `image_retriever`) can help obtain this information. If yes, state which tool you will use and what input you will provide to it. If no tool is needed, explain that you can answer directly.
55
  3. CODE (if using a tool):
56
  ```python
57
- # Your Python code to call ONE tool.
58
- # REMEMBER: Use `await` for `web_search` and `image_retriever`.
59
  # ALWAYS print the result of the tool call.
60
- # Example for web_search:
61
- # search_result = await web_search(query="some specific query")
62
  # print(search_result)
63
- # Example for calculator:
64
- # calc_result = calculator(expression="1+1")
65
- # print(calc_result)
66
  ```<end_code>
67
  4. OBSERVATION: [The system will insert the printed output of your tool call here.]
68
- 5. THOUGHT: Analyze the observation. Is it what you expected? Do you have enough information to answer the user's question now? If not, what is your next step? (e.g., use another tool, refine a previous tool call, or formulate the answer). If you need to use another tool, go back to step 2.
69
  6. If you have the information, formulate the final answer according to the formatting rules.
70
 
71
  CRITICAL: Your *entire response* to the user for each turn must culminate in the final answer using this exact template on a new line:
@@ -74,7 +68,7 @@ FINAL ANSWER: [Your concise answer, strictly following the formatting rules belo
74
  Formatting rules for the value in FINAL ANSWER:
75
  - If the question asks for a number: Provide only the number itself (e.g., 42). Do not use commas for thousands separation (e.g., use 1234 not 1,234). Do not include units like '$' or '%' unless the question specifically asks for it and it's part of the answer.
76
  - If the question asks for a string: Provide the most concise string possible. Avoid articles (a, an, the) unless grammatically essential. Avoid common abbreviations (e.g., for cities like \"NYC\" for \"New York City\") unless the question implies it. Write out numerical digits as words (e.g., \"two\" instead of 2) unless numerical digits are requested.
77
- - If the question asks for a comma-separated list: Apply the above string/number rules to each element. Ensure elements are separated ONLY by a comma (e.g., item one,item two,three). NO space after the comma unless it\'s part of the item itself.
78
  - If the answer is a calculation result, provide just the number.
79
  """
80
 
@@ -110,45 +104,11 @@ async def close_shared_http_session():
110
  logger.info("Closed shared aiohttp.ClientSession.")
111
 
112
  # --- Tool Definitions ---
113
- class ImageRetrievalTool(Tool):
114
- name = "image_retriever"
115
- description = "Retrieves an image from a web URL. Input: a string URL. Output: a status message."
116
- inputs = {"url": {"type": "string", "description": "The direct URL of the image to retrieve."}}
117
- output_type = "string"
118
- is_async = True
119
-
120
- def __init__(self, session: aiohttp.ClientSession):
121
- super().__init__()
122
- self.image_memory: Dict[str, Dict[str, Any]] = {}
123
- self.screenshot_count = 0
124
- self._session = session
125
-
126
- async def forward(self, url: str) -> str:
127
- logger.info(f"ImageRetrievalTool called with URL: {url}")
128
- try:
129
- async with self._session.get(url, timeout=aiohttp.ClientTimeout(total=20)) as response:
130
- response.raise_for_status()
131
- image_data = await response.read()
132
- image_id = f"image_{self.screenshot_count}"
133
- self.image_memory[image_id] = {
134
- 'data': image_data, 'url': url, 'timestamp': datetime.now().isoformat()
135
- }
136
- self.screenshot_count += 1
137
- return f"Image retrieved successfully from {url}. Stored in memory as {image_id}."
138
- except asyncio.TimeoutError:
139
- logger.error(f"Timeout retrieving image {url}")
140
- return f"Error: Timeout retrieving image {url}."
141
- except aiohttp.ClientError as e:
142
- logger.error(f"ClientError retrieving image {url}: {type(e).__name__} - {str(e)}")
143
- return f"Error retrieving image (client error): {str(e)}"
144
- except Exception as e:
145
- logger.error(f"Unexpected error retrieving image {url}: {type(e).__name__} - {str(e)}")
146
- return f"Error retrieving image: {str(e)}"
147
-
148
- class WebSearchTool(Tool):
149
- name = "web_search"
150
  description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
151
- inputs = {"query": {"type": "string", "description": "The search query to execute."}}
 
152
  output_type = "string"
153
  is_async = True
154
 
@@ -156,8 +116,11 @@ class WebSearchTool(Tool):
156
  super().__init__()
157
  self._session = session
158
 
159
- async def forward(self, query: str) -> str:
160
- logger.info(f"WebSearchTool called with query: {query}")
 
 
 
161
  serper_api_key = os.environ.get('SERPER_API_KEY')
162
  if not serper_api_key:
163
  logger.error("SERPER_API_KEY not found.")
@@ -198,41 +161,12 @@ class WebSearchTool(Tool):
198
  formatted_output = "\n".join(results) if results else "No relevant search results found."
199
  return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
200
 
201
- class CalculatorTool(Tool):
202
- name = "calculator"
203
- description = "Performs mathematical calculations. Input: a string mathematical expression. Output: calculation result string."
204
- inputs = {"expression": {"type": "string", "description": "The mathematical expression to evaluate (e.g., '2+2*5')."}}
205
- output_type = "string"
206
- is_async = False
207
-
208
- def __init__(self):
209
- super().__init__()
210
- self.operations = {
211
- '+': operator.add, '-': operator.sub,
212
- '*': operator.mul, '/': operator.truediv,
213
- '^': operator.pow
214
- }
215
- self.allowed_chars = "0123456789+-*/^(). "
216
-
217
- async def forward(self, expression: str) -> str:
218
- logger.info(f"CalculatorTool called with expression: {expression}")
219
- try:
220
- safe_expr = "".join(c for c in expression if c in self.allowed_chars)
221
- if not safe_expr:
222
- return "Error: Empty or invalid expression for calculator."
223
- result = eval(safe_expr, {"__builtins__": {}}, self.operations) # type: ignore
224
- return f"Calculation result: {safe_expr} = {float(result)}"
225
- except Exception as e:
226
- logger.error(f"Error evaluating expression '{expression}': {str(e)}")
227
- return f"Error: Could not evaluate expression '{expression}'. Ensure it's a simple arithmetic expression."
228
 
229
  # --- Agent Definition ---
230
  class QuestionAnsweringAgent(CodeAgent):
231
  def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
232
  tools = [
233
- WebSearchTool(session=http_session),
234
- CalculatorTool(),
235
- ImageRetrievalTool(session=http_session)
236
  ]
237
 
238
  effective_model = model
@@ -345,9 +279,6 @@ class QuestionAnsweringAgent(CodeAgent):
345
  return final_answer_for_submission, reasoning_trace
346
 
347
  # --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
348
- GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
349
-
350
-
351
  class ChuckAgent:
352
  def __init__(self):
353
  required_env_vars = ['OPENAI_API_KEY', 'SERPER_API_KEY']
@@ -372,17 +303,13 @@ class ChuckAgent:
372
  def __call__(self, question: str) -> Tuple[str, str]:
373
  logger.info(f"ChuckAgent received question (first 50 chars): {question[:50]}...")
374
  try:
375
- # Ensure we're using the correct event loop (important in Gradio)
376
- try:
377
- loop = asyncio.get_event_loop()
378
- except RuntimeError:
379
- loop = asyncio.new_event_loop()
380
- asyncio.set_event_loop(loop)
381
 
382
  # Schedule the agent's processing within the current event loop
383
  agent_task = asyncio.ensure_future(self.agent.process_question(question),
384
- loop=loop)
385
- final_answer, reasoning_trace = loop.run_until_complete(agent_task)
386
 
387
  logger.info(f"ChuckAgent returning answer (first 50 chars): {final_answer[:50]}...")
388
  return final_answer, reasoning_trace
@@ -499,7 +426,6 @@ def submit_answers(base_api_url: str, username: str, agent_code_url: str,
499
  # --- Gradio Interface Main Function ---
500
  GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
501
 
502
-
503
  def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
504
  global GLOBAL_CHUCK_AGENT
505
  logger.info(f"run_and_submit_all_evaluation received profile: {type(profile)}")
@@ -573,7 +499,7 @@ with gr.Blocks() as demo:
573
  """
574
  )
575
  gr.Markdown(
576
- f"""
577
  ---
578
  **Technical Notes:**
579
  * The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
@@ -596,7 +522,7 @@ with gr.Blocks() as demo:
596
 
597
  # --- Application Startup & Shutdown Handling ---
598
  if __name__ == "__main__":
599
- print("\n" + "-" * 30 + " App Starting " + "-" * 30)
600
  space_host_startup = os.getenv("SPACE_HOST")
601
  space_id_startup, agent_url_startup = get_space_id_agent_code_url()
602
 
@@ -612,5 +538,34 @@ if __name__ == "__main__":
612
  print(f" Agent Code URL reported to server: {agent_url_startup}")
613
  else:
614
  print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
615
-
616
- print(f" Default API URL: {CONFIG.DEFAULT_API_URL}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  import re
7
  import json
8
  import logging
 
9
  import aiohttp
10
  from typing import Optional, Dict, Any, List, Tuple
11
 
 
37
  SERPER_API_NUM_RESULTS = 3
38
  WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
39
  AGENT_MAX_STEPS = 10
40
+ AGENT_VERBOSITY_LEVEL = 2
41
 
42
  AGENT_SYSTEM_PROMPT = """You are a highly intelligent and meticulous AI assistant. Your primary goal is to answer the user's question accurately and concisely.
43
  You have access to a specific set of Python tools. You MUST use these exact function names as provided when you decide to use a tool.
44
  When you generate Python code to call a tool, you MUST print the result of the tool call so it can be observed.
45
 
46
  Available Tools:
47
+ 1. `web_search(query: str, provider: str = "serpapi") -> str`: Use this tool to search the internet for current information or information you do not possess. The 'provider' parameter MUST be set to "serpapi". This tool is asynchronous, so your generated code MUST call it using `await`. Example: `search_results = await web_search(query="latest news on AI", provider="serpapi")\nprint(search_results)`
48
+
 
 
49
  Follow this process for every question:
50
  1. THOUGHT: Understand the user's question. Identify the core information needed.
51
+ 2. THOUGHT: You MUST use the `web_search` tool with `provider="serpapi"` to get information from the internet.
52
  3. CODE (if using a tool):
53
  ```python
54
+ # Your Python code to call the web_search tool.
55
+ # REMEMBER: Use `await` and set provider="serpapi".
56
  # ALWAYS print the result of the tool call.
57
+ # Example:
58
+ # search_result = await web_search(query="some specific query", provider="serpapi")
59
  # print(search_result)
 
 
 
60
  ```<end_code>
61
  4. OBSERVATION: [The system will insert the printed output of your tool call here.]
62
+ 5. THOUGHT: Analyze the observation. Is it what you expected? Do you have enough information to answer the user's question now? If not, refine your search.
63
  6. If you have the information, formulate the final answer according to the formatting rules.
64
 
65
  CRITICAL: Your *entire response* to the user for each turn must culminate in the final answer using this exact template on a new line:
 
68
  Formatting rules for the value in FINAL ANSWER:
69
  - If the question asks for a number: Provide only the number itself (e.g., 42). Do not use commas for thousands separation (e.g., use 1234 not 1,234). Do not include units like '$' or '%' unless the question specifically asks for it and it's part of the answer.
70
  - If the question asks for a string: Provide the most concise string possible. Avoid articles (a, an, the) unless grammatically essential. Avoid common abbreviations (e.g., for cities like \"NYC\" for \"New York City\") unless the question implies it. Write out numerical digits as words (e.g., \"two\" instead of 2) unless numerical digits are requested.
71
+ - If the question asks for a comma-separated list: Apply the above string/number rules to each element. Ensure elements are separated ONLY by a comma (e.g., item one,item two,three). NO space after the comma unless it's part of the item itself.
72
  - If the answer is a calculation result, provide just the number.
73
  """
74
 
 
104
  logger.info("Closed shared aiohttp.ClientSession.")
105
 
106
  # --- Tool Definitions ---
107
+ class GoogleSearchTool(Tool): # Renamed to GoogleSearchTool
108
+ name = "web_search" # Keep the original name for the agent to use
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
110
+ inputs = {"query": {"type": "string", "description": "The search query to execute."},
111
+ "provider": {"type": "string", "description": "The search provider. MUST be 'serpapi'.", "default": "serpapi"}}
112
  output_type = "string"
113
  is_async = True
114
 
 
116
  super().__init__()
117
  self._session = session
118
 
119
+ async def forward(self, query: str, provider: str = "serpapi") -> str: # Added provider
120
+ if provider != "serpapi":
121
+ return "Error: Invalid search provider. Only 'serpapi' is supported."
122
+
123
+ logger.info(f"GoogleSearchTool called with query: {query}, provider: {provider}")
124
  serper_api_key = os.environ.get('SERPER_API_KEY')
125
  if not serper_api_key:
126
  logger.error("SERPER_API_KEY not found.")
 
161
  formatted_output = "\n".join(results) if results else "No relevant search results found."
162
  return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
163
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
 
165
  # --- Agent Definition ---
166
  class QuestionAnsweringAgent(CodeAgent):
167
  def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
168
  tools = [
169
+ GoogleSearchTool(session=http_session), # Using GoogleSearchTool
 
 
170
  ]
171
 
172
  effective_model = model
 
279
  return final_answer_for_submission, reasoning_trace
280
 
281
  # --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
 
 
 
282
  class ChuckAgent:
283
  def __init__(self):
284
  required_env_vars = ['OPENAI_API_KEY', 'SERPER_API_KEY']
 
303
  def __call__(self, question: str) -> Tuple[str, str]:
304
  logger.info(f"ChuckAgent received question (first 50 chars): {question[:50]}...")
305
  try:
306
+ if asyncio.get_event_loop() is not self.loop:
307
+ asyncio.set_event_loop(self.loop)
 
 
 
 
308
 
309
  # Schedule the agent's processing within the current event loop
310
  agent_task = asyncio.ensure_future(self.agent.process_question(question),
311
+ loop=self.loop)
312
+ final_answer, reasoning_trace = self.loop.run_until_complete(agent_task)
313
 
314
  logger.info(f"ChuckAgent returning answer (first 50 chars): {final_answer[:50]}...")
315
  return final_answer, reasoning_trace
 
426
  # --- Gradio Interface Main Function ---
427
  GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
428
 
 
429
  def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
430
  global GLOBAL_CHUCK_AGENT
431
  logger.info(f"run_and_submit_all_evaluation received profile: {type(profile)}")
 
499
  """
500
  )
501
  gr.Markdown(
502
+ f"""
503
  ---
504
  **Technical Notes:**
505
  * The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
 
522
 
523
  # --- Application Startup & Shutdown Handling ---
524
  if __name__ == "__main__":
525
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
526
  space_host_startup = os.getenv("SPACE_HOST")
527
  space_id_startup, agent_url_startup = get_space_id_agent_code_url()
528
 
 
538
  print(f" Agent Code URL reported to server: {agent_url_startup}")
539
  else:
540
  print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
541
+
542
+ print(f" Default API URL: {CONFIG.DEFAULT_API_URL}")
543
+ print(f" OpenAI Model ID: {CONFIG.OPENAI_MODEL_ID}")
544
+ print("-"*(60 + len(" App Starting ")) + "\n")
545
+ print("Launching Gradio Interface for Chuck Agent Evaluation...")
546
+
547
+ try:
548
+ demo.launch(debug=True, share=False)
549
+ finally:
550
+ loop_to_use = None
551
+ if GLOBAL_CHUCK_AGENT and hasattr(GLOBAL_CHUCK_AGENT, 'http_session') and GLOBAL_CHUCK_AGENT.http_session:
552
+ loop_to_use = GLOBAL_CHUCK_AGENT.http_session.loop
553
+ elif SHARED_HTTP_SESSION:
554
+ loop_to_use = SHARED_HTTP_SESSION.loop
555
+
556
+ if loop_to_use and loop_to_use.is_running():
557
+ logger.info("Attempting to shutdown agent and close HTTP session in finally block...")
558
+ try:
559
+ current_loop = asyncio.get_event_loop_policy().get_event_loop() # More robust way to get current loop
560
+ if current_loop is not loop_to_use and not loop_to_use.is_closed():
561
+ asyncio.set_event_loop(loop_to_use)
562
+
563
+ if GLOBAL_CHUCK_AGENT:
564
+ loop_to_use.run_until_complete(GLOBAL_CHUCK_AGENT.shutdown())
565
+ elif SHARED_HTTP_SESSION and not SHARED_HTTP_SESSION.closed:
566
+ loop_to_use.run_until_complete(close_shared_http_session())
567
+ except Exception as e:
568
+ logger.error(f"Error during final cleanup of HTTP session: {e}", exc_info=True)
569
+ else:
570
+ logger.info("No active HTTP session or running loop to close in finally block.")
571
+ }