Update app.py
Browse files
app.py
CHANGED
|
@@ -245,13 +245,28 @@ class QuestionAnsweringAgent(CodeAgent):
|
|
| 245 |
logger.info(f"QuestionAnsweringAgent initialized with model: {CONFIG.OPENAI_MODEL_ID}.")
|
| 246 |
|
| 247 |
async def process_question(self, question_text: str) -> Tuple[str, str]:
|
|
|
|
| 248 |
reasoning_trace = "Agent execution started."
|
| 249 |
final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
|
| 250 |
try:
|
| 251 |
logger.info(f"Processing question with CodeAgent: {question_text[:100]}...")
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
logger.info(f"CodeAgent full response (first 500 chars): {full_agent_response[:500]}...")
|
| 256 |
|
| 257 |
match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response, re.IGNORECASE | re.DOTALL)
|
|
@@ -259,16 +274,22 @@ class QuestionAnsweringAgent(CodeAgent):
|
|
| 259 |
final_answer_for_submission = match.group(1).strip()
|
| 260 |
logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}")
|
| 261 |
else:
|
| 262 |
-
logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback.")
|
| 263 |
final_answer_for_submission = full_agent_response.strip()
|
| 264 |
|
| 265 |
-
if not final_answer_for_submission:
|
| 266 |
logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
|
| 267 |
final_answer_for_submission = "Could not determine answer."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
except Exception as e:
|
| 269 |
logger.error(f"Error processing question in QuestionAnsweringAgent: {str(e)}", exc_info=True)
|
| 270 |
final_answer_for_submission = f"Error in agent processing: {str(e)}"
|
| 271 |
reasoning_trace += f"\nError encountered: {str(e)}"
|
|
|
|
| 272 |
return final_answer_for_submission, reasoning_trace
|
| 273 |
|
| 274 |
# --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
|
|
@@ -339,17 +360,7 @@ def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
|
|
| 339 |
raise ValueError(f"Error decoding server response for questions: {e}") from e
|
| 340 |
|
| 341 |
def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
|
| 342 |
-
|
| 343 |
-
results_log = []
|
| 344 |
-
logger.info(f"Running agent on {len(questions_data)} questions...")
|
| 345 |
-
for i, item in enumerate(questions_data):
|
| 346 |
-
task_id = item.get("task_id")
|
| 347 |
-
question_text = item.get("question")
|
| 348 |
-
if not task_id or question_text is None:
|
| 349 |
-
logger.warning(f"Skipping item {i+1} with missing data: {item}")
|
| 350 |
-
continue
|
| 351 |
-
logger.info(f"Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
|
| 352 |
-
model_ans, reasoning = "Error: Agent did not run", "No reasoning generated."
|
| 353 |
try:
|
| 354 |
model_ans, reasoning = agent(question_text)
|
| 355 |
except Exception as e:
|
|
@@ -357,14 +368,17 @@ def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]
|
|
| 357 |
model_ans = f"AGENT_CALL_ERROR: {e}"
|
| 358 |
reasoning = str(e)
|
| 359 |
|
| 360 |
-
|
| 361 |
-
|
|
|
|
| 362 |
payload_item["reasoning_trace"] = reasoning
|
| 363 |
answers_payload.append(payload_item)
|
| 364 |
|
| 365 |
results_log.append({
|
| 366 |
-
"Task ID": task_id,
|
| 367 |
-
"
|
|
|
|
|
|
|
| 368 |
})
|
| 369 |
return answers_payload, results_log
|
| 370 |
|
|
|
|
| 245 |
logger.info(f"QuestionAnsweringAgent initialized with model: {CONFIG.OPENAI_MODEL_ID}.")
|
| 246 |
|
| 247 |
async def process_question(self, question_text: str) -> Tuple[str, str]:
|
| 248 |
+
"""Processes a question and returns the final answer and reasoning trace."""
|
| 249 |
reasoning_trace = "Agent execution started."
|
| 250 |
final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
|
| 251 |
try:
|
| 252 |
logger.info(f"Processing question with CodeAgent: {question_text[:100]}...")
|
| 253 |
+
# MODIFICATION: Removed 'await' if self.run() is not async
|
| 254 |
+
# This assumes self.run() returns an object that can be converted to string,
|
| 255 |
+
# or an object that CodeAgent expects. If self.run() is truly async,
|
| 256 |
+
# then AgentText might be an intermediate result not meant to be awaited directly.
|
| 257 |
+
raw_output_obj = self.run(question_text)
|
| 258 |
+
|
| 259 |
+
# Convert raw_output_obj to string. This might need adjustment
|
| 260 |
+
# depending on what self.run() actually returns (e.g., AgentText might have a .text property)
|
| 261 |
+
if hasattr(raw_output_obj, 'text'): # Common pattern for such objects
|
| 262 |
+
full_agent_response = str(raw_output_obj.text)
|
| 263 |
+
elif isinstance(raw_output_obj, str):
|
| 264 |
+
full_agent_response = raw_output_obj
|
| 265 |
+
else: # Fallback, try to stringify directly
|
| 266 |
+
full_agent_response = str(raw_output_obj)
|
| 267 |
+
|
| 268 |
+
reasoning_trace = full_agent_response # Use the full response as the trace
|
| 269 |
+
|
| 270 |
logger.info(f"CodeAgent full response (first 500 chars): {full_agent_response[:500]}...")
|
| 271 |
|
| 272 |
match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response, re.IGNORECASE | re.DOTALL)
|
|
|
|
| 274 |
final_answer_for_submission = match.group(1).strip()
|
| 275 |
logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}")
|
| 276 |
else:
|
| 277 |
+
logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback (may be incorrect for submission).")
|
| 278 |
final_answer_for_submission = full_agent_response.strip()
|
| 279 |
|
| 280 |
+
if not final_answer_for_submission: # If empty after stripping
|
| 281 |
logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
|
| 282 |
final_answer_for_submission = "Could not determine answer."
|
| 283 |
+
|
| 284 |
+
except TypeError as te: # Catching the specific TypeError first
|
| 285 |
+
logger.error(f"TypeError during agent processing (likely self.run call): {str(te)}", exc_info=True)
|
| 286 |
+
final_answer_for_submission = f"Error in agent processing: {str(te)}"
|
| 287 |
+
reasoning_trace += f"\nTypeError encountered: {str(te)}"
|
| 288 |
except Exception as e:
|
| 289 |
logger.error(f"Error processing question in QuestionAnsweringAgent: {str(e)}", exc_info=True)
|
| 290 |
final_answer_for_submission = f"Error in agent processing: {str(e)}"
|
| 291 |
reasoning_trace += f"\nError encountered: {str(e)}"
|
| 292 |
+
|
| 293 |
return final_answer_for_submission, reasoning_trace
|
| 294 |
|
| 295 |
# --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
|
|
|
|
| 360 |
raise ValueError(f"Error decoding server response for questions: {e}") from e
|
| 361 |
|
| 362 |
def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
|
| 363 |
+
# ... (other code remains the same) ...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 364 |
try:
|
| 365 |
model_ans, reasoning = agent(question_text)
|
| 366 |
except Exception as e:
|
|
|
|
| 368 |
model_ans = f"AGENT_CALL_ERROR: {e}"
|
| 369 |
reasoning = str(e)
|
| 370 |
|
| 371 |
+
# MODIFICATION: Renamed 'model_answer' to 'submitted_answer' for the payload
|
| 372 |
+
payload_item = {"task_id": task_id, "submitted_answer": model_ans}
|
| 373 |
+
if reasoning: # Add reasoning_trace if it's available and not empty
|
| 374 |
payload_item["reasoning_trace"] = reasoning
|
| 375 |
answers_payload.append(payload_item)
|
| 376 |
|
| 377 |
results_log.append({
|
| 378 |
+
"Task ID": task_id,
|
| 379 |
+
"Question": question_text,
|
| 380 |
+
"Submitted Answer": model_ans, # This key is for your display df, can be different
|
| 381 |
+
"Reasoning Trace": reasoning
|
| 382 |
})
|
| 383 |
return answers_payload, results_log
|
| 384 |
|