Update app.py
Browse files
app.py
CHANGED
|
@@ -23,15 +23,16 @@ from typing import Optional, Dict, Any, List, Tuple # Added Tuple
|
|
| 23 |
print("DEBUG: typing imported")
|
| 24 |
|
| 25 |
# Import necessary components from smolagents
|
|
|
|
| 26 |
try:
|
| 27 |
from smolagents import CodeAgent, Tool, OpenAIServerModel
|
| 28 |
-
#
|
| 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 |
-
|
| 35 |
class CodeAgent:
|
| 36 |
def __init__(self, *args, **kwargs):
|
| 37 |
print("DEBUG: Dummy CodeAgent initialized because smolagents failed to import.")
|
|
@@ -39,8 +40,12 @@ except ImportError as e:
|
|
| 39 |
def run(self, *args, **kwargs):
|
| 40 |
print("DEBUG: Dummy CodeAgent run called.")
|
| 41 |
logging.error("Dummy CodeAgent run called.")
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
class Tool:
|
| 46 |
def __init__(self, *args, **kwargs):
|
|
@@ -52,11 +57,14 @@ except ImportError as e:
|
|
| 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 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
| 60 |
pass
|
| 61 |
|
| 62 |
from datetime import datetime
|
|
@@ -128,8 +136,8 @@ Remember, the "FINAL ANSWER: " prefix is a literal string you must output as the
|
|
| 128 |
"""
|
| 129 |
|
| 130 |
SUMMARIZER_SYSTEM_PROMPT = """You are an expert at extracting concise answers from text.
|
| 131 |
-
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.
|
| 132 |
-
This concise answer MUST strictly adhere to the provided formatting rules for numbers, strings, or comma-separated lists, as applicable to the question.
|
| 133 |
Do NOT include "FINAL ANSWER:" or any other prefix in your response. Just output the answer value.
|
| 134 |
Do NOT explain your reasoning for the concise answer. Only provide the answer value.
|
| 135 |
If the reasoning provided does not contain a clear answer to the original question, output the exact phrase "Could not determine answer from reasoning."
|
|
@@ -147,14 +155,13 @@ print("DEBUG: Logging configured.")
|
|
| 147 |
|
| 148 |
# --- Utility Functions ---
|
| 149 |
def ensure_dir_exists(directory_path: str):
|
| 150 |
-
"""Creates a directory if it doesn't already exist."""
|
| 151 |
-
print(f"DEBUG: Ensuring directory exists: {directory_path}")
|
| 152 |
os.makedirs(directory_path, exist_ok=True)
|
|
|
|
|
|
|
| 153 |
|
| 154 |
ensure_dir_exists(CONFIG.SCREENSHOTS_DIR)
|
| 155 |
|
| 156 |
def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
|
| 157 |
-
"""Gets Space ID and constructs the agent code URL."""
|
| 158 |
space_id = os.getenv("SPACE_ID")
|
| 159 |
if space_id:
|
| 160 |
agent_code_url = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
|
@@ -251,8 +258,8 @@ class QuestionAnsweringAgent(CodeAgent):
|
|
| 251 |
]
|
| 252 |
print(f"DEBUG: QuestionAnsweringAgent tools: {tools}")
|
| 253 |
|
| 254 |
-
self.llm_for_fallback = model
|
| 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:
|
|
@@ -264,9 +271,13 @@ class QuestionAnsweringAgent(CodeAgent):
|
|
| 264 |
api_key=openai_api_key
|
| 265 |
)
|
| 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,
|
| 270 |
"tools": tools,
|
| 271 |
"max_steps": CONFIG.AGENT_MAX_STEPS,
|
| 272 |
}
|
|
@@ -315,69 +326,73 @@ class QuestionAnsweringAgent(CodeAgent):
|
|
| 315 |
print(f"DEBUG: QuestionAnsweringAgent.process_question called for: '{question_text[:100]}...'")
|
| 316 |
reasoning_trace = "Agent execution started."
|
| 317 |
final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
|
|
|
|
| 318 |
try:
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 339 |
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
|
|
|
| 349 |
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 354 |
else:
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 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,7 +458,6 @@ class ChuckAgent:
|
|
| 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.")
|
|
|
|
| 23 |
print("DEBUG: typing imported")
|
| 24 |
|
| 25 |
# Import necessary components from smolagents
|
| 26 |
+
SMOLAGENTS_LOADED = False # Initialize flag
|
| 27 |
try:
|
| 28 |
from smolagents import CodeAgent, Tool, OpenAIServerModel
|
| 29 |
+
# AgentMessage is not directly imported if not available or needed for basic dict messages
|
| 30 |
print("DEBUG: smolagents components (CodeAgent, Tool, OpenAIServerModel) imported successfully.")
|
| 31 |
SMOLAGENTS_LOADED = True
|
| 32 |
except ImportError as e:
|
| 33 |
print(f"DEBUG: Failed to import smolagents. Error: {e}")
|
| 34 |
logging.error(f"Failed to import smolagents. Please ensure it is installed and not corrupted. Error: {e}")
|
| 35 |
+
# Dummy classes for script parsing if smolagents is not installed or fails to import
|
| 36 |
class CodeAgent:
|
| 37 |
def __init__(self, *args, **kwargs):
|
| 38 |
print("DEBUG: Dummy CodeAgent initialized because smolagents failed to import.")
|
|
|
|
| 40 |
def run(self, *args, **kwargs):
|
| 41 |
print("DEBUG: Dummy CodeAgent run called.")
|
| 42 |
logging.error("Dummy CodeAgent run called.")
|
| 43 |
+
# Simulate an object with text and log_string for consistent handling in process_question
|
| 44 |
+
class DummyRunResponse:
|
| 45 |
+
text = "Error: smolagents CodeAgent not loaded."
|
| 46 |
+
def log_string(self):
|
| 47 |
+
return "Error: smolagents CodeAgent not loaded. No reasoning trace available."
|
| 48 |
+
return DummyRunResponse()
|
| 49 |
|
| 50 |
class Tool:
|
| 51 |
def __init__(self, *args, **kwargs):
|
|
|
|
| 57 |
def __init__(self, *args, **kwargs):
|
| 58 |
print("DEBUG: Dummy OpenAIServerModel initialized because smolagents failed to import.")
|
| 59 |
logging.error("Dummy OpenAIServerModel initialized because smolagents failed to import.")
|
| 60 |
+
|
| 61 |
+
async def generate_stream(self, messages, **kwargs): # Changed to generate_stream
|
| 62 |
+
print("DEBUG: Dummy OpenAIServerModel generate_stream called.")
|
| 63 |
+
# Simulate async generator behavior
|
| 64 |
+
class DummyStreamChunk:
|
| 65 |
+
text = "Error: smolagents.OpenAIServerModel not loaded or dummy generate_stream called."
|
| 66 |
+
yield DummyStreamChunk()
|
| 67 |
+
|
| 68 |
pass
|
| 69 |
|
| 70 |
from datetime import datetime
|
|
|
|
| 136 |
"""
|
| 137 |
|
| 138 |
SUMMARIZER_SYSTEM_PROMPT = """You are an expert at extracting concise answers from text.
|
| 139 |
+
Given an original question and a detailed reasoning process (full agent log) that attempted to answer it, your task is to provide a very short, direct answer to the original question based *only* on the information present in the provided reasoning process.
|
| 140 |
+
This concise answer MUST strictly adhere to the provided formatting rules for numbers, strings, or comma-separated lists, as applicable to the original question.
|
| 141 |
Do NOT include "FINAL ANSWER:" or any other prefix in your response. Just output the answer value.
|
| 142 |
Do NOT explain your reasoning for the concise answer. Only provide the answer value.
|
| 143 |
If the reasoning provided does not contain a clear answer to the original question, output the exact phrase "Could not determine answer from reasoning."
|
|
|
|
| 155 |
|
| 156 |
# --- Utility Functions ---
|
| 157 |
def ensure_dir_exists(directory_path: str):
|
|
|
|
|
|
|
| 158 |
os.makedirs(directory_path, exist_ok=True)
|
| 159 |
+
print(f"DEBUG: Ensured directory exists: {directory_path}")
|
| 160 |
+
|
| 161 |
|
| 162 |
ensure_dir_exists(CONFIG.SCREENSHOTS_DIR)
|
| 163 |
|
| 164 |
def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
|
|
|
|
| 165 |
space_id = os.getenv("SPACE_ID")
|
| 166 |
if space_id:
|
| 167 |
agent_code_url = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
|
|
|
| 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')
|
| 265 |
if not openai_api_key:
|
|
|
|
| 271 |
api_key=openai_api_key
|
| 272 |
)
|
| 273 |
print(f"DEBUG: QuestionAnsweringAgent default OpenAIServerModel created with model_id: {CONFIG.OPENAI_MODEL_ID}")
|
| 274 |
+
elif not SMOLAGENTS_LOADED:
|
| 275 |
+
print("DEBUG: QuestionAnsweringAgent - smolagents not loaded, llm_for_fallback will use dummy.")
|
| 276 |
+
self.llm_for_fallback = OpenAIServerModel() # This will be the dummy if SMOLAGENTS_LOADED is False
|
| 277 |
+
|
| 278 |
|
| 279 |
minimal_super_args = {
|
| 280 |
+
"model": self.llm_for_fallback,
|
| 281 |
"tools": tools,
|
| 282 |
"max_steps": CONFIG.AGENT_MAX_STEPS,
|
| 283 |
}
|
|
|
|
| 326 |
print(f"DEBUG: QuestionAnsweringAgent.process_question called for: '{question_text[:100]}...'")
|
| 327 |
reasoning_trace = "Agent execution started."
|
| 328 |
final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
|
| 329 |
+
|
| 330 |
try:
|
| 331 |
+
raw_output_obj = self.run(question_text)
|
| 332 |
+
print(f"DEBUG: QuestionAnsweringAgent.run() output type: {type(raw_output_obj)}")
|
| 333 |
+
|
| 334 |
+
# Always get the full log for reasoning_trace
|
| 335 |
+
if hasattr(raw_output_obj, 'log_string') and callable(raw_output_obj.log_string):
|
| 336 |
+
reasoning_trace = str(raw_output_obj.log_string())
|
| 337 |
+
else: # Fallback for dummy or unexpected object
|
| 338 |
+
reasoning_trace = str(raw_output_obj)
|
| 339 |
+
|
| 340 |
+
# Get the agent's final text output for parsing
|
| 341 |
+
agent_final_text_output = ""
|
| 342 |
+
if hasattr(raw_output_obj, 'text') and raw_output_obj.text is not None:
|
| 343 |
+
agent_final_text_output = str(raw_output_obj.text)
|
| 344 |
+
elif isinstance(raw_output_obj, str): # If run() directly returned a string (e.g. dummy)
|
| 345 |
+
agent_final_text_output = raw_output_obj
|
| 346 |
+
else:
|
| 347 |
+
logger.warning(f"Raw output from agent.run() was of type {type(raw_output_obj)} and had no 'text' attribute. Using full log for parsing.")
|
| 348 |
+
agent_final_text_output = reasoning_trace # Parse the full log if .text is not available
|
| 349 |
+
|
| 350 |
+
print(f"DEBUG: QuestionAnsweringAgent agent_final_text_output (first 200 chars): {agent_final_text_output[:200]}")
|
| 351 |
+
|
| 352 |
+
match = re.search(r"FINAL ANSWER:\s*(.*)", agent_final_text_output, re.IGNORECASE | re.DOTALL)
|
| 353 |
+
|
| 354 |
+
if match:
|
| 355 |
+
final_answer_for_submission = match.group(1).strip()
|
| 356 |
+
print(f"DEBUG: QuestionAnsweringAgent extracted FINAL ANSWER from agent's direct output: '{final_answer_for_submission}'")
|
| 357 |
+
elif SMOLAGENTS_LOADED and self.llm_for_fallback: # Only attempt LLM fallback if smolagents is loaded
|
| 358 |
+
logger.warning("Could not find 'FINAL ANSWER:' in agent's direct output. Attempting LLM summarization fallback.")
|
| 359 |
+
print("DEBUG: WARNING - QuestionAnsweringAgent could not find 'FINAL ANSWER:' in agent's direct output. Initiating LLM summarization fallback.")
|
| 360 |
|
| 361 |
+
summarizer_messages = [
|
| 362 |
+
{"role": "system", "content": CONFIG.SUMMARIZER_SYSTEM_PROMPT},
|
| 363 |
+
{"role": "user", "content": f"Original Question: {question_text}\n\nAgent's Full Reasoning Log (which might not have ended with 'FINAL ANSWER:' correctly):\n{reasoning_trace}\n\nBased on the reasoning provided in the 'Agent's Full Reasoning Log', 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.'"}
|
| 364 |
+
]
|
| 365 |
+
print(f"DEBUG: Summarizer LLM call with messages (user message snippet): {summarizer_messages[1]['content'][:200]}...")
|
| 366 |
+
try:
|
| 367 |
+
concise_answer_parts = []
|
| 368 |
+
async for chunk in self.llm_for_fallback.generate_stream(messages=summarizer_messages):
|
| 369 |
+
if chunk and hasattr(chunk, 'text') and chunk.text:
|
| 370 |
+
concise_answer_parts.append(chunk.text)
|
| 371 |
|
| 372 |
+
concise_answer = "".join(concise_answer_parts).strip()
|
| 373 |
+
|
| 374 |
+
if concise_answer:
|
| 375 |
+
if "Could not determine answer from reasoning." in concise_answer:
|
| 376 |
+
print(f"DEBUG: LLM summarization fallback indicated no clear answer. Using placeholder.")
|
| 377 |
+
logger.warning("LLM summarization fallback indicated no clear answer. Using placeholder.")
|
| 378 |
+
final_answer_for_submission = "Could not determine answer."
|
| 379 |
+
else:
|
| 380 |
+
final_answer_for_submission = concise_answer
|
| 381 |
+
print(f"DEBUG: LLM summarization fallback successful. Concise answer: '{final_answer_for_submission}'")
|
| 382 |
+
logger.info(f"LLM summarization fallback used. Extracted concise answer: '{final_answer_for_submission}'")
|
| 383 |
else:
|
| 384 |
+
print("DEBUG: ERROR - LLM summarization fallback returned empty or invalid response. Using reasoning_trace as ultimate fallback.")
|
| 385 |
+
logger.error("LLM summarization fallback returned empty. Using reasoning_trace as ultimate fallback.")
|
| 386 |
+
final_answer_for_submission = reasoning_trace.strip() # Fallback to full reasoning if summary is empty
|
| 387 |
+
except Exception as e_summary:
|
| 388 |
+
print(f"DEBUG: ERROR - Exception during LLM summarization fallback: {type(e_summary).__name__} - {str(e_summary)}. Using reasoning_trace as ultimate fallback.")
|
| 389 |
+
logger.error(f"Exception during LLM summarization fallback: {e_summary}. Using reasoning_trace as ultimate fallback.", exc_info=True)
|
| 390 |
+
final_answer_for_submission = reasoning_trace.strip()
|
| 391 |
+
else: # smolagents not loaded OR self.llm_for_fallback is None
|
| 392 |
+
logger.warning("Could not find 'FINAL ANSWER:' and smolagents not loaded or no fallback LLM. Using agent_final_text_output.")
|
| 393 |
+
print("DEBUG: WARNING - Could not find 'FINAL ANSWER:' and no LLM fallback possible. Using agent_final_text_output.")
|
| 394 |
+
final_answer_for_submission = agent_final_text_output.strip()
|
| 395 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 396 |
|
| 397 |
if not final_answer_for_submission:
|
| 398 |
logger.warning("Extracted final answer is empty after all fallbacks. Defaulting to a placeholder.")
|
|
|
|
| 458 |
print("DEBUG: ChuckAgent - self.agent_instance is None. Initializing QuestionAnsweringAgent...")
|
| 459 |
logger.info("Initializing QuestionAnsweringAgent within ChuckAgent...")
|
| 460 |
try:
|
|
|
|
| 461 |
self.agent_instance = QuestionAnsweringAgent(http_session=self.http_session)
|
| 462 |
print("DEBUG: ChuckAgent - QuestionAnsweringAgent initialized successfully.")
|
| 463 |
logger.info("QuestionAnsweringAgent initialized successfully.")
|