pydantic test
Browse files
app.py
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
print("DEBUG: app.py execution started (top of file)")
|
| 2 |
import os
|
| 3 |
print("DEBUG: os imported")
|
| 4 |
-
import sys
|
| 5 |
-
print("DEBUG: sys imported")
|
| 6 |
import gradio as gr
|
| 7 |
print("DEBUG: gradio imported")
|
| 8 |
import requests
|
|
@@ -29,8 +29,9 @@ print("DEBUG: typing and pydantic imported")
|
|
| 29 |
PYDANTIC_AI_LOADED = False
|
| 30 |
try:
|
| 31 |
from pydantic_ai import Agent
|
| 32 |
-
from pydantic_ai.
|
| 33 |
-
from pydantic_ai.
|
|
|
|
| 34 |
print("DEBUG: pydantic-ai components imported successfully.")
|
| 35 |
PYDANTIC_AI_LOADED = True
|
| 36 |
except ImportError as e:
|
|
@@ -45,9 +46,14 @@ except ImportError as e:
|
|
| 45 |
print("DEBUG: Dummy Pydantic AI Agent run called.")
|
| 46 |
logging.error("Dummy Pydantic AI Agent run called.")
|
| 47 |
return "Error: pydantic-ai Agent not loaded."
|
| 48 |
-
class
|
| 49 |
def __init__(self, *args, **kwargs):
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
|
| 53 |
from datetime import datetime
|
|
@@ -56,17 +62,14 @@ print("DEBUG: datetime imported")
|
|
| 56 |
# --- Configuration ---
|
| 57 |
print("DEBUG: Defining AppConfig.")
|
| 58 |
class AppConfig:
|
| 59 |
-
DEFAULT_API_URL = "
|
| 60 |
QUESTIONS_URL_PATH = "/questions"
|
| 61 |
SUBMIT_URL_PATH = "/submit"
|
| 62 |
SCREENSHOTS_DIR = "screenshots"
|
| 63 |
OPENAI_MODEL_ID = "gpt-4-1106-preview" # Using a model known for good function calling
|
| 64 |
SERPER_API_NUM_RESULTS = 3
|
| 65 |
WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
|
| 66 |
-
# AGENT_MAX_STEPS = 10 # Pydantic AI manages loops differently, this might not directly apply
|
| 67 |
-
# AGENT_VERBOSITY_LEVEL = 2 # Pydantic AI logging is configured differently
|
| 68 |
|
| 69 |
-
# MODIFIED: System Prompt for Pydantic AI with OpenAI Function Calling
|
| 70 |
PYDANTIC_AI_SYSTEM_PROMPT = """You are a highly intelligent and meticulous AI assistant.
|
| 71 |
Your primary goal is to answer the user's question accurately and concisely.
|
| 72 |
You have access to tools. If you need to use a tool, you will be provided with its definition.
|
|
@@ -109,8 +112,6 @@ logging.basicConfig(
|
|
| 109 |
level=logging.INFO,
|
| 110 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
| 111 |
logger = logging.getLogger(__name__)
|
| 112 |
-
# For more detailed pydantic-ai logging, you can set its logger level:
|
| 113 |
-
# logging.getLogger("pydantic_ai").setLevel(logging.DEBUG)
|
| 114 |
print("DEBUG: Logging configured.")
|
| 115 |
|
| 116 |
# --- Utility Functions ---
|
|
@@ -123,28 +124,21 @@ ensure_dir_exists(CONFIG.SCREENSHOTS_DIR)
|
|
| 123 |
def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
|
| 124 |
space_id = os.getenv("SPACE_ID")
|
| 125 |
if space_id:
|
| 126 |
-
agent_code_url = f"
|
| 127 |
else:
|
| 128 |
agent_code_url = "Agent code URL not found (SPACE_ID not set)"
|
| 129 |
return space_id, agent_code_url
|
| 130 |
|
| 131 |
print("DEBUG: Utility functions defined.")
|
| 132 |
|
| 133 |
-
|
| 134 |
# --- Tool Definitions for Pydantic AI ---
|
| 135 |
-
# Pydantic AI tools are typically simple functions decorated with @tool
|
| 136 |
-
# or methods of a class.
|
| 137 |
-
|
| 138 |
print("DEBUG: Defining GoogleSearchTool for Pydantic AI.")
|
| 139 |
|
| 140 |
-
|
| 141 |
-
# Pydantic-AI's @tool decorator will handle the description for the LLM.
|
| 142 |
-
|
| 143 |
-
if PYDANTIC_AI_LOADED: # Only define if library is loaded
|
| 144 |
@pydantic_tool(
|
| 145 |
description="Searches the web using Serper API for information. Use this for current events or information not in your knowledge base. Input is the search query."
|
| 146 |
)
|
| 147 |
-
async def web_search(query: str) -> str:
|
| 148 |
print(f"DEBUG: Pydantic AI web_search tool called with query: '{query}'")
|
| 149 |
serper_api_key = os.environ.get('SERPER_API_KEY')
|
| 150 |
if not serper_api_key:
|
|
@@ -152,19 +146,16 @@ if PYDANTIC_AI_LOADED: # Only define if library is loaded
|
|
| 152 |
print("DEBUG: ERROR - SERPER_API_KEY not found.")
|
| 153 |
return "Error: Serper API key not found in environment. Cannot perform web search."
|
| 154 |
|
| 155 |
-
url = "
|
| 156 |
headers = {'X-API-KEY': serper_api_key, 'Content-Type': 'application/json'}
|
| 157 |
payload = json.dumps({'q': query, 'num': CONFIG.SERPER_API_NUM_RESULTS})
|
| 158 |
|
| 159 |
-
# Create session per call to maximize compatibility with event loops
|
| 160 |
async with aiohttp.ClientSession() as session:
|
| 161 |
try:
|
| 162 |
async with session.post(url, headers=headers, data=payload, timeout=aiohttp.ClientTimeout(total=15)) as response:
|
| 163 |
response.raise_for_status()
|
| 164 |
data = await response.json()
|
| 165 |
print(f"DEBUG: web_search tool received data for query '{query}'.")
|
| 166 |
-
|
| 167 |
-
# Formatting results (same as your original _format_results)
|
| 168 |
results = []
|
| 169 |
if 'organic' in data and data['organic']:
|
| 170 |
for result in data['organic'][:CONFIG.SERPER_API_NUM_RESULTS]:
|
|
@@ -179,7 +170,6 @@ if PYDANTIC_AI_LOADED: # Only define if library is loaded
|
|
| 179 |
results.append(f"Knowledge Graph: {title}\n{description}\n---")
|
| 180 |
formatted_output = "\n".join(results) if results else "No relevant search results found."
|
| 181 |
return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
|
| 182 |
-
|
| 183 |
except asyncio.TimeoutError:
|
| 184 |
logger.error(f"Timeout performing search for '{query}'")
|
| 185 |
print(f"DEBUG: ERROR - Timeout in web_search tool for query '{query}'.")
|
|
@@ -196,20 +186,13 @@ if PYDANTIC_AI_LOADED: # Only define if library is loaded
|
|
| 196 |
logger.error(f"Unexpected error performing search for '{query}': {type(e).__name__} - {str(e)}", exc_info=True)
|
| 197 |
print(f"DEBUG: ERROR - Unexpected error in web_search tool for query '{query}': {str(e)}.")
|
| 198 |
return f"Error performing search: An unexpected error occurred."
|
| 199 |
-
else:
|
| 200 |
async def web_search(query: str) -> str:
|
| 201 |
return "Error: pydantic-ai not loaded, web_search tool unavailable."
|
| 202 |
|
| 203 |
-
# --- Pydantic AI Agent Definition ---
|
| 204 |
print("DEBUG: Defining PydanticQuestionAnsweringAgent (conceptual).")
|
| 205 |
-
|
| 206 |
-
# With Pydantic AI, we don't typically subclass Agent for this kind of use case.
|
| 207 |
-
# We instantiate it and provide it with an LLM, tools, and a system prompt.
|
| 208 |
-
# The 'QuestionAnsweringAgent' class is effectively replaced by an instance of pydantic_ai.Agent
|
| 209 |
-
# The logic for process_question will be part of ChuckAgent's interaction with the pydantic_ai.Agent
|
| 210 |
-
|
| 211 |
-
# --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
|
| 212 |
print("DEBUG: Defining ChuckAgent (modified for Pydantic AI).")
|
|
|
|
| 213 |
class ChuckAgent:
|
| 214 |
def __init__(self):
|
| 215 |
print("DEBUG: ChuckAgent.__init__ called.")
|
|
@@ -223,10 +206,9 @@ class ChuckAgent:
|
|
| 223 |
raise EnvironmentError(error_msg)
|
| 224 |
print("DEBUG: ChuckAgent environment variables checked.")
|
| 225 |
|
| 226 |
-
self.agent_instance: Optional[Agent] = None
|
| 227 |
-
self.llm_for_fallback: Optional[
|
| 228 |
|
| 229 |
-
# Event loop management for running async pydantic-ai agent from sync Gradio
|
| 230 |
try:
|
| 231 |
self.loop = asyncio.get_running_loop()
|
| 232 |
print(f"DEBUG: ChuckAgent obtained running event loop: {self.loop}")
|
|
@@ -235,10 +217,6 @@ class ChuckAgent:
|
|
| 235 |
self.loop = asyncio.new_event_loop()
|
| 236 |
asyncio.set_event_loop(self.loop)
|
| 237 |
print(f"DEBUG: ChuckAgent using event loop: {self.loop}")
|
| 238 |
-
|
| 239 |
-
# aiohttp.ClientSession is no longer managed by ChuckAgent directly for the search tool,
|
| 240 |
-
# as each tool call will create its own.
|
| 241 |
-
# self.http_session = None # Removed
|
| 242 |
|
| 243 |
logger.info("ChuckAgent basic initialization complete. Pydantic AI Agent will be created on first use.")
|
| 244 |
print("DEBUG: ChuckAgent basic initialization complete (Pydantic AI version).")
|
|
@@ -250,43 +228,38 @@ class ChuckAgent:
|
|
| 250 |
logger.info("Initializing Pydantic AI Agent within ChuckAgent...")
|
| 251 |
try:
|
| 252 |
openai_api_key = os.environ.get('OPENAI_API_KEY')
|
| 253 |
-
#
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
)
|
| 259 |
-
self.llm_for_fallback = llm
|
| 260 |
|
| 261 |
-
# Instantiate Pydantic AI Agent
|
| 262 |
self.agent_instance = Agent(
|
| 263 |
llm=llm,
|
| 264 |
-
tools=[web_search],
|
| 265 |
system_prompt=CONFIG.PYDANTIC_AI_SYSTEM_PROMPT,
|
| 266 |
-
debug=True
|
| 267 |
)
|
| 268 |
print("DEBUG: ChuckAgent - Pydantic AI Agent initialized successfully.")
|
| 269 |
logger.info("Pydantic AI Agent initialized successfully.")
|
| 270 |
except Exception as e:
|
| 271 |
print(f"DEBUG: ERROR - ChuckAgent failed to initialize Pydantic AI Agent: {type(e).__name__} - {e}")
|
| 272 |
logger.error(f"Failed to initialize Pydantic AI Agent: {e}", exc_info=True)
|
| 273 |
-
raise
|
| 274 |
elif not PYDANTIC_AI_LOADED:
|
| 275 |
print("DEBUG: ERROR - Pydantic AI library not loaded, cannot initialize agent.")
|
| 276 |
logger.error("Pydantic AI library not loaded, cannot initialize agent.")
|
| 277 |
-
|
| 278 |
-
# but it won't be functional.
|
| 279 |
-
self.agent_instance = Agent() # This will be the dummy agent
|
| 280 |
else:
|
| 281 |
print("DEBUG: ChuckAgent - Pydantic AI Agent already initialized.")
|
| 282 |
|
| 283 |
-
# This method replaces the old QuestionAnsweringAgent.process_question
|
| 284 |
async def _process_question_async(self, question_text: str) -> Tuple[str, str]:
|
| 285 |
print(f"DEBUG: ChuckAgent._process_question_async called for: '{question_text[:100]}...'")
|
| 286 |
reasoning_trace = "Pydantic AI Agent execution started."
|
| 287 |
final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
|
| 288 |
|
| 289 |
-
# Ensure agent is initialized; this should ideally be guaranteed by _ensure_agent_initialized
|
| 290 |
if self.agent_instance is None or (not PYDANTIC_AI_LOADED and isinstance(self.agent_instance, globals().get('Agent'))):
|
| 291 |
logger.error("Pydantic AI Agent instance not available or is a dummy placeholder.")
|
| 292 |
print("DEBUG: ERROR - Pydantic AI Agent instance not available in _process_question_async.")
|
|
@@ -294,74 +267,65 @@ class ChuckAgent:
|
|
| 294 |
|
| 295 |
try:
|
| 296 |
agent_final_text_output = await self.agent_instance.run(question_text)
|
| 297 |
-
reasoning_trace = str(agent_final_text_output)
|
| 298 |
|
| 299 |
print(f"DEBUG: Pydantic AI Agent raw output (first 500 chars): {reasoning_trace[:500]}")
|
| 300 |
-
|
| 301 |
match = re.search(r"FINAL ANSWER:\s*(.*)", reasoning_trace, re.IGNORECASE | re.DOTALL)
|
| 302 |
|
| 303 |
if match:
|
| 304 |
final_answer_for_submission = match.group(1).strip()
|
| 305 |
print(f"DEBUG: Pydantic AI Agent extracted FINAL ANSWER: '{final_answer_for_submission}'")
|
| 306 |
-
elif PYDANTIC_AI_LOADED and self.llm_for_fallback:
|
| 307 |
logger.warning("Could not find 'FINAL ANSWER:' in Pydantic AI Agent's output. Attempting LLM summarization fallback.")
|
| 308 |
print("DEBUG: WARNING - Pydantic AI Agent - Could not find 'FINAL ANSWER:'. Initiating LLM summarization fallback.")
|
| 309 |
-
|
| 310 |
summarizer_messages = [
|
| 311 |
{"role": "system", "content": CONFIG.SUMMARIZER_SYSTEM_PROMPT},
|
| 312 |
{"role": "user", "content": f"Original Question: {question_text}\n\nAgent's Full Output Log:\n{reasoning_trace}\n\nBased on the 'Agent's Full Output 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. If a clear answer cannot be determined, output 'Could not determine answer from reasoning.'"}
|
| 313 |
]
|
| 314 |
print(f"DEBUG: Summarizer LLM call with messages (user message snippet): {summarizer_messages[1]['content'][:200]}...")
|
| 315 |
try:
|
| 316 |
-
from openai import OpenAI as OfficialOpenAIClient
|
| 317 |
client = OfficialOpenAIClient(api_key=os.environ.get('OPENAI_API_KEY'))
|
| 318 |
response = client.chat.completions.create(
|
| 319 |
-
model=CONFIG.OPENAI_MODEL_ID,
|
| 320 |
messages=summarizer_messages,
|
| 321 |
temperature=0.0
|
| 322 |
)
|
| 323 |
concise_answer = response.choices[0].message.content.strip()
|
| 324 |
-
|
| 325 |
if concise_answer:
|
| 326 |
if "Could not determine answer from reasoning." in concise_answer:
|
| 327 |
print(f"DEBUG: LLM summarization fallback indicated no clear answer. Using placeholder.")
|
| 328 |
-
final_answer_for_submission = "Could not determine answer."
|
| 329 |
else:
|
| 330 |
final_answer_for_submission = concise_answer
|
| 331 |
print(f"DEBUG: LLM summarization fallback successful. Concise answer: '{final_answer_for_submission}'")
|
| 332 |
else:
|
| 333 |
print("DEBUG: ERROR - LLM summarization fallback returned empty. Using full agent output.")
|
| 334 |
-
final_answer_for_submission = reasoning_trace.strip()
|
| 335 |
except Exception as e_summary:
|
| 336 |
print(f"DEBUG: ERROR - Exception during LLM summarization fallback: {type(e_summary).__name__} - {str(e_summary)}. Using full agent output.")
|
| 337 |
logger.error(f"Exception during LLM summarization fallback: {e_summary}.", exc_info=True)
|
| 338 |
-
final_answer_for_submission = reasoning_trace.strip()
|
| 339 |
-
else:
|
| 340 |
logger.warning("Could not find 'FINAL ANSWER:' and no LLM fallback possible/applicable. Using agent's full output.")
|
| 341 |
-
final_answer_for_submission = reasoning_trace.strip()
|
| 342 |
|
| 343 |
-
|
| 344 |
-
if not final_answer_for_submission: # Should be rare if reasoning_trace is used as fallback
|
| 345 |
final_answer_for_submission = "Could not determine answer."
|
| 346 |
-
|
| 347 |
except Exception as e:
|
| 348 |
error_msg = f"Error processing question with Pydantic AI Agent: {type(e).__name__} - {str(e)}"
|
| 349 |
print(f"DEBUG: ERROR - {error_msg}")
|
| 350 |
logger.error(error_msg, exc_info=True)
|
| 351 |
final_answer_for_submission = f"Error in Pydantic AI agent processing: {str(e)}"
|
| 352 |
reasoning_trace += f"\nError encountered during processing: {str(e)}"
|
| 353 |
-
|
| 354 |
return final_answer_for_submission, reasoning_trace
|
| 355 |
|
| 356 |
def __call__(self, question: str) -> Tuple[str, str]:
|
| 357 |
print(f"DEBUG: ChuckAgent.__call__ received question: '{question[:50]}...' (Pydantic AI version)")
|
| 358 |
try:
|
| 359 |
-
self._ensure_agent_initialized()
|
| 360 |
-
|
| 361 |
-
# Critical check if agent is usable
|
| 362 |
if self.agent_instance is None or \
|
| 363 |
(not PYDANTIC_AI_LOADED and isinstance(self.agent_instance, globals().get('Agent'))):
|
| 364 |
-
# globals().get('Agent') refers to the dummy Agent if PYDANTIC_AI_LOADED is False
|
| 365 |
error_message = "Pydantic AI Agent was not initialized or is a dummy placeholder due to missing 'pydantic-ai' library."
|
| 366 |
print(f"DEBUG: ERROR - ChuckAgent.__call__ {error_message}")
|
| 367 |
raise RuntimeError(error_message)
|
|
@@ -373,9 +337,7 @@ class ChuckAgent:
|
|
| 373 |
else:
|
| 374 |
future = asyncio.run_coroutine_threadsafe(self._process_question_async(question), self.loop)
|
| 375 |
print(f"DEBUG: ChuckAgent waiting for future.result() for question: '{question[:50]}...'")
|
| 376 |
-
|
| 377 |
-
final_answer, reasoning_trace = future.result(timeout=300)
|
| 378 |
-
|
| 379 |
print(f"DEBUG: ChuckAgent future.result() obtained. Answer: '{final_answer[:50]}...'")
|
| 380 |
logger.info(f"ChuckAgent returning answer (first 50 chars): '{final_answer[:50]}...'")
|
| 381 |
return final_answer, reasoning_trace
|
|
@@ -388,7 +350,6 @@ class ChuckAgent:
|
|
| 388 |
async def shutdown_async(self):
|
| 389 |
print("DEBUG: ChuckAgent.shutdown_async called (Pydantic AI version).")
|
| 390 |
logger.info("ChuckAgent async shutdown initiated (Pydantic AI version).")
|
| 391 |
-
# No explicit http_session to close here at ChuckAgent level for the search tool
|
| 392 |
logger.info("ChuckAgent async shutdown complete (Pydantic AI version).")
|
| 393 |
print("DEBUG: ChuckAgent async shutdown complete (Pydantic AI version).")
|
| 394 |
|
|
@@ -396,10 +357,9 @@ class ChuckAgent:
|
|
| 396 |
print("DEBUG: ChuckAgent.close called (Pydantic AI version).")
|
| 397 |
if self.loop and self.loop.is_running():
|
| 398 |
print("DEBUG: ChuckAgent.close - loop is running, scheduling async_shutdown.")
|
| 399 |
-
# Ensure the future is awaited or handled properly, especially if called from non-async context
|
| 400 |
future = asyncio.run_coroutine_threadsafe(self.shutdown_async(), self.loop)
|
| 401 |
try:
|
| 402 |
-
future.result(timeout=10)
|
| 403 |
except asyncio.TimeoutError:
|
| 404 |
logger.warning("Timeout waiting for ChuckAgent async_shutdown to complete.")
|
| 405 |
except Exception as e:
|
|
@@ -416,8 +376,6 @@ class ChuckAgent:
|
|
| 416 |
|
| 417 |
print("DEBUG: ChuckAgent class defined (Pydantic AI version).")
|
| 418 |
|
| 419 |
-
|
| 420 |
-
# --- Orchestration Functions (fetch_questions, process_all_questions, submit_answers) ---
|
| 421 |
def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
|
| 422 |
print(f"DEBUG: fetch_questions called with base_api_url: {base_api_url}")
|
| 423 |
questions_url = f"{base_api_url}{CONFIG.QUESTIONS_URL_PATH}"
|
|
@@ -436,7 +394,7 @@ def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
|
|
| 436 |
print(f"DEBUG: ERROR - Error fetching questions: {e}")
|
| 437 |
logger.error(f"Error fetching questions: {e}", exc_info=True)
|
| 438 |
raise ConnectionError(f"Error fetching questions: {e}")
|
| 439 |
-
except requests.exceptions.JSONDecodeError as e:
|
| 440 |
print(f"DEBUG: ERROR - Error decoding questions JSON: {e}")
|
| 441 |
logger.error(f"Error decoding questions JSON: {e}. Response: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True)
|
| 442 |
raise ValueError(f"Error decoding server response for questions: {e}")
|
|
@@ -448,23 +406,22 @@ def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]
|
|
| 448 |
for i, item in enumerate(questions_data):
|
| 449 |
task_id = item.get("task_id")
|
| 450 |
question_text = item.get("question")
|
| 451 |
-
if not task_id or question_text is None:
|
| 452 |
logger.warning(f"Skipping item with missing task_id or question: {item}")
|
| 453 |
continue
|
| 454 |
print(f"DEBUG: Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
|
| 455 |
try:
|
| 456 |
-
model_ans, reasoning = agent(question_text)
|
| 457 |
payload_item = {"task_id": task_id, "submitted_answer": model_ans}
|
| 458 |
if reasoning:
|
| 459 |
payload_item["reasoning_trace"] = reasoning
|
| 460 |
answers_payload.append(payload_item)
|
| 461 |
-
|
| 462 |
results_log_data.append({
|
| 463 |
"Task ID": task_id, "Question": question_text,
|
| 464 |
"Submitted Answer": model_ans,
|
| 465 |
"Reasoning Trace": reasoning
|
| 466 |
})
|
| 467 |
-
except Exception as e:
|
| 468 |
print(f"DEBUG: ERROR - Error running agent on task {task_id}: {e}")
|
| 469 |
logger.error(f"Error running agent on task {task_id} ('{question_text[:50]}...'): {e}", exc_info=True)
|
| 470 |
error_answer = f"AGENT_CALL_ERROR: {str(e)}"
|
|
@@ -480,10 +437,8 @@ def submit_answers(base_api_url: str, username: str, agent_code_url: str, answer
|
|
| 480 |
return "Agent did not produce any answers to submit."
|
| 481 |
submit_url = f"{base_api_url}{CONFIG.SUBMIT_URL_PATH}"
|
| 482 |
submission_data = {"username": username.strip(), "agent_code": agent_code_url, "answers": answers_payload}
|
| 483 |
-
|
| 484 |
if answers_payload:
|
| 485 |
print(f"DEBUG: Sample of first answer payload being sent: {answers_payload[0]}")
|
| 486 |
-
|
| 487 |
logger.info(f"Submitting {len(answers_payload)} answers for user '{username}' to {submit_url}...")
|
| 488 |
try:
|
| 489 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
|
@@ -505,17 +460,14 @@ def submit_answers(base_api_url: str, username: str, agent_code_url: str, answer
|
|
| 505 |
final_status = "Submission Failed: The request timed out."; logger.error(final_status)
|
| 506 |
except requests.exceptions.RequestException as e:
|
| 507 |
final_status = f"Submission Failed: Network error - {e}"; logger.error(final_status, exc_info=True)
|
| 508 |
-
except Exception as e:
|
| 509 |
final_status = f"An unexpected error occurred during submission: {e}"; logger.error(final_status, exc_info=True)
|
| 510 |
print(f"DEBUG: submit_answers final_status: {final_status}")
|
| 511 |
return final_status
|
| 512 |
|
| 513 |
-
|
| 514 |
-
# --- Gradio Interface and Main Execution Logic ---
|
| 515 |
GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
|
| 516 |
|
| 517 |
print("DEBUG: Defining run_and_submit_all_evaluation function.")
|
| 518 |
-
# MODIFIED run_and_submit_all_evaluation function
|
| 519 |
def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
|
| 520 |
global GLOBAL_CHUCK_AGENT
|
| 521 |
print(f"DEBUG: run_and_submit_all_evaluation called. Profile type: {type(profile)}")
|
|
@@ -531,7 +483,6 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
|
|
| 531 |
effective_profile = arg_val
|
| 532 |
logger.info(f"Found gr.OAuthProfile in *args: {effective_profile.username if effective_profile else 'None (from args)'}")
|
| 533 |
break
|
| 534 |
-
|
| 535 |
if not effective_profile:
|
| 536 |
logger.warning("User not logged in or profile not correctly passed for evaluation.")
|
| 537 |
print("DEBUG: ERROR - User not logged in or profile not correctly passed for evaluation.")
|
|
@@ -542,17 +493,16 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
|
|
| 542 |
print(f"DEBUG: User logged in: {username}")
|
| 543 |
|
| 544 |
_, agent_code_url = get_space_id_agent_code_url()
|
| 545 |
-
results_log_data: List[Dict[str, Any]] = []
|
| 546 |
|
| 547 |
try:
|
| 548 |
-
#
|
| 549 |
-
|
| 550 |
-
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."
|
| 551 |
print(f"DEBUG: {error_msg}")
|
| 552 |
logger.critical(error_msg)
|
| 553 |
-
error_df_data = [{"Task ID": "N/A",
|
| 554 |
-
"Question": "Critical Dependency Error",
|
| 555 |
-
"Submitted Answer": "pydantic-ai
|
| 556 |
"Reasoning Trace": error_msg}]
|
| 557 |
return error_msg, pd.DataFrame(error_df_data)
|
| 558 |
|
|
@@ -560,72 +510,65 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
|
|
| 560 |
if GLOBAL_CHUCK_AGENT is None:
|
| 561 |
print("DEBUG: GLOBAL_CHUCK_AGENT is None. Creating new instance (Pydantic AI version).")
|
| 562 |
logger.info("GLOBAL_CHUCK_AGENT is None. Attempting to create a new instance (Pydantic AI version).")
|
| 563 |
-
GLOBAL_CHUCK_AGENT = ChuckAgent()
|
| 564 |
print("DEBUG: GLOBAL_CHUCK_AGENT new instance created.")
|
| 565 |
else:
|
| 566 |
print("DEBUG: GLOBAL_CHUCK_AGENT already exists.")
|
| 567 |
agent_instance = GLOBAL_CHUCK_AGENT
|
| 568 |
-
|
| 569 |
print("DEBUG: run_and_submit_all_evaluation - Ensuring agent_instance._ensure_agent_initialized().")
|
| 570 |
-
agent_instance._ensure_agent_initialized()
|
| 571 |
print("DEBUG: run_and_submit_all_evaluation - Agent ensured to be initialized.")
|
| 572 |
-
|
| 573 |
-
# This secondary check is mostly redundant due to the PYDANTIC_AI_LOADED check above
|
| 574 |
-
# and error handling within ChuckAgent.__call__ but kept for belt-and-suspenders.
|
| 575 |
if agent_instance.agent_instance is None or \
|
| 576 |
-
(not PYDANTIC_AI_LOADED and isinstance(agent_instance.agent_instance, globals().get('Agent'))):
|
| 577 |
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."
|
| 578 |
logger.critical(critical_error_msg)
|
| 579 |
print(f"DEBUG: CRITICAL - {critical_error_msg}")
|
| 580 |
-
# Create a DataFrame for the error message
|
| 581 |
error_df_data = [{"Task ID": "N/A",
|
| 582 |
"Question": "Agent Initialization Error",
|
| 583 |
"Submitted Answer": "Init Failed",
|
| 584 |
"Reasoning Trace": critical_error_msg}]
|
| 585 |
return critical_error_msg, pd.DataFrame(error_df_data)
|
| 586 |
|
| 587 |
-
|
| 588 |
questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
|
| 589 |
answers_payload, results_log_data_processed = process_all_questions(agent_instance, questions_data)
|
| 590 |
-
results_log_data.extend(results_log_data_processed)
|
| 591 |
submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload)
|
| 592 |
-
|
| 593 |
except EnvironmentError as e:
|
| 594 |
print(f"DEBUG: ERROR - EnvironmentError in run_and_submit_all_evaluation: {e}")
|
| 595 |
logger.critical(f"Agent instantiation or operation failed due to missing env vars: {e}")
|
| 596 |
submission_status = f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets."
|
| 597 |
-
if not results_log_data:
|
| 598 |
results_log_data = [{"Task ID": "N/A", "Question": "Environment Error", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
|
| 599 |
-
except (ConnectionError, ValueError) as e:
|
| 600 |
print(f"DEBUG: ERROR - ConnectionError/ValueError in run_and_submit_all_evaluation: {e}")
|
| 601 |
logger.error(f"Data handling or connection error during evaluation: {e}", exc_info=True)
|
| 602 |
submission_status = str(e)
|
| 603 |
if not results_log_data:
|
| 604 |
results_log_data = [{"Task ID": "N/A", "Question": "Connection/Value Error", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
|
| 605 |
-
except RuntimeError as e:
|
| 606 |
print(f"DEBUG: ERROR - RuntimeError in run_and_submit_all_evaluation: {e}")
|
| 607 |
logger.error(f"Runtime error during evaluation: {e}", exc_info=True)
|
| 608 |
submission_status = f"Runtime Error: {e}"
|
| 609 |
if not results_log_data:
|
| 610 |
results_log_data = [{"Task ID": "N/A", "Question": "Runtime Error", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
|
| 611 |
-
except Exception as e:
|
| 612 |
print(f"DEBUG: ERROR - Unexpected Exception in run_and_submit_all_evaluation: {type(e).__name__} - {e}")
|
| 613 |
logger.error(f"An unexpected error occurred during the evaluation pipeline: {e}", exc_info=True)
|
| 614 |
submission_status = f"An unexpected error occurred: {e}"
|
| 615 |
-
if not results_log_data:
|
| 616 |
results_log_data = [{"Task ID": "N/A", "Question": "Unexpected Error", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
|
| 617 |
|
| 618 |
-
# Ensure results_df is always created, even if results_log_data is empty after errors
|
| 619 |
results_df = pd.DataFrame(results_log_data if results_log_data else [])
|
| 620 |
print(f"DEBUG: run_and_submit_all_evaluation returning. Status: {submission_status[:100]}...")
|
| 621 |
return submission_status, results_df
|
| 622 |
|
| 623 |
-
|
| 624 |
print("DEBUG: Building Gradio interface.")
|
| 625 |
try:
|
| 626 |
with gr.Blocks(css=".gradio-container {max-width: 960px !important; margin: auto !important;}") as demo:
|
| 627 |
print("DEBUG: gr.Blocks context entered.")
|
| 628 |
-
gr.Markdown("# Chuck's Agent Evaluation Runner (Pydantic AI Version)")
|
| 629 |
gr.Markdown(
|
| 630 |
"""
|
| 631 |
**Instructions:**
|
|
@@ -653,17 +596,14 @@ try:
|
|
| 653 |
"""
|
| 654 |
)
|
| 655 |
print("DEBUG: Gradio Markdown elements created.")
|
| 656 |
-
|
| 657 |
login_button = gr.LoginButton()
|
| 658 |
print("DEBUG: Gradio LoginButton created.")
|
| 659 |
run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
|
| 660 |
print("DEBUG: Gradio Run Button created.")
|
| 661 |
-
|
| 662 |
with gr.Column():
|
| 663 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=8, interactive=False, show_copy_button=True)
|
| 664 |
results_table = gr.DataFrame(label="Detailed Results: Questions and Agent Answers", wrap=True)
|
| 665 |
print("DEBUG: Gradio output elements (Textbox, DataFrame) created.")
|
| 666 |
-
|
| 667 |
run_button.click(
|
| 668 |
fn=run_and_submit_all_evaluation,
|
| 669 |
inputs=[login_button],
|
|
@@ -674,55 +614,44 @@ try:
|
|
| 674 |
except Exception as e:
|
| 675 |
print(f"DEBUG: ERROR - Exception during Gradio UI definition: {e}")
|
| 676 |
logger.critical(f"Gradio UI definition failed: {e}", exc_info=True)
|
| 677 |
-
demo = None
|
| 678 |
-
|
| 679 |
|
| 680 |
-
# --- Application Startup & Shutdown Handling ---
|
| 681 |
if __name__ == "__main__":
|
| 682 |
print("\n" + "="*15 + " Application Startup (Pydantic AI) " + "="*15)
|
| 683 |
-
|
| 684 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 685 |
space_id_startup, agent_url_startup = get_space_id_agent_code_url()
|
| 686 |
-
|
| 687 |
-
# MODIFIED Python version reporting
|
| 688 |
print(f"Python Version: {'.'.join(map(str, sys.version_info[:3]))}")
|
| 689 |
print(f"Gradio Version: {gr.__version__}")
|
| 690 |
try:
|
| 691 |
-
# Try to import pydantic_ai again here just for version display, if loaded.
|
| 692 |
if PYDANTIC_AI_LOADED:
|
| 693 |
-
import pydantic_ai
|
| 694 |
print(f"pydantic-ai Version: {pydantic_ai.__version__ if hasattr(pydantic_ai, '__version__') else 'unknown (loaded)'}")
|
| 695 |
else:
|
| 696 |
print("pydantic-ai could not be imported (version unknown). This is expected if the library has issues or is not installed.")
|
| 697 |
except ImportError:
|
| 698 |
print("pydantic-ai could not be imported during version check (version unknown).")
|
| 699 |
|
| 700 |
-
|
| 701 |
if space_host_startup:
|
| 702 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 703 |
print(f" Runtime URL might be: https://{space_host_startup}")
|
| 704 |
else:
|
| 705 |
print("ℹ️ SPACE_HOST environment variable not found (likely running locally).")
|
| 706 |
-
|
| 707 |
if space_id_startup:
|
| 708 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 709 |
-
print(f" Repo URL:
|
| 710 |
print(f" Agent Code URL reported to server: {agent_url_startup}")
|
| 711 |
else:
|
| 712 |
print("ℹ️ SPACE_ID environment variable not found. Repo URL cannot be determined.")
|
| 713 |
-
|
| 714 |
print(f" Default API URL for scoring: {CONFIG.DEFAULT_API_URL}")
|
| 715 |
print(f" OpenAI Model ID for Agent: {CONFIG.OPENAI_MODEL_ID}")
|
| 716 |
print("="* (30 + len(" Application Startup (Pydantic AI) ")) + "\n")
|
| 717 |
-
|
| 718 |
print("Launching Gradio Interface for Chuck Agent Evaluation (Pydantic AI Version)...")
|
| 719 |
print("Please ensure OPENAI_API_KEY and SERPER_API_KEY are set in your environment or Space Secrets.")
|
| 720 |
print("Ensure pydantic-ai and openai>=1.3.0 are in requirements.txt.")
|
| 721 |
|
| 722 |
if demo is not None:
|
| 723 |
try:
|
| 724 |
-
|
| 725 |
-
demo.launch(debug=True, share=False)
|
| 726 |
except Exception as e:
|
| 727 |
print(f"DEBUG: ERROR - Gradio demo.launch() failed: {e}")
|
| 728 |
logger.critical(f"Gradio demo launch failed: {e}", exc_info=True)
|
|
@@ -743,7 +672,6 @@ if __name__ == "__main__":
|
|
| 743 |
print("DEBUG: No GLOBAL_CHUCK_AGENT instance to shutdown.")
|
| 744 |
else:
|
| 745 |
print("DEBUG: ERROR - Gradio demo object is None, cannot launch. Check for errors during UI definition.")
|
| 746 |
-
|
| 747 |
print("\n" + "="*15 + " Application Shutdown (Pydantic AI) " + "="*15)
|
| 748 |
else:
|
| 749 |
print("DEBUG: Script is being imported, not run as main.")
|
|
|
|
| 1 |
print("DEBUG: app.py execution started (top of file)")
|
| 2 |
import os
|
| 3 |
print("DEBUG: os imported")
|
| 4 |
+
import sys
|
| 5 |
+
print("DEBUG: sys imported")
|
| 6 |
import gradio as gr
|
| 7 |
print("DEBUG: gradio imported")
|
| 8 |
import requests
|
|
|
|
| 29 |
PYDANTIC_AI_LOADED = False
|
| 30 |
try:
|
| 31 |
from pydantic_ai import Agent
|
| 32 |
+
from pydantic_ai.models.openai import OpenAIModel # MODIFIED import
|
| 33 |
+
from pydantic_ai.providers.openai import OpenAIProvider # ADDED import
|
| 34 |
+
from pydantic_ai.tools import tool as pydantic_tool
|
| 35 |
print("DEBUG: pydantic-ai components imported successfully.")
|
| 36 |
PYDANTIC_AI_LOADED = True
|
| 37 |
except ImportError as e:
|
|
|
|
| 46 |
print("DEBUG: Dummy Pydantic AI Agent run called.")
|
| 47 |
logging.error("Dummy Pydantic AI Agent run called.")
|
| 48 |
return "Error: pydantic-ai Agent not loaded."
|
| 49 |
+
class OpenAIModel: # MODIFIED DUMMY to match new class name
|
| 50 |
def __init__(self, *args, **kwargs):
|
| 51 |
+
print("DEBUG: Dummy Pydantic AI OpenAIModel initialized.")
|
| 52 |
+
logging.error("Dummy Pydantic AI OpenAIModel initialized.")
|
| 53 |
+
class OpenAIProvider: # ADDED DUMMY
|
| 54 |
+
def __init__(self, *args, **kwargs):
|
| 55 |
+
print("DEBUG: Dummy Pydantic AI OpenAIProvider initialized.")
|
| 56 |
+
logging.error("Dummy Pydantic AI OpenAIProvider initialized.")
|
| 57 |
|
| 58 |
|
| 59 |
from datetime import datetime
|
|
|
|
| 62 |
# --- Configuration ---
|
| 63 |
print("DEBUG: Defining AppConfig.")
|
| 64 |
class AppConfig:
|
| 65 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 66 |
QUESTIONS_URL_PATH = "/questions"
|
| 67 |
SUBMIT_URL_PATH = "/submit"
|
| 68 |
SCREENSHOTS_DIR = "screenshots"
|
| 69 |
OPENAI_MODEL_ID = "gpt-4-1106-preview" # Using a model known for good function calling
|
| 70 |
SERPER_API_NUM_RESULTS = 3
|
| 71 |
WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
|
|
|
|
|
|
|
| 72 |
|
|
|
|
| 73 |
PYDANTIC_AI_SYSTEM_PROMPT = """You are a highly intelligent and meticulous AI assistant.
|
| 74 |
Your primary goal is to answer the user's question accurately and concisely.
|
| 75 |
You have access to tools. If you need to use a tool, you will be provided with its definition.
|
|
|
|
| 112 |
level=logging.INFO,
|
| 113 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
| 114 |
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
| 115 |
print("DEBUG: Logging configured.")
|
| 116 |
|
| 117 |
# --- Utility Functions ---
|
|
|
|
| 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/{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
|
| 131 |
|
| 132 |
print("DEBUG: Utility functions defined.")
|
| 133 |
|
|
|
|
| 134 |
# --- Tool Definitions for Pydantic AI ---
|
|
|
|
|
|
|
|
|
|
| 135 |
print("DEBUG: Defining GoogleSearchTool for Pydantic AI.")
|
| 136 |
|
| 137 |
+
if PYDANTIC_AI_LOADED:
|
|
|
|
|
|
|
|
|
|
| 138 |
@pydantic_tool(
|
| 139 |
description="Searches the web using Serper API for information. Use this for current events or information not in your knowledge base. Input is the search query."
|
| 140 |
)
|
| 141 |
+
async def web_search(query: str) -> str:
|
| 142 |
print(f"DEBUG: Pydantic AI web_search tool called with query: '{query}'")
|
| 143 |
serper_api_key = os.environ.get('SERPER_API_KEY')
|
| 144 |
if not serper_api_key:
|
|
|
|
| 146 |
print("DEBUG: ERROR - SERPER_API_KEY not found.")
|
| 147 |
return "Error: Serper API key not found in environment. Cannot perform web search."
|
| 148 |
|
| 149 |
+
url = "https://google.serper.dev/search"
|
| 150 |
headers = {'X-API-KEY': serper_api_key, 'Content-Type': 'application/json'}
|
| 151 |
payload = json.dumps({'q': query, 'num': CONFIG.SERPER_API_NUM_RESULTS})
|
| 152 |
|
|
|
|
| 153 |
async with aiohttp.ClientSession() as session:
|
| 154 |
try:
|
| 155 |
async with session.post(url, headers=headers, data=payload, timeout=aiohttp.ClientTimeout(total=15)) as response:
|
| 156 |
response.raise_for_status()
|
| 157 |
data = await response.json()
|
| 158 |
print(f"DEBUG: web_search tool received data for query '{query}'.")
|
|
|
|
|
|
|
| 159 |
results = []
|
| 160 |
if 'organic' in data and data['organic']:
|
| 161 |
for result in data['organic'][:CONFIG.SERPER_API_NUM_RESULTS]:
|
|
|
|
| 170 |
results.append(f"Knowledge Graph: {title}\n{description}\n---")
|
| 171 |
formatted_output = "\n".join(results) if results else "No relevant search results found."
|
| 172 |
return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
|
|
|
|
| 173 |
except asyncio.TimeoutError:
|
| 174 |
logger.error(f"Timeout performing search for '{query}'")
|
| 175 |
print(f"DEBUG: ERROR - Timeout in web_search tool for query '{query}'.")
|
|
|
|
| 186 |
logger.error(f"Unexpected error performing search for '{query}': {type(e).__name__} - {str(e)}", exc_info=True)
|
| 187 |
print(f"DEBUG: ERROR - Unexpected error in web_search tool for query '{query}': {str(e)}.")
|
| 188 |
return f"Error performing search: An unexpected error occurred."
|
| 189 |
+
else:
|
| 190 |
async def web_search(query: str) -> str:
|
| 191 |
return "Error: pydantic-ai not loaded, web_search tool unavailable."
|
| 192 |
|
|
|
|
| 193 |
print("DEBUG: Defining PydanticQuestionAnsweringAgent (conceptual).")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
print("DEBUG: Defining ChuckAgent (modified for Pydantic AI).")
|
| 195 |
+
|
| 196 |
class ChuckAgent:
|
| 197 |
def __init__(self):
|
| 198 |
print("DEBUG: ChuckAgent.__init__ called.")
|
|
|
|
| 206 |
raise EnvironmentError(error_msg)
|
| 207 |
print("DEBUG: ChuckAgent environment variables checked.")
|
| 208 |
|
| 209 |
+
self.agent_instance: Optional[Agent] = None
|
| 210 |
+
self.llm_for_fallback: Optional[OpenAIModel] = None # MODIFIED type hint
|
| 211 |
|
|
|
|
| 212 |
try:
|
| 213 |
self.loop = asyncio.get_running_loop()
|
| 214 |
print(f"DEBUG: ChuckAgent obtained running event loop: {self.loop}")
|
|
|
|
| 217 |
self.loop = asyncio.new_event_loop()
|
| 218 |
asyncio.set_event_loop(self.loop)
|
| 219 |
print(f"DEBUG: ChuckAgent using event loop: {self.loop}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
|
| 221 |
logger.info("ChuckAgent basic initialization complete. Pydantic AI Agent will be created on first use.")
|
| 222 |
print("DEBUG: ChuckAgent basic initialization complete (Pydantic AI version).")
|
|
|
|
| 228 |
logger.info("Initializing Pydantic AI Agent within ChuckAgent...")
|
| 229 |
try:
|
| 230 |
openai_api_key = os.environ.get('OPENAI_API_KEY')
|
| 231 |
+
# MODIFIED LLM and Provider instantiation
|
| 232 |
+
provider = OpenAIProvider(api_key=openai_api_key)
|
| 233 |
+
llm = OpenAIModel(
|
| 234 |
+
model_name=CONFIG.OPENAI_MODEL_ID, # Use model_name parameter
|
| 235 |
+
provider=provider
|
| 236 |
)
|
| 237 |
+
self.llm_for_fallback = llm
|
| 238 |
|
|
|
|
| 239 |
self.agent_instance = Agent(
|
| 240 |
llm=llm,
|
| 241 |
+
tools=[web_search],
|
| 242 |
system_prompt=CONFIG.PYDANTIC_AI_SYSTEM_PROMPT,
|
| 243 |
+
debug=True
|
| 244 |
)
|
| 245 |
print("DEBUG: ChuckAgent - Pydantic AI Agent initialized successfully.")
|
| 246 |
logger.info("Pydantic AI Agent initialized successfully.")
|
| 247 |
except Exception as e:
|
| 248 |
print(f"DEBUG: ERROR - ChuckAgent failed to initialize Pydantic AI Agent: {type(e).__name__} - {e}")
|
| 249 |
logger.error(f"Failed to initialize Pydantic AI Agent: {e}", exc_info=True)
|
| 250 |
+
raise
|
| 251 |
elif not PYDANTIC_AI_LOADED:
|
| 252 |
print("DEBUG: ERROR - Pydantic AI library not loaded, cannot initialize agent.")
|
| 253 |
logger.error("Pydantic AI library not loaded, cannot initialize agent.")
|
| 254 |
+
self.agent_instance = Agent() # Dummy agent
|
|
|
|
|
|
|
| 255 |
else:
|
| 256 |
print("DEBUG: ChuckAgent - Pydantic AI Agent already initialized.")
|
| 257 |
|
|
|
|
| 258 |
async def _process_question_async(self, question_text: str) -> Tuple[str, str]:
|
| 259 |
print(f"DEBUG: ChuckAgent._process_question_async called for: '{question_text[:100]}...'")
|
| 260 |
reasoning_trace = "Pydantic AI Agent execution started."
|
| 261 |
final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
|
| 262 |
|
|
|
|
| 263 |
if self.agent_instance is None or (not PYDANTIC_AI_LOADED and isinstance(self.agent_instance, globals().get('Agent'))):
|
| 264 |
logger.error("Pydantic AI Agent instance not available or is a dummy placeholder.")
|
| 265 |
print("DEBUG: ERROR - Pydantic AI Agent instance not available in _process_question_async.")
|
|
|
|
| 267 |
|
| 268 |
try:
|
| 269 |
agent_final_text_output = await self.agent_instance.run(question_text)
|
| 270 |
+
reasoning_trace = str(agent_final_text_output)
|
| 271 |
|
| 272 |
print(f"DEBUG: Pydantic AI Agent raw output (first 500 chars): {reasoning_trace[:500]}")
|
|
|
|
| 273 |
match = re.search(r"FINAL ANSWER:\s*(.*)", reasoning_trace, re.IGNORECASE | re.DOTALL)
|
| 274 |
|
| 275 |
if match:
|
| 276 |
final_answer_for_submission = match.group(1).strip()
|
| 277 |
print(f"DEBUG: Pydantic AI Agent extracted FINAL ANSWER: '{final_answer_for_submission}'")
|
| 278 |
+
elif PYDANTIC_AI_LOADED and self.llm_for_fallback:
|
| 279 |
logger.warning("Could not find 'FINAL ANSWER:' in Pydantic AI Agent's output. Attempting LLM summarization fallback.")
|
| 280 |
print("DEBUG: WARNING - Pydantic AI Agent - Could not find 'FINAL ANSWER:'. Initiating LLM summarization fallback.")
|
|
|
|
| 281 |
summarizer_messages = [
|
| 282 |
{"role": "system", "content": CONFIG.SUMMARIZER_SYSTEM_PROMPT},
|
| 283 |
{"role": "user", "content": f"Original Question: {question_text}\n\nAgent's Full Output Log:\n{reasoning_trace}\n\nBased on the 'Agent's Full Output 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. If a clear answer cannot be determined, output 'Could not determine answer from reasoning.'"}
|
| 284 |
]
|
| 285 |
print(f"DEBUG: Summarizer LLM call with messages (user message snippet): {summarizer_messages[1]['content'][:200]}...")
|
| 286 |
try:
|
| 287 |
+
from openai import OpenAI as OfficialOpenAIClient
|
| 288 |
client = OfficialOpenAIClient(api_key=os.environ.get('OPENAI_API_KEY'))
|
| 289 |
response = client.chat.completions.create(
|
| 290 |
+
model=CONFIG.OPENAI_MODEL_ID,
|
| 291 |
messages=summarizer_messages,
|
| 292 |
temperature=0.0
|
| 293 |
)
|
| 294 |
concise_answer = response.choices[0].message.content.strip()
|
|
|
|
| 295 |
if concise_answer:
|
| 296 |
if "Could not determine answer from reasoning." in concise_answer:
|
| 297 |
print(f"DEBUG: LLM summarization fallback indicated no clear answer. Using placeholder.")
|
| 298 |
+
final_answer_for_submission = "Could not determine answer."
|
| 299 |
else:
|
| 300 |
final_answer_for_submission = concise_answer
|
| 301 |
print(f"DEBUG: LLM summarization fallback successful. Concise answer: '{final_answer_for_submission}'")
|
| 302 |
else:
|
| 303 |
print("DEBUG: ERROR - LLM summarization fallback returned empty. Using full agent output.")
|
| 304 |
+
final_answer_for_submission = reasoning_trace.strip()
|
| 305 |
except Exception as e_summary:
|
| 306 |
print(f"DEBUG: ERROR - Exception during LLM summarization fallback: {type(e_summary).__name__} - {str(e_summary)}. Using full agent output.")
|
| 307 |
logger.error(f"Exception during LLM summarization fallback: {e_summary}.", exc_info=True)
|
| 308 |
+
final_answer_for_submission = reasoning_trace.strip()
|
| 309 |
+
else:
|
| 310 |
logger.warning("Could not find 'FINAL ANSWER:' and no LLM fallback possible/applicable. Using agent's full output.")
|
| 311 |
+
final_answer_for_submission = reasoning_trace.strip()
|
| 312 |
|
| 313 |
+
if not final_answer_for_submission:
|
|
|
|
| 314 |
final_answer_for_submission = "Could not determine answer."
|
|
|
|
| 315 |
except Exception as e:
|
| 316 |
error_msg = f"Error processing question with Pydantic AI Agent: {type(e).__name__} - {str(e)}"
|
| 317 |
print(f"DEBUG: ERROR - {error_msg}")
|
| 318 |
logger.error(error_msg, exc_info=True)
|
| 319 |
final_answer_for_submission = f"Error in Pydantic AI agent processing: {str(e)}"
|
| 320 |
reasoning_trace += f"\nError encountered during processing: {str(e)}"
|
|
|
|
| 321 |
return final_answer_for_submission, reasoning_trace
|
| 322 |
|
| 323 |
def __call__(self, question: str) -> Tuple[str, str]:
|
| 324 |
print(f"DEBUG: ChuckAgent.__call__ received question: '{question[:50]}...' (Pydantic AI version)")
|
| 325 |
try:
|
| 326 |
+
self._ensure_agent_initialized()
|
|
|
|
|
|
|
| 327 |
if self.agent_instance is None or \
|
| 328 |
(not PYDANTIC_AI_LOADED and isinstance(self.agent_instance, globals().get('Agent'))):
|
|
|
|
| 329 |
error_message = "Pydantic AI Agent was not initialized or is a dummy placeholder due to missing 'pydantic-ai' library."
|
| 330 |
print(f"DEBUG: ERROR - ChuckAgent.__call__ {error_message}")
|
| 331 |
raise RuntimeError(error_message)
|
|
|
|
| 337 |
else:
|
| 338 |
future = asyncio.run_coroutine_threadsafe(self._process_question_async(question), self.loop)
|
| 339 |
print(f"DEBUG: ChuckAgent waiting for future.result() for question: '{question[:50]}...'")
|
| 340 |
+
final_answer, reasoning_trace = future.result(timeout=300)
|
|
|
|
|
|
|
| 341 |
print(f"DEBUG: ChuckAgent future.result() obtained. Answer: '{final_answer[:50]}...'")
|
| 342 |
logger.info(f"ChuckAgent returning answer (first 50 chars): '{final_answer[:50]}...'")
|
| 343 |
return final_answer, reasoning_trace
|
|
|
|
| 350 |
async def shutdown_async(self):
|
| 351 |
print("DEBUG: ChuckAgent.shutdown_async called (Pydantic AI version).")
|
| 352 |
logger.info("ChuckAgent async shutdown initiated (Pydantic AI version).")
|
|
|
|
| 353 |
logger.info("ChuckAgent async shutdown complete (Pydantic AI version).")
|
| 354 |
print("DEBUG: ChuckAgent async shutdown complete (Pydantic AI version).")
|
| 355 |
|
|
|
|
| 357 |
print("DEBUG: ChuckAgent.close called (Pydantic AI version).")
|
| 358 |
if self.loop and self.loop.is_running():
|
| 359 |
print("DEBUG: ChuckAgent.close - loop is running, scheduling async_shutdown.")
|
|
|
|
| 360 |
future = asyncio.run_coroutine_threadsafe(self.shutdown_async(), self.loop)
|
| 361 |
try:
|
| 362 |
+
future.result(timeout=10)
|
| 363 |
except asyncio.TimeoutError:
|
| 364 |
logger.warning("Timeout waiting for ChuckAgent async_shutdown to complete.")
|
| 365 |
except Exception as e:
|
|
|
|
| 376 |
|
| 377 |
print("DEBUG: ChuckAgent class defined (Pydantic AI version).")
|
| 378 |
|
|
|
|
|
|
|
| 379 |
def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
|
| 380 |
print(f"DEBUG: fetch_questions called with base_api_url: {base_api_url}")
|
| 381 |
questions_url = f"{base_api_url}{CONFIG.QUESTIONS_URL_PATH}"
|
|
|
|
| 394 |
print(f"DEBUG: ERROR - Error fetching questions: {e}")
|
| 395 |
logger.error(f"Error fetching questions: {e}", exc_info=True)
|
| 396 |
raise ConnectionError(f"Error fetching questions: {e}")
|
| 397 |
+
except requests.exceptions.JSONDecodeError as e:
|
| 398 |
print(f"DEBUG: ERROR - Error decoding questions JSON: {e}")
|
| 399 |
logger.error(f"Error decoding questions JSON: {e}. Response: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True)
|
| 400 |
raise ValueError(f"Error decoding server response for questions: {e}")
|
|
|
|
| 406 |
for i, item in enumerate(questions_data):
|
| 407 |
task_id = item.get("task_id")
|
| 408 |
question_text = item.get("question")
|
| 409 |
+
if not task_id or question_text is None:
|
| 410 |
logger.warning(f"Skipping item with missing task_id or question: {item}")
|
| 411 |
continue
|
| 412 |
print(f"DEBUG: Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
|
| 413 |
try:
|
| 414 |
+
model_ans, reasoning = agent(question_text)
|
| 415 |
payload_item = {"task_id": task_id, "submitted_answer": model_ans}
|
| 416 |
if reasoning:
|
| 417 |
payload_item["reasoning_trace"] = reasoning
|
| 418 |
answers_payload.append(payload_item)
|
|
|
|
| 419 |
results_log_data.append({
|
| 420 |
"Task ID": task_id, "Question": question_text,
|
| 421 |
"Submitted Answer": model_ans,
|
| 422 |
"Reasoning Trace": reasoning
|
| 423 |
})
|
| 424 |
+
except Exception as e:
|
| 425 |
print(f"DEBUG: ERROR - Error running agent on task {task_id}: {e}")
|
| 426 |
logger.error(f"Error running agent on task {task_id} ('{question_text[:50]}...'): {e}", exc_info=True)
|
| 427 |
error_answer = f"AGENT_CALL_ERROR: {str(e)}"
|
|
|
|
| 437 |
return "Agent did not produce any answers to submit."
|
| 438 |
submit_url = f"{base_api_url}{CONFIG.SUBMIT_URL_PATH}"
|
| 439 |
submission_data = {"username": username.strip(), "agent_code": agent_code_url, "answers": answers_payload}
|
|
|
|
| 440 |
if answers_payload:
|
| 441 |
print(f"DEBUG: Sample of first answer payload being sent: {answers_payload[0]}")
|
|
|
|
| 442 |
logger.info(f"Submitting {len(answers_payload)} answers for user '{username}' to {submit_url}...")
|
| 443 |
try:
|
| 444 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
|
|
|
| 460 |
final_status = "Submission Failed: The request timed out."; logger.error(final_status)
|
| 461 |
except requests.exceptions.RequestException as e:
|
| 462 |
final_status = f"Submission Failed: Network error - {e}"; logger.error(final_status, exc_info=True)
|
| 463 |
+
except Exception as e:
|
| 464 |
final_status = f"An unexpected error occurred during submission: {e}"; logger.error(final_status, exc_info=True)
|
| 465 |
print(f"DEBUG: submit_answers final_status: {final_status}")
|
| 466 |
return final_status
|
| 467 |
|
|
|
|
|
|
|
| 468 |
GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
|
| 469 |
|
| 470 |
print("DEBUG: Defining run_and_submit_all_evaluation function.")
|
|
|
|
| 471 |
def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
|
| 472 |
global GLOBAL_CHUCK_AGENT
|
| 473 |
print(f"DEBUG: run_and_submit_all_evaluation called. Profile type: {type(profile)}")
|
|
|
|
| 483 |
effective_profile = arg_val
|
| 484 |
logger.info(f"Found gr.OAuthProfile in *args: {effective_profile.username if effective_profile else 'None (from args)'}")
|
| 485 |
break
|
|
|
|
| 486 |
if not effective_profile:
|
| 487 |
logger.warning("User not logged in or profile not correctly passed for evaluation.")
|
| 488 |
print("DEBUG: ERROR - User not logged in or profile not correctly passed for evaluation.")
|
|
|
|
| 493 |
print(f"DEBUG: User logged in: {username}")
|
| 494 |
|
| 495 |
_, agent_code_url = get_space_id_agent_code_url()
|
| 496 |
+
results_log_data: List[Dict[str, Any]] = []
|
| 497 |
|
| 498 |
try:
|
| 499 |
+
if not PYDANTIC_AI_LOADED: # Check the global flag set during initial imports
|
| 500 |
+
error_msg = "CRITICAL ERROR: The 'pydantic-ai' library is not installed correctly or key submodules are missing (e.g., 'pydantic_ai.models' or 'pydantic_ai.providers'). The Agent cannot function. Please ensure 'pydantic-ai' is correctly installed (e.g., in requirements.txt) and the environment is correctly set up, then restart the application."
|
|
|
|
| 501 |
print(f"DEBUG: {error_msg}")
|
| 502 |
logger.critical(error_msg)
|
| 503 |
+
error_df_data = [{"Task ID": "N/A",
|
| 504 |
+
"Question": "Critical Dependency Error",
|
| 505 |
+
"Submitted Answer": "pydantic-ai import failed",
|
| 506 |
"Reasoning Trace": error_msg}]
|
| 507 |
return error_msg, pd.DataFrame(error_df_data)
|
| 508 |
|
|
|
|
| 510 |
if GLOBAL_CHUCK_AGENT is None:
|
| 511 |
print("DEBUG: GLOBAL_CHUCK_AGENT is None. Creating new instance (Pydantic AI version).")
|
| 512 |
logger.info("GLOBAL_CHUCK_AGENT is None. Attempting to create a new instance (Pydantic AI version).")
|
| 513 |
+
GLOBAL_CHUCK_AGENT = ChuckAgent()
|
| 514 |
print("DEBUG: GLOBAL_CHUCK_AGENT new instance created.")
|
| 515 |
else:
|
| 516 |
print("DEBUG: GLOBAL_CHUCK_AGENT already exists.")
|
| 517 |
agent_instance = GLOBAL_CHUCK_AGENT
|
| 518 |
+
|
| 519 |
print("DEBUG: run_and_submit_all_evaluation - Ensuring agent_instance._ensure_agent_initialized().")
|
| 520 |
+
agent_instance._ensure_agent_initialized()
|
| 521 |
print("DEBUG: run_and_submit_all_evaluation - Agent ensured to be initialized.")
|
| 522 |
+
|
|
|
|
|
|
|
| 523 |
if agent_instance.agent_instance is None or \
|
| 524 |
+
(not PYDANTIC_AI_LOADED and isinstance(agent_instance.agent_instance, globals().get('Agent'))): # Re-check if somehow a dummy was created
|
| 525 |
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."
|
| 526 |
logger.critical(critical_error_msg)
|
| 527 |
print(f"DEBUG: CRITICAL - {critical_error_msg}")
|
|
|
|
| 528 |
error_df_data = [{"Task ID": "N/A",
|
| 529 |
"Question": "Agent Initialization Error",
|
| 530 |
"Submitted Answer": "Init Failed",
|
| 531 |
"Reasoning Trace": critical_error_msg}]
|
| 532 |
return critical_error_msg, pd.DataFrame(error_df_data)
|
| 533 |
|
|
|
|
| 534 |
questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
|
| 535 |
answers_payload, results_log_data_processed = process_all_questions(agent_instance, questions_data)
|
| 536 |
+
results_log_data.extend(results_log_data_processed)
|
| 537 |
submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload)
|
|
|
|
| 538 |
except EnvironmentError as e:
|
| 539 |
print(f"DEBUG: ERROR - EnvironmentError in run_and_submit_all_evaluation: {e}")
|
| 540 |
logger.critical(f"Agent instantiation or operation failed due to missing env vars: {e}")
|
| 541 |
submission_status = f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets."
|
| 542 |
+
if not results_log_data:
|
| 543 |
results_log_data = [{"Task ID": "N/A", "Question": "Environment Error", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
|
| 544 |
+
except (ConnectionError, ValueError) as e:
|
| 545 |
print(f"DEBUG: ERROR - ConnectionError/ValueError in run_and_submit_all_evaluation: {e}")
|
| 546 |
logger.error(f"Data handling or connection error during evaluation: {e}", exc_info=True)
|
| 547 |
submission_status = str(e)
|
| 548 |
if not results_log_data:
|
| 549 |
results_log_data = [{"Task ID": "N/A", "Question": "Connection/Value Error", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
|
| 550 |
+
except RuntimeError as e:
|
| 551 |
print(f"DEBUG: ERROR - RuntimeError in run_and_submit_all_evaluation: {e}")
|
| 552 |
logger.error(f"Runtime error during evaluation: {e}", exc_info=True)
|
| 553 |
submission_status = f"Runtime Error: {e}"
|
| 554 |
if not results_log_data:
|
| 555 |
results_log_data = [{"Task ID": "N/A", "Question": "Runtime Error", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
|
| 556 |
+
except Exception as e:
|
| 557 |
print(f"DEBUG: ERROR - Unexpected Exception in run_and_submit_all_evaluation: {type(e).__name__} - {e}")
|
| 558 |
logger.error(f"An unexpected error occurred during the evaluation pipeline: {e}", exc_info=True)
|
| 559 |
submission_status = f"An unexpected error occurred: {e}"
|
| 560 |
+
if not results_log_data:
|
| 561 |
results_log_data = [{"Task ID": "N/A", "Question": "Unexpected Error", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
|
| 562 |
|
|
|
|
| 563 |
results_df = pd.DataFrame(results_log_data if results_log_data else [])
|
| 564 |
print(f"DEBUG: run_and_submit_all_evaluation returning. Status: {submission_status[:100]}...")
|
| 565 |
return submission_status, results_df
|
| 566 |
|
|
|
|
| 567 |
print("DEBUG: Building Gradio interface.")
|
| 568 |
try:
|
| 569 |
with gr.Blocks(css=".gradio-container {max-width: 960px !important; margin: auto !important;}") as demo:
|
| 570 |
print("DEBUG: gr.Blocks context entered.")
|
| 571 |
+
gr.Markdown("# Chuck's Agent Evaluation Runner (Pydantic AI Version)")
|
| 572 |
gr.Markdown(
|
| 573 |
"""
|
| 574 |
**Instructions:**
|
|
|
|
| 596 |
"""
|
| 597 |
)
|
| 598 |
print("DEBUG: Gradio Markdown elements created.")
|
|
|
|
| 599 |
login_button = gr.LoginButton()
|
| 600 |
print("DEBUG: Gradio LoginButton created.")
|
| 601 |
run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
|
| 602 |
print("DEBUG: Gradio Run Button created.")
|
|
|
|
| 603 |
with gr.Column():
|
| 604 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=8, interactive=False, show_copy_button=True)
|
| 605 |
results_table = gr.DataFrame(label="Detailed Results: Questions and Agent Answers", wrap=True)
|
| 606 |
print("DEBUG: Gradio output elements (Textbox, DataFrame) created.")
|
|
|
|
| 607 |
run_button.click(
|
| 608 |
fn=run_and_submit_all_evaluation,
|
| 609 |
inputs=[login_button],
|
|
|
|
| 614 |
except Exception as e:
|
| 615 |
print(f"DEBUG: ERROR - Exception during Gradio UI definition: {e}")
|
| 616 |
logger.critical(f"Gradio UI definition failed: {e}", exc_info=True)
|
| 617 |
+
demo = None
|
|
|
|
| 618 |
|
|
|
|
| 619 |
if __name__ == "__main__":
|
| 620 |
print("\n" + "="*15 + " Application Startup (Pydantic AI) " + "="*15)
|
|
|
|
| 621 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 622 |
space_id_startup, agent_url_startup = get_space_id_agent_code_url()
|
|
|
|
|
|
|
| 623 |
print(f"Python Version: {'.'.join(map(str, sys.version_info[:3]))}")
|
| 624 |
print(f"Gradio Version: {gr.__version__}")
|
| 625 |
try:
|
|
|
|
| 626 |
if PYDANTIC_AI_LOADED:
|
| 627 |
+
import pydantic_ai # Local import for version access
|
| 628 |
print(f"pydantic-ai Version: {pydantic_ai.__version__ if hasattr(pydantic_ai, '__version__') else 'unknown (loaded)'}")
|
| 629 |
else:
|
| 630 |
print("pydantic-ai could not be imported (version unknown). This is expected if the library has issues or is not installed.")
|
| 631 |
except ImportError:
|
| 632 |
print("pydantic-ai could not be imported during version check (version unknown).")
|
| 633 |
|
|
|
|
| 634 |
if space_host_startup:
|
| 635 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 636 |
print(f" Runtime URL might be: https://{space_host_startup}")
|
| 637 |
else:
|
| 638 |
print("ℹ️ SPACE_HOST environment variable not found (likely running locally).")
|
|
|
|
| 639 |
if space_id_startup:
|
| 640 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 641 |
+
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 642 |
print(f" Agent Code URL reported to server: {agent_url_startup}")
|
| 643 |
else:
|
| 644 |
print("ℹ️ SPACE_ID environment variable not found. Repo URL cannot be determined.")
|
|
|
|
| 645 |
print(f" Default API URL for scoring: {CONFIG.DEFAULT_API_URL}")
|
| 646 |
print(f" OpenAI Model ID for Agent: {CONFIG.OPENAI_MODEL_ID}")
|
| 647 |
print("="* (30 + len(" Application Startup (Pydantic AI) ")) + "\n")
|
|
|
|
| 648 |
print("Launching Gradio Interface for Chuck Agent Evaluation (Pydantic AI Version)...")
|
| 649 |
print("Please ensure OPENAI_API_KEY and SERPER_API_KEY are set in your environment or Space Secrets.")
|
| 650 |
print("Ensure pydantic-ai and openai>=1.3.0 are in requirements.txt.")
|
| 651 |
|
| 652 |
if demo is not None:
|
| 653 |
try:
|
| 654 |
+
demo.launch(debug=True, share=False)
|
|
|
|
| 655 |
except Exception as e:
|
| 656 |
print(f"DEBUG: ERROR - Gradio demo.launch() failed: {e}")
|
| 657 |
logger.critical(f"Gradio demo launch failed: {e}", exc_info=True)
|
|
|
|
| 672 |
print("DEBUG: No GLOBAL_CHUCK_AGENT instance to shutdown.")
|
| 673 |
else:
|
| 674 |
print("DEBUG: ERROR - Gradio demo object is None, cannot launch. Check for errors during UI definition.")
|
|
|
|
| 675 |
print("\n" + "="*15 + " Application Shutdown (Pydantic AI) " + "="*15)
|
| 676 |
else:
|
| 677 |
print("DEBUG: Script is being imported, not run as main.")
|