pydantic update experiment
Browse files
app.py
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
|
|
| 1 |
print("DEBUG: app.py execution started (top of file)")
|
| 2 |
import os
|
| 3 |
print("DEBUG: os imported")
|
|
|
|
|
|
|
| 4 |
import gradio as gr
|
| 5 |
print("DEBUG: gradio imported")
|
| 6 |
import requests
|
|
@@ -54,7 +57,7 @@ print("DEBUG: datetime imported")
|
|
| 54 |
# --- Configuration ---
|
| 55 |
print("DEBUG: Defining AppConfig.")
|
| 56 |
class AppConfig:
|
| 57 |
-
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 58 |
QUESTIONS_URL_PATH = "/questions"
|
| 59 |
SUBMIT_URL_PATH = "/submit"
|
| 60 |
SCREENSHOTS_DIR = "screenshots"
|
|
@@ -121,7 +124,7 @@ ensure_dir_exists(CONFIG.SCREENSHOTS_DIR)
|
|
| 121 |
def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
|
| 122 |
space_id = os.getenv("SPACE_ID")
|
| 123 |
if space_id:
|
| 124 |
-
agent_code_url = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 125 |
else:
|
| 126 |
agent_code_url = "Agent code URL not found (SPACE_ID not set)"
|
| 127 |
return space_id, agent_code_url
|
|
@@ -150,7 +153,7 @@ if PYDANTIC_AI_LOADED: # Only define if library is loaded
|
|
| 150 |
print("DEBUG: ERROR - SERPER_API_KEY not found.")
|
| 151 |
return "Error: Serper API key not found in environment. Cannot perform web search."
|
| 152 |
|
| 153 |
-
url = "https://google.serper.dev/search"
|
| 154 |
headers = {'X-API-KEY': serper_api_key, 'Content-Type': 'application/json'}
|
| 155 |
payload = json.dumps({'q': query, 'num': CONFIG.SERPER_API_NUM_RESULTS})
|
| 156 |
|
|
@@ -268,7 +271,7 @@ class ChuckAgent:
|
|
| 268 |
except Exception as e:
|
| 269 |
print(f"DEBUG: ERROR - ChuckAgent failed to initialize Pydantic AI Agent: {type(e).__name__} - {e}")
|
| 270 |
logger.error(f"Failed to initialize Pydantic AI Agent: {e}", exc_info=True)
|
| 271 |
-
raise
|
| 272 |
elif not PYDANTIC_AI_LOADED:
|
| 273 |
print("DEBUG: ERROR - Pydantic AI library not loaded, cannot initialize agent.")
|
| 274 |
logger.error("Pydantic AI library not loaded, cannot initialize agent.")
|
|
@@ -284,33 +287,24 @@ class ChuckAgent:
|
|
| 284 |
reasoning_trace = "Pydantic AI Agent execution started."
|
| 285 |
final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
|
| 286 |
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
|
|
|
|
|
|
| 290 |
|
| 291 |
try:
|
| 292 |
-
# Pydantic AI's `run` method is async.
|
| 293 |
-
# It returns the final response string from the LLM after tool use.
|
| 294 |
-
# Pydantic AI handles the multi-step tool use internally based on the LLM's responses.
|
| 295 |
-
# The 'run' method in pydantic-ai can take a list of messages or a simple string prompt.
|
| 296 |
-
# For multi-turn conversation or more control, you might use agent.chat()
|
| 297 |
-
# but for single Q&A, agent.run() is fine.
|
| 298 |
-
# The "reasoning trace" isn't explicitly returned by pydantic-ai.run like smolagents.
|
| 299 |
-
# We will capture the full response as the primary source of reasoning.
|
| 300 |
-
# More detailed tracing can be achieved by configuring Python's logging for pydantic_ai.
|
| 301 |
-
|
| 302 |
-
# Pydantic AI's run method returns the agent's final textual response
|
| 303 |
agent_final_text_output = await self.agent_instance.run(question_text)
|
| 304 |
-
reasoning_trace = agent_final_text_output # Use the full output as the trace
|
| 305 |
|
| 306 |
-
print(f"DEBUG: Pydantic AI Agent raw output (first 500 chars): {
|
| 307 |
|
| 308 |
-
match = re.search(r"FINAL ANSWER:\s*(.*)",
|
| 309 |
|
| 310 |
if match:
|
| 311 |
final_answer_for_submission = match.group(1).strip()
|
| 312 |
print(f"DEBUG: Pydantic AI Agent extracted FINAL ANSWER: '{final_answer_for_submission}'")
|
| 313 |
-
elif PYDANTIC_AI_LOADED and self.llm_for_fallback:
|
| 314 |
logger.warning("Could not find 'FINAL ANSWER:' in Pydantic AI Agent's output. Attempting LLM summarization fallback.")
|
| 315 |
print("DEBUG: WARNING - Pydantic AI Agent - Could not find 'FINAL ANSWER:'. Initiating LLM summarization fallback.")
|
| 316 |
|
|
@@ -320,20 +314,6 @@ class ChuckAgent:
|
|
| 320 |
]
|
| 321 |
print(f"DEBUG: Summarizer LLM call with messages (user message snippet): {summarizer_messages[1]['content'][:200]}...")
|
| 322 |
try:
|
| 323 |
-
# We need to use the OpenAI client directly for the summarizer if pydantic_ai's llm object doesn't expose a generic chat completion method easily.
|
| 324 |
-
# Or, if self.llm_for_fallback is the PydanticOpenAI object, it might be usable.
|
| 325 |
-
# For simplicity, let's assume we can use a similar call pattern if available, or adapt.
|
| 326 |
-
# PydanticOpenAI is a wrapper; direct OpenAI client might be cleaner for this.
|
| 327 |
-
# For now, let's assume a similar streaming interface or adapt if PydanticOpenAI doesn't offer one.
|
| 328 |
-
# This part might need adjustment based on PydanticOpenAI's exact API.
|
| 329 |
-
# Let's try to make a non-streaming call for simplicity with the summarizer.
|
| 330 |
-
|
| 331 |
-
# Re-using the PydanticOpenAI llm instance. It wraps an OpenAI client.
|
| 332 |
-
# The `PydanticOpenAI` class itself might not have a `generate_stream` like `smolagents.OpenAIServerModel`.
|
| 333 |
-
# It's used by the `pydantic_ai.Agent`. For a direct call, we might need `openai.ChatCompletion.create`
|
| 334 |
-
# For now, this part is complex to replicate exactly without knowing PydanticOpenAI's direct call API.
|
| 335 |
-
# A robust way is to use the underlying OpenAI client.
|
| 336 |
-
# As a placeholder:
|
| 337 |
from openai import OpenAI as OfficialOpenAIClient # Use official client for direct calls
|
| 338 |
client = OfficialOpenAIClient(api_key=os.environ.get('OPENAI_API_KEY'))
|
| 339 |
response = client.chat.completions.create(
|
|
@@ -346,23 +326,23 @@ class ChuckAgent:
|
|
| 346 |
if concise_answer:
|
| 347 |
if "Could not determine answer from reasoning." in concise_answer:
|
| 348 |
print(f"DEBUG: LLM summarization fallback indicated no clear answer. Using placeholder.")
|
| 349 |
-
final_answer_for_submission = "Could not determine answer."
|
| 350 |
else:
|
| 351 |
final_answer_for_submission = concise_answer
|
| 352 |
print(f"DEBUG: LLM summarization fallback successful. Concise answer: '{final_answer_for_submission}'")
|
| 353 |
else:
|
| 354 |
-
print("DEBUG: ERROR - LLM summarization fallback returned empty. Using full output.")
|
| 355 |
-
final_answer_for_submission = reasoning_trace.strip()
|
| 356 |
except Exception as e_summary:
|
| 357 |
-
print(f"DEBUG: ERROR - Exception during LLM summarization fallback: {type(e_summary).__name__} - {str(e_summary)}. Using full output.")
|
| 358 |
logger.error(f"Exception during LLM summarization fallback: {e_summary}.", exc_info=True)
|
| 359 |
-
final_answer_for_submission = reasoning_trace.strip()
|
| 360 |
-
else:
|
| 361 |
-
logger.warning("Could not find 'FINAL ANSWER:' and no LLM fallback possible. Using agent's full output.")
|
| 362 |
-
final_answer_for_submission =
|
| 363 |
|
| 364 |
|
| 365 |
-
if not final_answer_for_submission:
|
| 366 |
final_answer_for_submission = "Could not determine answer."
|
| 367 |
|
| 368 |
except Exception as e:
|
|
@@ -370,17 +350,22 @@ class ChuckAgent:
|
|
| 370 |
print(f"DEBUG: ERROR - {error_msg}")
|
| 371 |
logger.error(error_msg, exc_info=True)
|
| 372 |
final_answer_for_submission = f"Error in Pydantic AI agent processing: {str(e)}"
|
| 373 |
-
reasoning_trace += f"\nError encountered: {str(e)}"
|
| 374 |
|
| 375 |
return final_answer_for_submission, reasoning_trace
|
| 376 |
|
| 377 |
def __call__(self, question: str) -> Tuple[str, str]:
|
| 378 |
print(f"DEBUG: ChuckAgent.__call__ received question: '{question[:50]}...' (Pydantic AI version)")
|
| 379 |
try:
|
| 380 |
-
self._ensure_agent_initialized()
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 384 |
|
| 385 |
print(f"DEBUG: ChuckAgent submitting task to event loop {self.loop} for question: '{question[:50]}...'")
|
| 386 |
if not self.loop.is_running():
|
|
@@ -389,7 +374,8 @@ class ChuckAgent:
|
|
| 389 |
else:
|
| 390 |
future = asyncio.run_coroutine_threadsafe(self._process_question_async(question), self.loop)
|
| 391 |
print(f"DEBUG: ChuckAgent waiting for future.result() for question: '{question[:50]}...'")
|
| 392 |
-
|
|
|
|
| 393 |
|
| 394 |
print(f"DEBUG: ChuckAgent future.result() obtained. Answer: '{final_answer[:50]}...'")
|
| 395 |
logger.info(f"ChuckAgent returning answer (first 50 chars): '{final_answer[:50]}...'")
|
|
@@ -411,22 +397,28 @@ class ChuckAgent:
|
|
| 411 |
print("DEBUG: ChuckAgent.close called (Pydantic AI version).")
|
| 412 |
if self.loop and self.loop.is_running():
|
| 413 |
print("DEBUG: ChuckAgent.close - loop is running, scheduling async_shutdown.")
|
| 414 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 415 |
elif self.loop and not self.loop.is_running():
|
| 416 |
print("DEBUG: ChuckAgent.close - loop is not running, using run_until_complete for shutdown_async.")
|
| 417 |
-
|
|
|
|
|
|
|
|
|
|
| 418 |
else:
|
| 419 |
-
print("DEBUG: ChuckAgent.close - No running loop to manage for shutdown.")
|
| 420 |
print("DEBUG: ChuckAgent.close finished (Pydantic AI version).")
|
| 421 |
|
| 422 |
print("DEBUG: ChuckAgent class defined (Pydantic AI version).")
|
| 423 |
|
| 424 |
|
| 425 |
# --- Orchestration Functions (fetch_questions, process_all_questions, submit_answers) ---
|
| 426 |
-
# These should largely remain the same, as they orchestrate the calls to ChuckAgent
|
| 427 |
-
# and handle communication with the evaluation server.
|
| 428 |
-
# Make sure process_all_questions correctly calls the new ChuckAgent.
|
| 429 |
-
|
| 430 |
def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
|
| 431 |
print(f"DEBUG: fetch_questions called with base_api_url: {base_api_url}")
|
| 432 |
questions_url = f"{base_api_url}{CONFIG.QUESTIONS_URL_PATH}"
|
|
@@ -445,7 +437,7 @@ def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
|
|
| 445 |
print(f"DEBUG: ERROR - Error fetching questions: {e}")
|
| 446 |
logger.error(f"Error fetching questions: {e}", exc_info=True)
|
| 447 |
raise ConnectionError(f"Error fetching questions: {e}")
|
| 448 |
-
except requests.exceptions.JSONDecodeError as e:
|
| 449 |
print(f"DEBUG: ERROR - Error decoding questions JSON: {e}")
|
| 450 |
logger.error(f"Error decoding questions JSON: {e}. Response: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True)
|
| 451 |
raise ValueError(f"Error decoding server response for questions: {e}")
|
|
@@ -457,12 +449,12 @@ def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]
|
|
| 457 |
for i, item in enumerate(questions_data):
|
| 458 |
task_id = item.get("task_id")
|
| 459 |
question_text = item.get("question")
|
| 460 |
-
if not task_id or question_text is None:
|
| 461 |
logger.warning(f"Skipping item with missing task_id or question: {item}")
|
| 462 |
continue
|
| 463 |
print(f"DEBUG: Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
|
| 464 |
try:
|
| 465 |
-
model_ans, reasoning = agent(question_text)
|
| 466 |
payload_item = {"task_id": task_id, "submitted_answer": model_ans}
|
| 467 |
if reasoning:
|
| 468 |
payload_item["reasoning_trace"] = reasoning
|
|
@@ -473,7 +465,7 @@ def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]
|
|
| 473 |
"Submitted Answer": model_ans,
|
| 474 |
"Reasoning Trace": reasoning
|
| 475 |
})
|
| 476 |
-
except Exception as e:
|
| 477 |
print(f"DEBUG: ERROR - Error running agent on task {task_id}: {e}")
|
| 478 |
logger.error(f"Error running agent on task {task_id} ('{question_text[:50]}...'): {e}", exc_info=True)
|
| 479 |
error_answer = f"AGENT_CALL_ERROR: {str(e)}"
|
|
@@ -508,13 +500,13 @@ def submit_answers(base_api_url: str, username: str, agent_code_url: str, answer
|
|
| 508 |
error_detail = f"Server responded with {e.response.status_code}."
|
| 509 |
try:
|
| 510 |
error_json = e.response.json(); error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 511 |
-
except requests.exceptions.JSONDecodeError: error_detail += f" Raw Response: {e.response.text[:500]}"
|
| 512 |
final_status = f"Submission Failed: {error_detail}"; logger.error(final_status)
|
| 513 |
except requests.exceptions.Timeout:
|
| 514 |
final_status = "Submission Failed: The request timed out."; logger.error(final_status)
|
| 515 |
except requests.exceptions.RequestException as e:
|
| 516 |
final_status = f"Submission Failed: Network error - {e}"; logger.error(final_status, exc_info=True)
|
| 517 |
-
except Exception as e:
|
| 518 |
final_status = f"An unexpected error occurred during submission: {e}"; logger.error(final_status, exc_info=True)
|
| 519 |
print(f"DEBUG: submit_answers final_status: {final_status}")
|
| 520 |
return final_status
|
|
@@ -524,6 +516,7 @@ def submit_answers(base_api_url: str, username: str, agent_code_url: str, answer
|
|
| 524 |
GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
|
| 525 |
|
| 526 |
print("DEBUG: Defining run_and_submit_all_evaluation function.")
|
|
|
|
| 527 |
def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
|
| 528 |
global GLOBAL_CHUCK_AGENT
|
| 529 |
print(f"DEBUG: run_and_submit_all_evaluation called. Profile type: {type(profile)}")
|
|
@@ -550,46 +543,80 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
|
|
| 550 |
print(f"DEBUG: User logged in: {username}")
|
| 551 |
|
| 552 |
_, agent_code_url = get_space_id_agent_code_url()
|
| 553 |
-
results_log_data: List[Dict[str, Any]] = []
|
| 554 |
|
| 555 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 556 |
print("DEBUG: run_and_submit_all_evaluation - Attempting to initialize/get GLOBAL_CHUCK_AGENT.")
|
| 557 |
if GLOBAL_CHUCK_AGENT is None:
|
| 558 |
print("DEBUG: GLOBAL_CHUCK_AGENT is None. Creating new instance (Pydantic AI version).")
|
| 559 |
logger.info("GLOBAL_CHUCK_AGENT is None. Attempting to create a new instance (Pydantic AI version).")
|
| 560 |
-
GLOBAL_CHUCK_AGENT = ChuckAgent()
|
| 561 |
print("DEBUG: GLOBAL_CHUCK_AGENT new instance created.")
|
| 562 |
else:
|
| 563 |
print("DEBUG: GLOBAL_CHUCK_AGENT already exists.")
|
| 564 |
agent_instance = GLOBAL_CHUCK_AGENT
|
| 565 |
-
|
| 566 |
print("DEBUG: run_and_submit_all_evaluation - Ensuring agent_instance._ensure_agent_initialized().")
|
| 567 |
-
agent_instance._ensure_agent_initialized()
|
| 568 |
print("DEBUG: run_and_submit_all_evaluation - Agent ensured to be initialized.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 569 |
|
| 570 |
questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
|
| 571 |
-
answers_payload,
|
|
|
|
| 572 |
submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload)
|
| 573 |
|
| 574 |
except EnvironmentError as e:
|
| 575 |
print(f"DEBUG: ERROR - EnvironmentError in run_and_submit_all_evaluation: {e}")
|
| 576 |
logger.critical(f"Agent instantiation or operation failed due to missing env vars: {e}")
|
| 577 |
submission_status = f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets."
|
| 578 |
-
|
|
|
|
|
|
|
| 579 |
print(f"DEBUG: ERROR - ConnectionError/ValueError in run_and_submit_all_evaluation: {e}")
|
| 580 |
logger.error(f"Data handling or connection error during evaluation: {e}", exc_info=True)
|
| 581 |
submission_status = str(e)
|
| 582 |
-
|
|
|
|
|
|
|
| 583 |
print(f"DEBUG: ERROR - RuntimeError in run_and_submit_all_evaluation: {e}")
|
| 584 |
logger.error(f"Runtime error during evaluation: {e}", exc_info=True)
|
| 585 |
submission_status = f"Runtime Error: {e}"
|
| 586 |
-
|
|
|
|
|
|
|
| 587 |
print(f"DEBUG: ERROR - Unexpected Exception in run_and_submit_all_evaluation: {type(e).__name__} - {e}")
|
| 588 |
logger.error(f"An unexpected error occurred during the evaluation pipeline: {e}", exc_info=True)
|
| 589 |
submission_status = f"An unexpected error occurred: {e}"
|
| 590 |
-
if not results_log_data:
|
| 591 |
-
results_log_data = [{"Task ID": "N/A", "Question": "
|
| 592 |
|
|
|
|
| 593 |
results_df = pd.DataFrame(results_log_data if results_log_data else [])
|
| 594 |
print(f"DEBUG: run_and_submit_all_evaluation returning. Status: {submission_status[:100]}...")
|
| 595 |
return submission_status, results_df
|
|
@@ -599,7 +626,7 @@ print("DEBUG: Building Gradio interface.")
|
|
| 599 |
try:
|
| 600 |
with gr.Blocks(css=".gradio-container {max-width: 960px !important; margin: auto !important;}") as demo:
|
| 601 |
print("DEBUG: gr.Blocks context entered.")
|
| 602 |
-
gr.Markdown("# Chuck's Agent Evaluation Runner (Pydantic AI Version)")
|
| 603 |
gr.Markdown(
|
| 604 |
"""
|
| 605 |
**Instructions:**
|
|
@@ -648,7 +675,7 @@ try:
|
|
| 648 |
except Exception as e:
|
| 649 |
print(f"DEBUG: ERROR - Exception during Gradio UI definition: {e}")
|
| 650 |
logger.critical(f"Gradio UI definition failed: {e}", exc_info=True)
|
| 651 |
-
demo = None
|
| 652 |
|
| 653 |
|
| 654 |
# --- Application Startup & Shutdown Handling ---
|
|
@@ -658,13 +685,18 @@ if __name__ == "__main__":
|
|
| 658 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 659 |
space_id_startup, agent_url_startup = get_space_id_agent_code_url()
|
| 660 |
|
| 661 |
-
|
|
|
|
| 662 |
print(f"Gradio Version: {gr.__version__}")
|
| 663 |
try:
|
| 664 |
-
import pydantic_ai
|
| 665 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 666 |
except ImportError:
|
| 667 |
-
|
| 668 |
|
| 669 |
|
| 670 |
if space_host_startup:
|
|
@@ -675,7 +707,7 @@ if __name__ == "__main__":
|
|
| 675 |
|
| 676 |
if space_id_startup:
|
| 677 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 678 |
-
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 679 |
print(f" Agent Code URL reported to server: {agent_url_startup}")
|
| 680 |
else:
|
| 681 |
print("ℹ️ SPACE_ID environment variable not found. Repo URL cannot be determined.")
|
|
@@ -690,7 +722,8 @@ if __name__ == "__main__":
|
|
| 690 |
|
| 691 |
if demo is not None:
|
| 692 |
try:
|
| 693 |
-
|
|
|
|
| 694 |
except Exception as e:
|
| 695 |
print(f"DEBUG: ERROR - Gradio demo.launch() failed: {e}")
|
| 696 |
logger.critical(f"Gradio demo launch failed: {e}", exc_info=True)
|
|
|
|
| 1 |
+
```python
|
| 2 |
print("DEBUG: app.py execution started (top of file)")
|
| 3 |
import os
|
| 4 |
print("DEBUG: os imported")
|
| 5 |
+
import sys # ADDED
|
| 6 |
+
print("DEBUG: sys imported") # ADDED
|
| 7 |
import gradio as gr
|
| 8 |
print("DEBUG: gradio imported")
|
| 9 |
import requests
|
|
|
|
| 57 |
# --- Configuration ---
|
| 58 |
print("DEBUG: Defining AppConfig.")
|
| 59 |
class AppConfig:
|
| 60 |
+
DEFAULT_API_URL = "[https://agents-course-unit4-scoring.hf.space](https://agents-course-unit4-scoring.hf.space)"
|
| 61 |
QUESTIONS_URL_PATH = "/questions"
|
| 62 |
SUBMIT_URL_PATH = "/submit"
|
| 63 |
SCREENSHOTS_DIR = "screenshots"
|
|
|
|
| 124 |
def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
|
| 125 |
space_id = os.getenv("SPACE_ID")
|
| 126 |
if space_id:
|
| 127 |
+
agent_code_url = f"[https://huggingface.co/spaces/](https://huggingface.co/spaces/){space_id}/tree/main"
|
| 128 |
else:
|
| 129 |
agent_code_url = "Agent code URL not found (SPACE_ID not set)"
|
| 130 |
return space_id, agent_code_url
|
|
|
|
| 153 |
print("DEBUG: ERROR - SERPER_API_KEY not found.")
|
| 154 |
return "Error: Serper API key not found in environment. Cannot perform web search."
|
| 155 |
|
| 156 |
+
url = "[https://google.serper.dev/search](https://google.serper.dev/search)"
|
| 157 |
headers = {'X-API-KEY': serper_api_key, 'Content-Type': 'application/json'}
|
| 158 |
payload = json.dumps({'q': query, 'num': CONFIG.SERPER_API_NUM_RESULTS})
|
| 159 |
|
|
|
|
| 271 |
except Exception as e:
|
| 272 |
print(f"DEBUG: ERROR - ChuckAgent failed to initialize Pydantic AI Agent: {type(e).__name__} - {e}")
|
| 273 |
logger.error(f"Failed to initialize Pydantic AI Agent: {e}", exc_info=True)
|
| 274 |
+
raise # Re-raise the exception to be caught by the caller if critical
|
| 275 |
elif not PYDANTIC_AI_LOADED:
|
| 276 |
print("DEBUG: ERROR - Pydantic AI library not loaded, cannot initialize agent.")
|
| 277 |
logger.error("Pydantic AI library not loaded, cannot initialize agent.")
|
|
|
|
| 287 |
reasoning_trace = "Pydantic AI Agent execution started."
|
| 288 |
final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
|
| 289 |
|
| 290 |
+
# Ensure agent is initialized; this should ideally be guaranteed by _ensure_agent_initialized
|
| 291 |
+
if self.agent_instance is None or (not PYDANTIC_AI_LOADED and isinstance(self.agent_instance, globals().get('Agent'))):
|
| 292 |
+
logger.error("Pydantic AI Agent instance not available or is a dummy placeholder.")
|
| 293 |
+
print("DEBUG: ERROR - Pydantic AI Agent instance not available in _process_question_async.")
|
| 294 |
+
return "Error: Pydantic AI Agent not properly initialized.", "Agent not initialized at process time."
|
| 295 |
|
| 296 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
agent_final_text_output = await self.agent_instance.run(question_text)
|
| 298 |
+
reasoning_trace = str(agent_final_text_output) # Use the full output as the trace
|
| 299 |
|
| 300 |
+
print(f"DEBUG: Pydantic AI Agent raw output (first 500 chars): {reasoning_trace[:500]}")
|
| 301 |
|
| 302 |
+
match = re.search(r"FINAL ANSWER:\s*(.*)", reasoning_trace, re.IGNORECASE | re.DOTALL)
|
| 303 |
|
| 304 |
if match:
|
| 305 |
final_answer_for_submission = match.group(1).strip()
|
| 306 |
print(f"DEBUG: Pydantic AI Agent extracted FINAL ANSWER: '{final_answer_for_submission}'")
|
| 307 |
+
elif PYDANTIC_AI_LOADED and self.llm_for_fallback: # Only attempt fallback if pydantic-ai was loaded
|
| 308 |
logger.warning("Could not find 'FINAL ANSWER:' in Pydantic AI Agent's output. Attempting LLM summarization fallback.")
|
| 309 |
print("DEBUG: WARNING - Pydantic AI Agent - Could not find 'FINAL ANSWER:'. Initiating LLM summarization fallback.")
|
| 310 |
|
|
|
|
| 314 |
]
|
| 315 |
print(f"DEBUG: Summarizer LLM call with messages (user message snippet): {summarizer_messages[1]['content'][:200]}...")
|
| 316 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
from openai import OpenAI as OfficialOpenAIClient # Use official client for direct calls
|
| 318 |
client = OfficialOpenAIClient(api_key=os.environ.get('OPENAI_API_KEY'))
|
| 319 |
response = client.chat.completions.create(
|
|
|
|
| 326 |
if concise_answer:
|
| 327 |
if "Could not determine answer from reasoning." in concise_answer:
|
| 328 |
print(f"DEBUG: LLM summarization fallback indicated no clear answer. Using placeholder.")
|
| 329 |
+
final_answer_for_submission = "Could not determine answer." # Or use the original agent output
|
| 330 |
else:
|
| 331 |
final_answer_for_submission = concise_answer
|
| 332 |
print(f"DEBUG: LLM summarization fallback successful. Concise answer: '{final_answer_for_submission}'")
|
| 333 |
else:
|
| 334 |
+
print("DEBUG: ERROR - LLM summarization fallback returned empty. Using full agent output.")
|
| 335 |
+
final_answer_for_submission = reasoning_trace.strip() # Fallback to full trace
|
| 336 |
except Exception as e_summary:
|
| 337 |
+
print(f"DEBUG: ERROR - Exception during LLM summarization fallback: {type(e_summary).__name__} - {str(e_summary)}. Using full agent output.")
|
| 338 |
logger.error(f"Exception during LLM summarization fallback: {e_summary}.", exc_info=True)
|
| 339 |
+
final_answer_for_submission = reasoning_trace.strip() # Fallback to full trace
|
| 340 |
+
else: # No FINAL ANSWER and no fallback (e.g., pydantic-ai not loaded, or no llm_for_fallback)
|
| 341 |
+
logger.warning("Could not find 'FINAL ANSWER:' and no LLM fallback possible/applicable. Using agent's full output.")
|
| 342 |
+
final_answer_for_submission = reasoning_trace.strip() # Use the full output
|
| 343 |
|
| 344 |
|
| 345 |
+
if not final_answer_for_submission: # Should be rare if reasoning_trace is used as fallback
|
| 346 |
final_answer_for_submission = "Could not determine answer."
|
| 347 |
|
| 348 |
except Exception as e:
|
|
|
|
| 350 |
print(f"DEBUG: ERROR - {error_msg}")
|
| 351 |
logger.error(error_msg, exc_info=True)
|
| 352 |
final_answer_for_submission = f"Error in Pydantic AI agent processing: {str(e)}"
|
| 353 |
+
reasoning_trace += f"\nError encountered during processing: {str(e)}"
|
| 354 |
|
| 355 |
return final_answer_for_submission, reasoning_trace
|
| 356 |
|
| 357 |
def __call__(self, question: str) -> Tuple[str, str]:
|
| 358 |
print(f"DEBUG: ChuckAgent.__call__ received question: '{question[:50]}...' (Pydantic AI version)")
|
| 359 |
try:
|
| 360 |
+
self._ensure_agent_initialized() # Ensures self.agent_instance is set (real or dummy)
|
| 361 |
+
|
| 362 |
+
# Critical check if agent is usable
|
| 363 |
+
if self.agent_instance is None or \
|
| 364 |
+
(not PYDANTIC_AI_LOADED and isinstance(self.agent_instance, globals().get('Agent'))):
|
| 365 |
+
# globals().get('Agent') refers to the dummy Agent if PYDANTIC_AI_LOADED is False
|
| 366 |
+
error_message = "Pydantic AI Agent was not initialized or is a dummy placeholder due to missing 'pydantic-ai' library."
|
| 367 |
+
print(f"DEBUG: ERROR - ChuckAgent.__call__ {error_message}")
|
| 368 |
+
raise RuntimeError(error_message)
|
| 369 |
|
| 370 |
print(f"DEBUG: ChuckAgent submitting task to event loop {self.loop} for question: '{question[:50]}...'")
|
| 371 |
if not self.loop.is_running():
|
|
|
|
| 374 |
else:
|
| 375 |
future = asyncio.run_coroutine_threadsafe(self._process_question_async(question), self.loop)
|
| 376 |
print(f"DEBUG: ChuckAgent waiting for future.result() for question: '{question[:50]}...'")
|
| 377 |
+
# Increased timeout for potentially longer chains or slower API responses
|
| 378 |
+
final_answer, reasoning_trace = future.result(timeout=300)
|
| 379 |
|
| 380 |
print(f"DEBUG: ChuckAgent future.result() obtained. Answer: '{final_answer[:50]}...'")
|
| 381 |
logger.info(f"ChuckAgent returning answer (first 50 chars): '{final_answer[:50]}...'")
|
|
|
|
| 397 |
print("DEBUG: ChuckAgent.close called (Pydantic AI version).")
|
| 398 |
if self.loop and self.loop.is_running():
|
| 399 |
print("DEBUG: ChuckAgent.close - loop is running, scheduling async_shutdown.")
|
| 400 |
+
# Ensure the future is awaited or handled properly, especially if called from non-async context
|
| 401 |
+
future = asyncio.run_coroutine_threadsafe(self.shutdown_async(), self.loop)
|
| 402 |
+
try:
|
| 403 |
+
future.result(timeout=10) # Wait for shutdown to complete
|
| 404 |
+
except asyncio.TimeoutError:
|
| 405 |
+
logger.warning("Timeout waiting for ChuckAgent async_shutdown to complete.")
|
| 406 |
+
except Exception as e:
|
| 407 |
+
logger.error(f"Error during async_shutdown result retrieval: {e}")
|
| 408 |
elif self.loop and not self.loop.is_running():
|
| 409 |
print("DEBUG: ChuckAgent.close - loop is not running, using run_until_complete for shutdown_async.")
|
| 410 |
+
try:
|
| 411 |
+
self.loop.run_until_complete(self.shutdown_async())
|
| 412 |
+
except Exception as e:
|
| 413 |
+
logger.error(f"Error during run_until_complete for shutdown_async: {e}")
|
| 414 |
else:
|
| 415 |
+
print("DEBUG: ChuckAgent.close - No running or available loop to manage for shutdown.")
|
| 416 |
print("DEBUG: ChuckAgent.close finished (Pydantic AI version).")
|
| 417 |
|
| 418 |
print("DEBUG: ChuckAgent class defined (Pydantic AI version).")
|
| 419 |
|
| 420 |
|
| 421 |
# --- Orchestration Functions (fetch_questions, process_all_questions, submit_answers) ---
|
|
|
|
|
|
|
|
|
|
|
|
|
| 422 |
def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
|
| 423 |
print(f"DEBUG: fetch_questions called with base_api_url: {base_api_url}")
|
| 424 |
questions_url = f"{base_api_url}{CONFIG.QUESTIONS_URL_PATH}"
|
|
|
|
| 437 |
print(f"DEBUG: ERROR - Error fetching questions: {e}")
|
| 438 |
logger.error(f"Error fetching questions: {e}", exc_info=True)
|
| 439 |
raise ConnectionError(f"Error fetching questions: {e}")
|
| 440 |
+
except requests.exceptions.JSONDecodeError as e:
|
| 441 |
print(f"DEBUG: ERROR - Error decoding questions JSON: {e}")
|
| 442 |
logger.error(f"Error decoding questions JSON: {e}. Response: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True)
|
| 443 |
raise ValueError(f"Error decoding server response for questions: {e}")
|
|
|
|
| 449 |
for i, item in enumerate(questions_data):
|
| 450 |
task_id = item.get("task_id")
|
| 451 |
question_text = item.get("question")
|
| 452 |
+
if not task_id or question_text is None:
|
| 453 |
logger.warning(f"Skipping item with missing task_id or question: {item}")
|
| 454 |
continue
|
| 455 |
print(f"DEBUG: Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
|
| 456 |
try:
|
| 457 |
+
model_ans, reasoning = agent(question_text)
|
| 458 |
payload_item = {"task_id": task_id, "submitted_answer": model_ans}
|
| 459 |
if reasoning:
|
| 460 |
payload_item["reasoning_trace"] = reasoning
|
|
|
|
| 465 |
"Submitted Answer": model_ans,
|
| 466 |
"Reasoning Trace": reasoning
|
| 467 |
})
|
| 468 |
+
except Exception as e: # Catch errors from agent call
|
| 469 |
print(f"DEBUG: ERROR - Error running agent on task {task_id}: {e}")
|
| 470 |
logger.error(f"Error running agent on task {task_id} ('{question_text[:50]}...'): {e}", exc_info=True)
|
| 471 |
error_answer = f"AGENT_CALL_ERROR: {str(e)}"
|
|
|
|
| 500 |
error_detail = f"Server responded with {e.response.status_code}."
|
| 501 |
try:
|
| 502 |
error_json = e.response.json(); error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 503 |
+
except requests.exceptions.JSONDecodeError: error_detail += f" Raw Response: {e.response.text[:500]}"
|
| 504 |
final_status = f"Submission Failed: {error_detail}"; logger.error(final_status)
|
| 505 |
except requests.exceptions.Timeout:
|
| 506 |
final_status = "Submission Failed: The request timed out."; logger.error(final_status)
|
| 507 |
except requests.exceptions.RequestException as e:
|
| 508 |
final_status = f"Submission Failed: Network error - {e}"; logger.error(final_status, exc_info=True)
|
| 509 |
+
except Exception as e: # Catch any other unexpected errors during submission
|
| 510 |
final_status = f"An unexpected error occurred during submission: {e}"; logger.error(final_status, exc_info=True)
|
| 511 |
print(f"DEBUG: submit_answers final_status: {final_status}")
|
| 512 |
return final_status
|
|
|
|
| 516 |
GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
|
| 517 |
|
| 518 |
print("DEBUG: Defining run_and_submit_all_evaluation function.")
|
| 519 |
+
# MODIFIED run_and_submit_all_evaluation function
|
| 520 |
def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
|
| 521 |
global GLOBAL_CHUCK_AGENT
|
| 522 |
print(f"DEBUG: run_and_submit_all_evaluation called. Profile type: {type(profile)}")
|
|
|
|
| 543 |
print(f"DEBUG: User logged in: {username}")
|
| 544 |
|
| 545 |
_, agent_code_url = get_space_id_agent_code_url()
|
| 546 |
+
results_log_data: List[Dict[str, Any]] = [] # Initialize here for broader scope
|
| 547 |
|
| 548 |
try:
|
| 549 |
+
# !!! ADDED CHECK FOR PYDANTIC_AI_LOADED !!!
|
| 550 |
+
if not PYDANTIC_AI_LOADED:
|
| 551 |
+
error_msg = "CRITICAL ERROR: The 'pydantic-ai' library is not installed or could not be loaded. The Agent cannot function. Please ensure 'pydantic-ai' is listed in your requirements.txt and the environment is correctly set up, then restart the application."
|
| 552 |
+
print(f"DEBUG: {error_msg}")
|
| 553 |
+
logger.critical(error_msg)
|
| 554 |
+
error_df_data = [{"Task ID": "N/A",
|
| 555 |
+
"Question": "Critical Dependency Error",
|
| 556 |
+
"Submitted Answer": "pydantic-ai missing",
|
| 557 |
+
"Reasoning Trace": error_msg}]
|
| 558 |
+
return error_msg, pd.DataFrame(error_df_data)
|
| 559 |
+
|
| 560 |
print("DEBUG: run_and_submit_all_evaluation - Attempting to initialize/get GLOBAL_CHUCK_AGENT.")
|
| 561 |
if GLOBAL_CHUCK_AGENT is None:
|
| 562 |
print("DEBUG: GLOBAL_CHUCK_AGENT is None. Creating new instance (Pydantic AI version).")
|
| 563 |
logger.info("GLOBAL_CHUCK_AGENT is None. Attempting to create a new instance (Pydantic AI version).")
|
| 564 |
+
GLOBAL_CHUCK_AGENT = ChuckAgent() # This might raise EnvironmentError if keys are missing
|
| 565 |
print("DEBUG: GLOBAL_CHUCK_AGENT new instance created.")
|
| 566 |
else:
|
| 567 |
print("DEBUG: GLOBAL_CHUCK_AGENT already exists.")
|
| 568 |
agent_instance = GLOBAL_CHUCK_AGENT
|
| 569 |
+
|
| 570 |
print("DEBUG: run_and_submit_all_evaluation - Ensuring agent_instance._ensure_agent_initialized().")
|
| 571 |
+
agent_instance._ensure_agent_initialized()
|
| 572 |
print("DEBUG: run_and_submit_all_evaluation - Agent ensured to be initialized.")
|
| 573 |
+
|
| 574 |
+
# This secondary check is mostly redundant due to the PYDANTIC_AI_LOADED check above
|
| 575 |
+
# and error handling within ChuckAgent.__call__ but kept for belt-and-suspenders.
|
| 576 |
+
if agent_instance.agent_instance is None or \
|
| 577 |
+
(not PYDANTIC_AI_LOADED and isinstance(agent_instance.agent_instance, globals().get('Agent'))):
|
| 578 |
+
critical_error_msg = "Agent initialization failed or resulted in a dummy agent. This typically means 'pydantic-ai' is missing or core configuration (like API keys) is incorrect."
|
| 579 |
+
logger.critical(critical_error_msg)
|
| 580 |
+
print(f"DEBUG: CRITICAL - {critical_error_msg}")
|
| 581 |
+
# Create a DataFrame for the error message
|
| 582 |
+
error_df_data = [{"Task ID": "N/A",
|
| 583 |
+
"Question": "Agent Initialization Error",
|
| 584 |
+
"Submitted Answer": "Init Failed",
|
| 585 |
+
"Reasoning Trace": critical_error_msg}]
|
| 586 |
+
return critical_error_msg, pd.DataFrame(error_df_data)
|
| 587 |
+
|
| 588 |
|
| 589 |
questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
|
| 590 |
+
answers_payload, results_log_data_processed = process_all_questions(agent_instance, questions_data)
|
| 591 |
+
results_log_data.extend(results_log_data_processed) # Append processed results
|
| 592 |
submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload)
|
| 593 |
|
| 594 |
except EnvironmentError as e:
|
| 595 |
print(f"DEBUG: ERROR - EnvironmentError in run_and_submit_all_evaluation: {e}")
|
| 596 |
logger.critical(f"Agent instantiation or operation failed due to missing env vars: {e}")
|
| 597 |
submission_status = f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets."
|
| 598 |
+
if not results_log_data: # Ensure results_log_data has some info for the table
|
| 599 |
+
results_log_data = [{"Task ID": "N/A", "Question": "Environment Error", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
|
| 600 |
+
except (ConnectionError, ValueError) as e: # Catch errors from fetch_questions
|
| 601 |
print(f"DEBUG: ERROR - ConnectionError/ValueError in run_and_submit_all_evaluation: {e}")
|
| 602 |
logger.error(f"Data handling or connection error during evaluation: {e}", exc_info=True)
|
| 603 |
submission_status = str(e)
|
| 604 |
+
if not results_log_data:
|
| 605 |
+
results_log_data = [{"Task ID": "N/A", "Question": "Connection/Value Error", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
|
| 606 |
+
except RuntimeError as e: # Catches issues like agent not initialized properly if it raises RuntimeError from __call__
|
| 607 |
print(f"DEBUG: ERROR - RuntimeError in run_and_submit_all_evaluation: {e}")
|
| 608 |
logger.error(f"Runtime error during evaluation: {e}", exc_info=True)
|
| 609 |
submission_status = f"Runtime Error: {e}"
|
| 610 |
+
if not results_log_data:
|
| 611 |
+
results_log_data = [{"Task ID": "N/A", "Question": "Runtime Error", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
|
| 612 |
+
except Exception as e: # Catch-all for other unexpected errors
|
| 613 |
print(f"DEBUG: ERROR - Unexpected Exception in run_and_submit_all_evaluation: {type(e).__name__} - {e}")
|
| 614 |
logger.error(f"An unexpected error occurred during the evaluation pipeline: {e}", exc_info=True)
|
| 615 |
submission_status = f"An unexpected error occurred: {e}"
|
| 616 |
+
if not results_log_data: # Ensure there's always some data for the DataFrame
|
| 617 |
+
results_log_data = [{"Task ID": "N/A", "Question": "Unexpected Error", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
|
| 618 |
|
| 619 |
+
# Ensure results_df is always created, even if results_log_data is empty after errors
|
| 620 |
results_df = pd.DataFrame(results_log_data if results_log_data else [])
|
| 621 |
print(f"DEBUG: run_and_submit_all_evaluation returning. Status: {submission_status[:100]}...")
|
| 622 |
return submission_status, results_df
|
|
|
|
| 626 |
try:
|
| 627 |
with gr.Blocks(css=".gradio-container {max-width: 960px !important; margin: auto !important;}") as demo:
|
| 628 |
print("DEBUG: gr.Blocks context entered.")
|
| 629 |
+
gr.Markdown("# Chuck's Agent Evaluation Runner (Pydantic AI Version)")
|
| 630 |
gr.Markdown(
|
| 631 |
"""
|
| 632 |
**Instructions:**
|
|
|
|
| 675 |
except Exception as e:
|
| 676 |
print(f"DEBUG: ERROR - Exception during Gradio UI definition: {e}")
|
| 677 |
logger.critical(f"Gradio UI definition failed: {e}", exc_info=True)
|
| 678 |
+
demo = None # Ensure demo is None if UI definition fails
|
| 679 |
|
| 680 |
|
| 681 |
# --- Application Startup & Shutdown Handling ---
|
|
|
|
| 685 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 686 |
space_id_startup, agent_url_startup = get_space_id_agent_code_url()
|
| 687 |
|
| 688 |
+
# MODIFIED Python version reporting
|
| 689 |
+
print(f"Python Version: {'.'.join(map(str, sys.version_info[:3]))}")
|
| 690 |
print(f"Gradio Version: {gr.__version__}")
|
| 691 |
try:
|
| 692 |
+
# Try to import pydantic_ai again here just for version display, if loaded.
|
| 693 |
+
if PYDANTIC_AI_LOADED:
|
| 694 |
+
import pydantic_ai
|
| 695 |
+
print(f"pydantic-ai Version: {pydantic_ai.__version__ if hasattr(pydantic_ai, '__version__') else 'unknown (loaded)'}")
|
| 696 |
+
else:
|
| 697 |
+
print("pydantic-ai could not be imported (version unknown). This is expected if the library has issues or is not installed.")
|
| 698 |
except ImportError:
|
| 699 |
+
print("pydantic-ai could not be imported during version check (version unknown).")
|
| 700 |
|
| 701 |
|
| 702 |
if space_host_startup:
|
|
|
|
| 707 |
|
| 708 |
if space_id_startup:
|
| 709 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 710 |
+
print(f" Repo URL: [https://huggingface.co/spaces/](https://huggingface.co/spaces/){space_id_startup}")
|
| 711 |
print(f" Agent Code URL reported to server: {agent_url_startup}")
|
| 712 |
else:
|
| 713 |
print("ℹ️ SPACE_ID environment variable not found. Repo URL cannot be determined.")
|
|
|
|
| 722 |
|
| 723 |
if demo is not None:
|
| 724 |
try:
|
| 725 |
+
# Set server_name for local development if needed, share=False for typical Space deployment
|
| 726 |
+
demo.launch(debug=True, share=False)
|
| 727 |
except Exception as e:
|
| 728 |
print(f"DEBUG: ERROR - Gradio demo.launch() failed: {e}")
|
| 729 |
logger.critical(f"Gradio demo launch failed: {e}", exc_info=True)
|