GoodLuckChuck commited on
Commit
fef1188
·
verified ·
1 Parent(s): d902a13

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -50
app.py CHANGED
@@ -55,13 +55,13 @@ except ImportError as e: # Catch the specific error for better logging
55
  async def generate_reply(self, messages, **kwargs): # Add dummy async method
56
  print("DEBUG: Dummy OpenAIServerModel generate_reply called.")
57
  # Return a dummy AgentMessage-like object
58
- class DummyAgentMessage:
59
- text = "Error: smolagents.OpenAIServerModel not loaded."
60
- return DummyAgentMessage()
61
 
62
  pass
63
 
64
- class AgentMessage: # Dummy for when smolagents fails to import
65
  def __init__(self, role: str, text: str):
66
  self.role = role
67
  self.text = text
@@ -77,12 +77,12 @@ class AppConfig:
77
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
78
  QUESTIONS_URL_PATH = "/questions"
79
  SUBMIT_URL_PATH = "/submit"
80
- SCREENSHOTS_DIR = "screenshots" # Currently not used, but kept for consistency
81
  OPENAI_MODEL_ID = "gpt-4o"
82
  SERPER_API_NUM_RESULTS = 3
83
  WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
84
  AGENT_MAX_STEPS = 10
85
- AGENT_VERBOSITY_LEVEL = 2 # 0: silent, 1: info, 2: debug
86
 
87
  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.
88
  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.
@@ -108,7 +108,7 @@ Follow this process for every question:
108
  6. If you have the information, formulate the final answer according to the formatting rules.
109
 
110
  CRITICAL FINAL ANSWER INSTRUCTIONS:
111
- Your *entire response text*, after all thoughts and tool use, MUST CULMINATE in the final answer.
112
  This final answer MUST be on its own new line and MUST start with the exact literal string "FINAL ANSWER: " (note the space after the colon).
113
  Only the answer value itself should follow this "FINAL ANSWER: " prefix. Do NOT include any of your thought process, conversational text, or additional explanations *after* this "FINAL ANSWER: " prefix and its value. Your response effectively stops there.
114
 
@@ -133,15 +133,15 @@ Formatting rules for the value that comes *after* "FINAL ANSWER: ":
133
  - 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., `FINAL ANSWER: item one,item two,three`). NO space after the comma unless it's part of the item itself.
134
  - If the answer is a calculation result, provide just the number (e.g., `FINAL ANSWER: 10`).
135
 
136
- Remember, the "FINAL ANSWER: " prefix is a literal string you must output as the very last part of your response, followed by the actual answer value. Do not confuse this with any internal `final_answer()` function you might use in your generated code; this is about the final textual output of your entire turn.
137
  """
138
 
139
  SUMMARIZER_SYSTEM_PROMPT = """You are an expert at extracting concise answers from text.
140
  Given an original question and a detailed reasoning process that attempted to answer it, your task is to provide a very short, direct answer to the original question.
141
- This concise answer MUST strictly adhere to the provided formatting rules.
142
- Do NOT include "FINAL ANSWER:" or any other prefix in your response. Just output the value.
143
  Do NOT explain your reasoning for the concise answer. Only provide the answer value.
