Update app.py
Browse files
app.py
CHANGED
|
@@ -25,13 +25,13 @@ print("DEBUG: typing imported")
|
|
| 25 |
# Import necessary components from smolagents
|
| 26 |
try:
|
| 27 |
from smolagents import CodeAgent, Tool, OpenAIServerModel
|
| 28 |
-
from smolagents.agent_types import AgentMessage
|
| 29 |
-
print("DEBUG: smolagents components (CodeAgent, Tool, OpenAIServerModel
|
| 30 |
-
|
|
|
|
| 31 |
print(f"DEBUG: Failed to import smolagents. Error: {e}")
|
| 32 |
logging.error(f"Failed to import smolagents. Please ensure it is installed and not corrupted. Error: {e}")
|
| 33 |
-
|
| 34 |
-
# This allows the rest of the script to be parsed, but it won't run correctly.
|
| 35 |
class CodeAgent:
|
| 36 |
def __init__(self, *args, **kwargs):
|
| 37 |
print("DEBUG: Dummy CodeAgent initialized because smolagents failed to import.")
|
|
@@ -52,21 +52,12 @@ except ImportError as e: # Catch the specific error for better logging
|
|
| 52 |
def __init__(self, *args, **kwargs):
|
| 53 |
print("DEBUG: Dummy OpenAIServerModel initialized because smolagents failed to import.")
|
| 54 |
logging.error("Dummy OpenAIServerModel initialized because smolagents failed to import.")
|
| 55 |
-
async def generate_reply(self, messages, **kwargs):
|
| 56 |
print("DEBUG: Dummy OpenAIServerModel generate_reply called.")
|
| 57 |
-
|
| 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
|
| 68 |
-
print(f"DEBUG: Dummy AgentMessage created for role {role}.")
|
| 69 |
-
|
| 70 |
|
| 71 |
from datetime import datetime
|
| 72 |
print("DEBUG: datetime imported")
|
|
@@ -262,7 +253,7 @@ class QuestionAnsweringAgent(CodeAgent):
|
|
| 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
|
| 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.")
|
|
@@ -275,7 +266,7 @@ class QuestionAnsweringAgent(CodeAgent):
|
|
| 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 |
}
|
|
@@ -325,61 +316,68 @@ class QuestionAnsweringAgent(CodeAgent):
|
|
| 325 |
reasoning_trace = "Agent execution started."
|
| 326 |
final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
|
| 327 |
try:
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
print(f"DEBUG: QuestionAnsweringAgent extracted FINAL ANSWER: '{final_answer_for_submission}'")
|
| 349 |
-
else:
|
| 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 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
|
|
|
|
|
|
| 357 |
else:
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 371 |
else:
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
print("DEBUG: ERROR - LLM summarization fallback
|
| 377 |
-
logger.error("LLM summarization 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.")
|
|
@@ -445,7 +443,8 @@ class ChuckAgent:
|
|
| 445 |
print("DEBUG: ChuckAgent - self.agent_instance is None. Initializing QuestionAnsweringAgent...")
|
| 446 |
logger.info("Initializing QuestionAnsweringAgent within ChuckAgent...")
|
| 447 |
try:
|
| 448 |
-
|
|
|
|
| 449 |
print("DEBUG: ChuckAgent - QuestionAnsweringAgent initialized successfully.")
|
| 450 |
logger.info("QuestionAnsweringAgent initialized successfully.")
|
| 451 |
except Exception as e:
|
|
@@ -544,7 +543,6 @@ def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]
|
|
| 544 |
print(f"DEBUG: Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
|
| 545 |
try:
|
| 546 |
model_ans, reasoning = agent(question_text)
|
| 547 |
-
# Use 'submitted_answer' as the key for the server payload
|
| 548 |
payload_item = {"task_id": task_id, "submitted_answer": model_ans}
|
| 549 |
if reasoning:
|
| 550 |
payload_item["reasoning_trace"] = reasoning
|
|
@@ -559,7 +557,6 @@ def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]
|
|
| 559 |
print(f"DEBUG: ERROR - Error running agent on task {task_id}: {e}")
|
| 560 |
logger.error(f"Error running agent on task {task_id} ('{question_text[:50]}...'): {e}", exc_info=True)
|
| 561 |
error_answer = f"AGENT_CALL_ERROR: {str(e)}"
|
| 562 |
-
# Use 'submitted_answer' as the key for the server payload in error cases too
|
| 563 |
answers_payload.append({"task_id": task_id, "submitted_answer": error_answer, "reasoning_trace": str(e)})
|
| 564 |
results_log_data.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": error_answer, "Reasoning Trace": str(e)})
|
| 565 |
print(f"DEBUG: process_all_questions finished. Produced {len(answers_payload)} answers.")
|
|
|
|
| 25 |
# Import necessary components from smolagents
|
| 26 |
try:
|
| 27 |
from smolagents import CodeAgent, Tool, OpenAIServerModel
|
| 28 |
+
# Removed problematic: from smolagents.agent_types import AgentMessage
|
| 29 |
+
print("DEBUG: smolagents components (CodeAgent, Tool, OpenAIServerModel) imported successfully.")
|
| 30 |
+
SMOLAGENTS_LOADED = True
|
| 31 |
+
except ImportError as e:
|
| 32 |
print(f"DEBUG: Failed to import smolagents. Error: {e}")
|
| 33 |
logging.error(f"Failed to import smolagents. Please ensure it is installed and not corrupted. Error: {e}")
|
| 34 |
+
SMOLAGENTS_LOADED = False
|
|
|
|
| 35 |
class CodeAgent:
|
| 36 |
def __init__(self, *args, **kwargs):
|
| 37 |
print("DEBUG: Dummy CodeAgent initialized because smolagents failed to import.")
|
|
|
|
| 52 |
def __init__(self, *args, **kwargs):
|
| 53 |
print("DEBUG: Dummy OpenAIServerModel initialized because smolagents failed to import.")
|
| 54 |
logging.error("Dummy OpenAIServerModel initialized because smolagents failed to import.")
|
| 55 |
+
async def generate_reply(self, messages, **kwargs):
|
| 56 |
print("DEBUG: Dummy OpenAIServerModel generate_reply called.")
|
| 57 |
+
class DummyAgentMessageResponse:
|
|
|
|
| 58 |
text = "Error: smolagents.OpenAIServerModel not loaded or dummy generate_reply called."
|
| 59 |
return DummyAgentMessageResponse()
|
|
|
|
| 60 |
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
from datetime import datetime
|
| 63 |
print("DEBUG: datetime imported")
|
|
|
|
| 253 |
|
| 254 |
self.llm_for_fallback = model # Store the model instance for fallback
|
| 255 |
if self.llm_for_fallback is None:
|
| 256 |
+
print("DEBUG: QuestionAnsweringAgent self.llm_for_fallback is None, creating default OpenAIServerModel.")
|
| 257 |
openai_api_key = os.environ.get('OPENAI_API_KEY')
|
| 258 |
if not openai_api_key:
|
| 259 |
print("DEBUG: ERROR - OPENAI_API_KEY not found for QuestionAnsweringAgent.")
|
|
|
|
| 266 |
print(f"DEBUG: QuestionAnsweringAgent default OpenAIServerModel created with model_id: {CONFIG.OPENAI_MODEL_ID}")
|
| 267 |
|
| 268 |
minimal_super_args = {
|
| 269 |
+
"model": self.llm_for_fallback, # Pass the same model instance to the parent class
|
| 270 |
"tools": tools,
|
| 271 |
"max_steps": CONFIG.AGENT_MAX_STEPS,
|
| 272 |
}
|
|
|
|
| 316 |
reasoning_trace = "Agent execution started."
|
| 317 |
final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
|
| 318 |
try:
|
| 319 |
+
if not SMOLAGENTS_LOADED: # If smolagents didn't load, use dummy behavior
|
| 320 |
+
full_agent_response = self.run(question_text) # Calls dummy run
|
| 321 |
+
reasoning_trace = full_agent_response
|
| 322 |
+
final_answer_for_submission = "Error: smolagents library not loaded."
|
| 323 |
+
logger.error("Smolagents library not loaded, cannot process question effectively.")
|
| 324 |
+
else: # Smolagents loaded, proceed with normal logic
|
| 325 |
+
raw_output_obj = self.run(question_text)
|
| 326 |
+
print(f"DEBUG: QuestionAnsweringAgent.run() output type: {type(raw_output_obj)}")
|
| 327 |
+
|
| 328 |
+
if hasattr(raw_output_obj, 'log_string') and callable(raw_output_obj.log_string):
|
| 329 |
+
full_agent_response = str(raw_output_obj.log_string())
|
| 330 |
+
elif hasattr(raw_output_obj, 'text') and raw_output_obj.text is not None:
|
| 331 |
+
full_agent_response = str(raw_output_obj.text)
|
| 332 |
+
elif isinstance(raw_output_obj, str):
|
| 333 |
+
full_agent_response = raw_output_obj
|
| 334 |
+
elif hasattr(raw_output_obj, 'result') and raw_output_obj.result is not None:
|
| 335 |
+
full_agent_response = str(raw_output_obj.result)
|
| 336 |
+
else:
|
| 337 |
+
full_agent_response = str(raw_output_obj)
|
| 338 |
+
logger.warning(f"Raw output from agent.run() was of type {type(raw_output_obj)}. Used generic str() conversion.")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 339 |
|
| 340 |
+
print(f"DEBUG: QuestionAnsweringAgent full_agent_response (first 200 chars): {full_agent_response[:200]}")
|
| 341 |
+
reasoning_trace = full_agent_response
|
| 342 |
+
match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response, re.IGNORECASE | re.DOTALL)
|
| 343 |
+
if match:
|
| 344 |
+
final_answer_for_submission = match.group(1).strip()
|
| 345 |
+
print(f"DEBUG: QuestionAnsweringAgent extracted FINAL ANSWER: '{final_answer_for_submission}'")
|
| 346 |
else:
|
| 347 |
+
logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Attempting LLM summarization fallback.")
|
| 348 |
+
print("DEBUG: WARNING - QuestionAnsweringAgent could not find 'FINAL ANSWER:' in agent's response. Initiating LLM summarization fallback.")
|
| 349 |
+
|
| 350 |
+
if not self.llm_for_fallback:
|
| 351 |
+
print("DEBUG: ERROR - self.llm_for_fallback not initialized. Using full response as ultimate fallback.")
|
| 352 |
+
logger.error("self.llm_for_fallback not initialized. Using full response as ultimate fallback.")
|
| 353 |
+
final_answer_for_submission = full_agent_response.strip()
|
| 354 |
+
else:
|
| 355 |
+
# Construct messages as dictionaries
|
| 356 |
+
summarizer_messages = [
|
| 357 |
+
{"role": "system", "content": CONFIG.SUMMARIZER_SYSTEM_PROMPT},
|
| 358 |
+
{"role": "user", "content": 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.'"}
|
| 359 |
+
]
|
| 360 |
+
print(f"DEBUG: Summarizer LLM call with messages (first message content shown): {str(summarizer_messages[0])[:100]}...")
|
| 361 |
+
try:
|
| 362 |
+
summary_response_obj = await self.llm_for_fallback.generate_reply(messages=summarizer_messages)
|
| 363 |
+
if summary_response_obj and hasattr(summary_response_obj, 'text') and summary_response_obj.text:
|
| 364 |
+
concise_answer = summary_response_obj.text.strip()
|
| 365 |
+
if "Could not determine answer from reasoning." in concise_answer:
|
| 366 |
+
print(f"DEBUG: LLM summarization fallback indicated no clear answer. Using placeholder.")
|
| 367 |
+
logger.warning("LLM summarization fallback indicated no clear answer. Using placeholder.")
|
| 368 |
+
final_answer_for_submission = "Could not determine answer."
|
| 369 |
+
else:
|
| 370 |
+
final_answer_for_submission = concise_answer
|
| 371 |
+
print(f"DEBUG: LLM summarization fallback successful. Concise answer: '{final_answer_for_submission}'")
|
| 372 |
+
logger.info(f"LLM summarization fallback used. Extracted concise answer: '{final_answer_for_submission}'")
|
| 373 |
else:
|
| 374 |
+
print("DEBUG: ERROR - LLM summarization fallback returned empty or invalid response. Using full response as ultimate fallback.")
|
| 375 |
+
logger.error("LLM summarization fallback returned empty. Using full response as ultimate fallback.")
|
| 376 |
+
final_answer_for_submission = full_agent_response.strip()
|
| 377 |
+
except Exception as e_summary:
|
| 378 |
+
print(f"DEBUG: ERROR - Exception during LLM summarization fallback: {type(e_summary).__name__} - {str(e_summary)}. Using full response as ultimate fallback.")
|
| 379 |
+
logger.error(f"Exception during LLM summarization fallback: {e_summary}. Using full response as ultimate fallback.", exc_info=True)
|
| 380 |
final_answer_for_submission = full_agent_response.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
|
| 382 |
if not final_answer_for_submission:
|
| 383 |
logger.warning("Extracted final answer is empty after all fallbacks. Defaulting to a placeholder.")
|
|
|
|
| 443 |
print("DEBUG: ChuckAgent - self.agent_instance is None. Initializing QuestionAnsweringAgent...")
|
| 444 |
logger.info("Initializing QuestionAnsweringAgent within ChuckAgent...")
|
| 445 |
try:
|
| 446 |
+
# Pass the http_session and the model will be created inside QuestionAnsweringAgent if not provided
|
| 447 |
+
self.agent_instance = QuestionAnsweringAgent(http_session=self.http_session)
|
| 448 |
print("DEBUG: ChuckAgent - QuestionAnsweringAgent initialized successfully.")
|
| 449 |
logger.info("QuestionAnsweringAgent initialized successfully.")
|
| 450 |
except Exception as e:
|
|
|
|
| 543 |
print(f"DEBUG: Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
|
| 544 |
try:
|
| 545 |
model_ans, reasoning = agent(question_text)
|
|
|
|
| 546 |
payload_item = {"task_id": task_id, "submitted_answer": model_ans}
|
| 547 |
if reasoning:
|
| 548 |
payload_item["reasoning_trace"] = reasoning
|
|
|
|
| 557 |
print(f"DEBUG: ERROR - Error running agent on task {task_id}: {e}")
|
| 558 |
logger.error(f"Error running agent on task {task_id} ('{question_text[:50]}...'): {e}", exc_info=True)
|
| 559 |
error_answer = f"AGENT_CALL_ERROR: {str(e)}"
|
|
|
|
| 560 |
answers_payload.append({"task_id": task_id, "submitted_answer": error_answer, "reasoning_trace": str(e)})
|
| 561 |
results_log_data.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": error_answer, "Reasoning Trace": str(e)})
|
| 562 |
print(f"DEBUG: process_all_questions finished. Produced {len(answers_payload)} answers.")
|