144
- If the reasoning provided does not contain a clear answer to the original question, output the phrase "Could not determine answer from reasoning."
145
  """
146
 
147
  CONFIG = AppConfig()
@@ -169,7 +169,6 @@ def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
169
  agent_code_url = f"https://huggingface.co/spaces/{space_id}/tree/main"
170
  else:
171
  agent_code_url = "Agent code URL not found (SPACE_ID not set)"
172
- # print(f"DEBUG: get_space_id_agent_code_url() -> space_id: {space_id}, url: {agent_code_url}")
173
  return space_id, agent_code_url
174
 
175
  print("DEBUG: Utility functions defined.")
@@ -261,22 +260,22 @@ class QuestionAnsweringAgent(CodeAgent):
261
  ]
262
  print(f"DEBUG: QuestionAnsweringAgent tools: {tools}")
263
 
264
- effective_model = model
265
- if effective_model is None:
266
  print("DEBUG: QuestionAnsweringAgent effective_model is None, creating default OpenAIServerModel.")
267
  openai_api_key = os.environ.get('OPENAI_API_KEY')
268
  if not openai_api_key:
269
  print("DEBUG: ERROR - OPENAI_API_KEY not found for QuestionAnsweringAgent.")
270
  logger.critical("OPENAI_API_KEY not found. Cannot initialize OpenAIServerModel.")
271
  raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
272
- effective_model = OpenAIServerModel(
273
  model_id=CONFIG.OPENAI_MODEL_ID,
274
  api_key=openai_api_key
275
  )
276
  print(f"DEBUG: QuestionAnsweringAgent default OpenAIServerModel created with model_id: {CONFIG.OPENAI_MODEL_ID}")
277
 
278
  minimal_super_args = {
279
- "model": effective_model,
280
  "tools": tools,
281
  "max_steps": CONFIG.AGENT_MAX_STEPS,
282
  }
@@ -285,7 +284,7 @@ class QuestionAnsweringAgent(CodeAgent):
285
  super().__init__(**minimal_super_args)
286
  print("DEBUG: QuestionAnsweringAgent super().__init__ successful (workaround active).")
287
 
288
- self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT # This is the main system prompt for the agent's reasoning
289
  print(f"DEBUG: QuestionAnsweringAgent explicitly set self.system_prompt.")
290
 
291
  if hasattr(self, 'verbosity_level'):
@@ -351,33 +350,40 @@ class QuestionAnsweringAgent(CodeAgent):
351
  logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Attempting LLM summarization fallback.")
352
  print("DEBUG: WARNING - QuestionAnsweringAgent could not find 'FINAL ANSWER:' in agent's response. Initiating LLM summarization fallback.")
353
 
354
- # Fallback: Ask the LLM to summarize the full_agent_response into a concise answer
355
- summarizer_messages = [
356
- AgentMessage(role="system", text=CONFIG.SUMMARIZER_SYSTEM_PROMPT),
357
- AgentMessage(role="user", text=f"Original Question: {question_text}\n\nAgent's Reasoning and Full Response:\n{full_agent_response}\n\nBased on the reasoning, provide a concise answer to the original question, strictly following the formatting rules mentioned in the system prompt for this summarization task. Your response should be ONLY the answer value.")
358
- ]
359
- print(f"DEBUG: Summarizer LLM call with messages: {summarizer_messages}")
360
- try:
361
- # Assuming self.model is the initialized OpenAIServerModel instance
362
- # and it has an async generate_reply method
363
- summary_response_obj = await self.model.generate_reply(messages=summarizer_messages)
364
- if summary_response_obj and summary_response_obj.text:
365
- final_answer_for_submission = summary_response_obj.text.strip()
366
- print(f"DEBUG: LLM summarization fallback successful. Concise answer: '{final_answer_for_submission}'")
367
- logger.info(f"LLM summarization fallback used. Extracted concise answer: '{final_answer_for_submission}'")
368
- else:
369
- print("DEBUG: ERROR - LLM summarization fallback returned empty or invalid response. Using full response as ultimate fallback.")
370
- logger.error("LLM summarization fallback returned empty. Using full response as ultimate fallback.")
371
- final_answer_for_submission = full_agent_response.strip() # Ultimate fallback
372
- except Exception as e_summary:
373
- print(f"DEBUG: ERROR - Exception during LLM summarization fallback: {type(e_summary).__name__} - {str(e_summary)}. Using full response as ultimate fallback.")
374
- logger.error(f"Exception during LLM summarization fallback: {e_summary}. Using full response as ultimate fallback.", exc_info=True)
375
- final_answer_for_submission = full_agent_response.strip() # Ultimate fallback
376
-
 
 
 
 
 
 
 
377
 
378
  if not final_answer_for_submission:
379
- logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
380
- print("DEBUG: WARNING - QuestionAnsweringAgent extracted final answer is empty.")
381
  final_answer_for_submission = "Could not determine answer."
382
 
383
  except TypeError as te:
@@ -408,20 +414,18 @@ class ChuckAgent:
408
  print("DEBUG: ChuckAgent environment variables checked.")
409
 
410
  try:
411
- # Try to get the currently running event loop (e.g., from Gradio/Uvicorn)
412
  self.loop = asyncio.get_running_loop()
413
  print(f"DEBUG: ChuckAgent obtained running event loop: {self.loop}")
414
- except RuntimeError: # No current event loop.
415
- # This case should be less common if Gradio is running, but as a fallback:
416
  print("DEBUG: ChuckAgent - No current running event loop, creating a new one for this thread.")
417
  self.loop = asyncio.new_event_loop()
418
- asyncio.set_event_loop(self.loop) # Set it for the current OS thread.
419
 
420
  print(f"DEBUG: ChuckAgent using event loop: {self.loop}")
421
 
422
  if self.loop.is_running():
423
  self.http_session = asyncio.run_coroutine_threadsafe(self._get_or_create_session(), self.loop).result(timeout=10)
424
- else: # If loop isn't running (e.g. new_event_loop that wasn't started), run it to create session
425
  self.http_session = self.loop.run_until_complete(self._get_or_create_session())
426
 
427
  print(f"DEBUG: ChuckAgent http_session created: {self.http_session}")
@@ -441,7 +445,7 @@ class ChuckAgent:
441
  print("DEBUG: ChuckAgent - self.agent_instance is None. Initializing QuestionAnsweringAgent...")
442
  logger.info("Initializing QuestionAnsweringAgent within ChuckAgent...")
443
  try:
444
- self.agent_instance = QuestionAnsweringAgent(http_session=self.http_session)
445
  print("DEBUG: ChuckAgent - QuestionAnsweringAgent initialized successfully.")
446
  logger.info("QuestionAnsweringAgent initialized successfully.")
447
  except Exception as e:
@@ -467,7 +471,7 @@ class ChuckAgent:
467
  else:
468
  future = asyncio.run_coroutine_threadsafe(self.agent_instance.process_question(question), self.loop)
469
  print(f"DEBUG: ChuckAgent waiting for future.result() for question: '{question[:50]}...'")
470
- final_answer, reasoning_trace = future.result(timeout=180) # Increased timeout
471
 
472
  print(f"DEBUG: ChuckAgent future.result() obtained for question: '{question[:50]}...'. Answer: '{final_answer[:50]}...'")
473
  logger.info(f"ChuckAgent returning answer (first 50 chars): '{final_answer[:50]}...'")
@@ -546,7 +550,6 @@ def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]
546
  payload_item["reasoning_trace"] = reasoning
547
  answers_payload.append(payload_item)
548
 
549
- # For local logging, you can keep 'Submitted Answer' or change it if you prefer
550
  results_log_data.append({
551
  "Task ID": task_id, "Question": question_text,
552
  "Submitted Answer": model_ans,
 
55
  async def generate_reply(self, messages, **kwargs): # Add dummy async method
56
  print("DEBUG: Dummy OpenAIServerModel generate_reply called.")
57
  # Return a dummy AgentMessage-like object
58
+ class DummyAgentMessageResponse: # Renamed to avoid conflict if AgentMessage itself is dummied
59
+ text = "Error: smolagents.OpenAIServerModel not loaded or dummy generate_reply called."
60
+ return DummyAgentMessageResponse()
61
 
62
  pass
63
 
64
+ class AgentMessage: # Dummy for when smolagents fails to import AgentMessage specifically
65
  def __init__(self, role: str, text: str):
66
  self.role = role
67
  self.text = text
 
77
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
78
  QUESTIONS_URL_PATH = "/questions"
79
  SUBMIT_URL_PATH = "/submit"
80
+ SCREENSHOTS_DIR = "screenshots"
81
  OPENAI_MODEL_ID = "gpt-4o"
82
  SERPER_API_NUM_RESULTS = 3
83
  WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
84
  AGENT_MAX_STEPS = 10
85
+ AGENT_VERBOSITY_LEVEL = 2
86
 
87
  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.
88
  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.
 
108
  6. If you have the information, formulate the final answer according to the formatting rules.
109
 
110
  CRITICAL FINAL ANSWER INSTRUCTIONS:
111
+ Your *entire textual response* for this turn, after all thoughts and tool use, MUST CULMINATE in the final answer.
112
  This final answer MUST be on its own new line and MUST start with the exact literal string "FINAL ANSWER: " (note the space after the colon).
113
  Only the answer value itself should follow this "FINAL ANSWER: " prefix. Do NOT include any of your thought process, conversational text, or additional explanations *after* this "FINAL ANSWER: " prefix and its value. Your response effectively stops there.
114
 
 
133
  - 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., `FINAL ANSWER: item one,item two,three`). NO space after the comma unless it's part of the item itself.
134
  - If the answer is a calculation result, provide just the number (e.g., `FINAL ANSWER: 10`).
135
 
136
+ Remember, the "FINAL ANSWER: " prefix is a literal string you must output as the very last part of your response, followed by the actual answer value. Do not confuse this with any internal `final_answer()` Python function you might generate in your CODE block; this instruction is about the final textual output of your entire turn.
137
  """
138
 
139
  SUMMARIZER_SYSTEM_PROMPT = """You are an expert at extracting concise answers from text.
140
  Given an original question and a detailed reasoning process that attempted to answer it, your task is to provide a very short, direct answer to the original question.
141
+ This concise answer MUST strictly adhere to the provided formatting rules for numbers, strings, or comma-separated lists, as applicable to the question.
142
+ Do NOT include "FINAL ANSWER:" or any other prefix in your response. Just output the answer value.
143
  Do NOT explain your reasoning for the concise answer. Only provide the answer value.
144
+ If the reasoning provided does not contain a clear answer to the original question, output the exact phrase "Could not determine answer from reasoning."
145
  """
146
 
147
  CONFIG = AppConfig()
 
169
  agent_code_url = f"https://huggingface.co/spaces/{space_id}/tree/main"
170
  else:
171
  agent_code_url = "Agent code URL not found (SPACE_ID not set)"
 
172
  return space_id, agent_code_url
173
 
174
  print("DEBUG: Utility functions defined.")
 
260
  ]
261
  print(f"DEBUG: QuestionAnsweringAgent tools: {tools}")
262
 
263
+ self.llm_for_fallback = model # Store the model instance for fallback
264
+ if self.llm_for_fallback is None:
265
  print("DEBUG: QuestionAnsweringAgent effective_model is None, creating default OpenAIServerModel.")
266
  openai_api_key = os.environ.get('OPENAI_API_KEY')
267
  if not openai_api_key:
268
  print("DEBUG: ERROR - OPENAI_API_KEY not found for QuestionAnsweringAgent.")
269
  logger.critical("OPENAI_API_KEY not found. Cannot initialize OpenAIServerModel.")
270
  raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
271
+ self.llm_for_fallback = OpenAIServerModel(
272
  model_id=CONFIG.OPENAI_MODEL_ID,
273
  api_key=openai_api_key
274
  )
275
  print(f"DEBUG: QuestionAnsweringAgent default OpenAIServerModel created with model_id: {CONFIG.OPENAI_MODEL_ID}")
276
 
277
  minimal_super_args = {
278
+ "model": self.llm_for_fallback, # Pass the model to the parent class
279
  "tools": tools,
280
  "max_steps": CONFIG.AGENT_MAX_STEPS,
281
  }
 
284
  super().__init__(**minimal_super_args)
285
  print("DEBUG: QuestionAnsweringAgent super().__init__ successful (workaround active).")
286
 
287
+ self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT
288
  print(f"DEBUG: QuestionAnsweringAgent explicitly set self.system_prompt.")
289
 
290
  if hasattr(self, 'verbosity_level'):
 
350
  logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Attempting LLM summarization fallback.")
351
  print("DEBUG: WARNING - QuestionAnsweringAgent could not find 'FINAL ANSWER:' in agent's response. Initiating LLM summarization fallback.")
352
 
353
+ if not self.llm_for_fallback: # Should have been initialized in __init__
354
+ print("DEBUG: ERROR - self.llm_for_fallback not initialized. Using full response as ultimate fallback.")
355
+ logger.error("self.llm_for_fallback not initialized. Using full response as ultimate fallback.")
356
+ final_answer_for_submission = full_agent_response.strip()
357
+ else:
358
+ summarizer_messages = [
359
+ AgentMessage(role="system", text=CONFIG.SUMMARIZER_SYSTEM_PROMPT),
360
+ AgentMessage(role="user", text=f"Original Question: {question_text}\n\nAgent's Reasoning and Full Response (which failed to use the 'FINAL ANSWER:' prefix correctly):\n{full_agent_response}\n\nBased on the reasoning provided in the 'Agent's Reasoning and Full Response', extract or formulate a concise, direct answer to the 'Original Question'. Your response should be ONLY the answer value itself, adhering strictly to the formatting rules mentioned in the system prompt for this summarization task. Do not add any prefix like 'FINAL ANSWER:'. If a clear answer cannot be determined from the reasoning, output the exact phrase 'Could not determine answer from reasoning.'")
361
+ ]
362
+ print(f"DEBUG: Summarizer LLM call with messages (first message content shown): {summarizer_messages[0].text[:100]}...") # Log snippet
363
+ try:
364
+ summary_response_obj = await self.llm_for_fallback.generate_reply(messages=summarizer_messages)
365
+ if summary_response_obj and summary_response_obj.text:
366
+ concise_answer = summary_response_obj.text.strip()
367
+ if "Could not determine answer from reasoning." in concise_answer:
368
+ print(f"DEBUG: LLM summarization fallback indicated no clear answer. Using placeholder.")
369
+ logger.warning("LLM summarization fallback indicated no clear answer. Using placeholder.")
370
+ final_answer_for_submission = "Could not determine answer."
371
+ else:
372
+ final_answer_for_submission = concise_answer
373
+ print(f"DEBUG: LLM summarization fallback successful. Concise answer: '{final_answer_for_submission}'")
374
+ logger.info(f"LLM summarization fallback used. Extracted concise answer: '{final_answer_for_submission}'")
375
+ else:
376
+ print("DEBUG: ERROR - LLM summarization fallback returned empty or invalid response. Using full response as ultimate fallback.")
377
+ logger.error("LLM summarization fallback returned empty. Using full response as ultimate fallback.")
378
+ final_answer_for_submission = full_agent_response.strip()
379
+ except Exception as e_summary:
380
+ print(f"DEBUG: ERROR - Exception during LLM summarization fallback: {type(e_summary).__name__} - {str(e_summary)}. Using full response as ultimate fallback.")
381
+ logger.error(f"Exception during LLM summarization fallback: {e_summary}. Using full response as ultimate fallback.", exc_info=True)
382
+ final_answer_for_submission = full_agent_response.strip()
383
 
384
  if not final_answer_for_submission:
385
+ logger.warning("Extracted final answer is empty after all fallbacks. Defaulting to a placeholder.")
386
+ print("DEBUG: WARNING - QuestionAnsweringAgent extracted final answer is empty after all fallbacks.")
387
  final_answer_for_submission = "Could not determine answer."
388
 
389
  except TypeError as te:
 
414
  print("DEBUG: ChuckAgent environment variables checked.")
415
 
416
  try:
 
417
  self.loop = asyncio.get_running_loop()
418
  print(f"DEBUG: ChuckAgent obtained running event loop: {self.loop}")
419
+ except RuntimeError:
 
420
  print("DEBUG: ChuckAgent - No current running event loop, creating a new one for this thread.")
421
  self.loop = asyncio.new_event_loop()
422
+ asyncio.set_event_loop(self.loop)
423
 
424
  print(f"DEBUG: ChuckAgent using event loop: {self.loop}")
425
 
426
  if self.loop.is_running():
427
  self.http_session = asyncio.run_coroutine_threadsafe(self._get_or_create_session(), self.loop).result(timeout=10)
428
+ else:
429
  self.http_session = self.loop.run_until_complete(self._get_or_create_session())
430
 
431
  print(f"DEBUG: ChuckAgent http_session created: {self.http_session}")
 
445
  print("DEBUG: ChuckAgent - self.agent_instance is None. Initializing QuestionAnsweringAgent...")
446
  logger.info("Initializing QuestionAnsweringAgent within ChuckAgent...")
447
  try:
448
+ self.agent_instance = QuestionAnsweringAgent(http_session=self.http_session) # Model will be created inside if None
449
  print("DEBUG: ChuckAgent - QuestionAnsweringAgent initialized successfully.")
450
  logger.info("QuestionAnsweringAgent initialized successfully.")
451
  except Exception as e:
 
471
  else:
472
  future = asyncio.run_coroutine_threadsafe(self.agent_instance.process_question(question), self.loop)
473
  print(f"DEBUG: ChuckAgent waiting for future.result() for question: '{question[:50]}...'")
474
+ final_answer, reasoning_trace = future.result(timeout=180)
475
 
476
  print(f"DEBUG: ChuckAgent future.result() obtained for question: '{question[:50]}...'. Answer: '{final_answer[:50]}...'")
477
  logger.info(f"ChuckAgent returning answer (first 50 chars): '{final_answer[:50]}...'")
 
550
  payload_item["reasoning_trace"] = reasoning
551
  answers_payload.append(payload_item)
552
 
 
553
  results_log_data.append({
554
  "Task ID": task_id, "Question": question_text,
555
  "Submitted Answer": model_ans,