Update app.py
Browse files
app.py
CHANGED
|
@@ -28,14 +28,13 @@ print("DEBUG: typing and pydantic imported")
|
|
| 28 |
# --- Pydantic AI Imports ---
|
| 29 |
PYDANTIC_AI_LOADED = False
|
| 30 |
try:
|
| 31 |
-
from pydantic_ai import Agent
|
| 32 |
-
|
| 33 |
-
print("DEBUG: pydantic-ai components imported successfully.")
|
| 34 |
PYDANTIC_AI_LOADED = True
|
| 35 |
except ImportError as e:
|
| 36 |
-
print(f"DEBUG: Failed to import pydantic-ai. Error: {e}")
|
| 37 |
-
logging.error(f"Failed to import pydantic-ai. Please ensure it is installed. Error: {e}")
|
| 38 |
-
# Dummy
|
| 39 |
class Agent:
|
| 40 |
def __init__(self, *args, **kwargs):
|
| 41 |
print("DEBUG: Dummy Pydantic AI Agent initialized.")
|
|
@@ -44,12 +43,6 @@ except ImportError as e:
|
|
| 44 |
print("DEBUG: Dummy Pydantic AI Agent run called.")
|
| 45 |
logging.error("Dummy Pydantic AI Agent run called.")
|
| 46 |
return "Error: pydantic-ai Agent not loaded."
|
| 47 |
-
# Dummy for pydantic_tool if its import fails; this is a basic callable
|
| 48 |
-
def pydantic_tool(*args, **kwargs):
|
| 49 |
-
def decorator(func):
|
| 50 |
-
return func
|
| 51 |
-
return decorator
|
| 52 |
-
|
| 53 |
|
| 54 |
from datetime import datetime
|
| 55 |
print("DEBUG: datetime imported")
|
|
@@ -61,7 +54,7 @@ class AppConfig:
|
|
| 61 |
QUESTIONS_URL_PATH = "/questions"
|
| 62 |
SUBMIT_URL_PATH = "/submit"
|
| 63 |
SCREENSHOTS_DIR = "screenshots"
|
| 64 |
-
OPENAI_MODEL_ID = "gpt-4-1106-preview"
|
| 65 |
SERPER_API_NUM_RESULTS = 3
|
| 66 |
WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
|
| 67 |
|
|
@@ -129,14 +122,11 @@ print("DEBUG: Utility functions defined.")
|
|
| 129 |
# --- Tool Definitions for Pydantic AI ---
|
| 130 |
print("DEBUG: Defining GoogleSearchTool for Pydantic AI.")
|
| 131 |
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
)
|
| 135 |
async def web_search(query: str) -> str:
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
print(f"DEBUG: Pydantic AI web_search tool called with query: '{query}'")
|
| 140 |
serper_api_key = os.environ.get('SERPER_API_KEY')
|
| 141 |
if not serper_api_key:
|
| 142 |
logger.error("SERPER_API_KEY not found in environment variables.")
|
|
@@ -212,17 +202,17 @@ class ChuckAgent:
|
|
| 212 |
print("DEBUG: ChuckAgent basic initialization complete (Pydantic AI version).")
|
| 213 |
|
| 214 |
def _ensure_agent_initialized(self):
|
| 215 |
-
global PYDANTIC_AI_LOADED
|
| 216 |
print("DEBUG: ChuckAgent._ensure_agent_initialized called.")
|
| 217 |
-
if self.agent_instance is None and PYDANTIC_AI_LOADED:
|
| 218 |
print("DEBUG: ChuckAgent - self.agent_instance is None. Initializing Pydantic AI Agent...")
|
| 219 |
logger.info("Initializing Pydantic AI Agent within ChuckAgent...")
|
| 220 |
try:
|
| 221 |
model_identifier = f"openai:{CONFIG.OPENAI_MODEL_ID}"
|
| 222 |
print(f"DEBUG: Initializing Pydantic AI Agent with model identifier: {model_identifier}")
|
| 223 |
self.agent_instance = Agent(
|
| 224 |
-
model_identifier,
|
| 225 |
-
tools=[web_search],
|
| 226 |
system_prompt=CONFIG.PYDANTIC_AI_SYSTEM_PROMPT,
|
| 227 |
debug=True
|
| 228 |
)
|
|
@@ -231,11 +221,11 @@ class ChuckAgent:
|
|
| 231 |
except Exception as e:
|
| 232 |
print(f"DEBUG: ERROR - ChuckAgent failed to initialize Pydantic AI Agent: {type(e).__name__} - {e}")
|
| 233 |
logger.error(f"Failed to initialize Pydantic AI Agent: {e}", exc_info=True)
|
| 234 |
-
PYDANTIC_AI_LOADED = False
|
| 235 |
-
if self.agent_instance is None:
|
| 236 |
-
self.agent_instance = Agent()
|
| 237 |
raise
|
| 238 |
-
elif not PYDANTIC_AI_LOADED:
|
| 239 |
print("DEBUG: ERROR - Pydantic AI library not loaded (or failed previous init), cannot initialize real agent.")
|
| 240 |
logger.error("Pydantic AI library not loaded (or failed previous init), cannot initialize real agent.")
|
| 241 |
if self.agent_instance is None:
|
|
@@ -251,7 +241,7 @@ class ChuckAgent:
|
|
| 251 |
if self.agent_instance is None or not PYDANTIC_AI_LOADED:
|
| 252 |
logger.error("Pydantic AI Agent instance not available or library not loaded.")
|
| 253 |
print("DEBUG: ERROR - Pydantic AI Agent instance not available in _process_question_async.")
|
| 254 |
-
if hasattr(self.agent_instance, 'run'):
|
| 255 |
dummy_error = await self.agent_instance.run("")
|
| 256 |
return dummy_error, "Agent not properly initialized or pydantic-ai not loaded."
|
| 257 |
return "Error: Pydantic AI Agent not properly initialized.", "Agent not initialized at process time."
|
|
@@ -265,7 +255,7 @@ class ChuckAgent:
|
|
| 265 |
if match:
|
| 266 |
final_answer_for_submission = match.group(1).strip()
|
| 267 |
print(f"DEBUG: Pydantic AI Agent extracted FINAL ANSWER: '{final_answer_for_submission}'")
|
| 268 |
-
elif PYDANTIC_AI_LOADED:
|
| 269 |
logger.warning("Could not find 'FINAL ANSWER:' in Pydantic AI Agent's output. Attempting LLM summarization fallback.")
|
| 270 |
print("DEBUG: WARNING - Pydantic AI Agent - Could not find 'FINAL ANSWER:'. Initiating LLM summarization fallback.")
|
| 271 |
summarizer_messages = [
|
|
@@ -284,7 +274,7 @@ class ChuckAgent:
|
|
| 284 |
concise_answer = response.choices[0].message.content.strip()
|
| 285 |
if concise_answer:
|
| 286 |
if "Could not determine answer from reasoning." in concise_answer:
|
| 287 |
-
print(f"DEBUG: LLM summarization fallback indicated no clear answer.
|
| 288 |
final_answer_for_submission = "Could not determine answer from reasoning."
|
| 289 |
else:
|
| 290 |
final_answer_for_submission = concise_answer
|
|
@@ -296,8 +286,8 @@ class ChuckAgent:
|
|
| 296 |
print(f"DEBUG: ERROR - Exception during LLM summarization fallback: {type(e_summary).__name__} - {str(e_summary)}. Using full agent output.")
|
| 297 |
logger.error(f"Exception during LLM summarization fallback: {e_summary}.", exc_info=True)
|
| 298 |
final_answer_for_submission = reasoning_trace.strip()
|
| 299 |
-
else:
|
| 300 |
-
logger.warning("Could not find 'FINAL ANSWER:' and Pydantic AI not loaded. Using agent's
|
| 301 |
final_answer_for_submission = reasoning_trace.strip()
|
| 302 |
|
| 303 |
if not final_answer_for_submission:
|
|
@@ -311,7 +301,7 @@ class ChuckAgent:
|
|
| 311 |
return final_answer_for_submission, reasoning_trace
|
| 312 |
|
| 313 |
def __call__(self, question: str) -> Tuple[str, str]:
|
| 314 |
-
global PYDANTIC_AI_LOADED
|
| 315 |
print(f"DEBUG: ChuckAgent.__call__ received question: '{question[:50]}...' (Pydantic AI version)")
|
| 316 |
try:
|
| 317 |
self._ensure_agent_initialized()
|
|
@@ -337,8 +327,9 @@ class ChuckAgent:
|
|
| 337 |
error_msg = f"Error running ChuckAgent (Pydantic AI): {type(e).__name__} - {str(e)}"
|
| 338 |
print(f"DEBUG: ERROR - Exception in ChuckAgent.__call__: {error_msg}")
|
| 339 |
logger.error(error_msg, exc_info=True)
|
| 340 |
-
|
| 341 |
-
|
|
|
|
| 342 |
return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg}"
|
| 343 |
|
| 344 |
async def shutdown_async(self):
|
|
@@ -514,7 +505,7 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
|
|
| 514 |
agent_instance._ensure_agent_initialized()
|
| 515 |
print("DEBUG: run_and_submit_all_evaluation - Agent ensured to be initialized.")
|
| 516 |
|
| 517 |
-
if not PYDANTIC_AI_LOADED: # Re-check after _ensure_agent_initialized
|
| 518 |
critical_error_msg = "Agent initialization failed post-import or a secondary import within Agent init failed. PydanticAI is not usable."
|
| 519 |
logger.critical(critical_error_msg)
|
| 520 |
print(f"DEBUG: CRITICAL - {critical_error_msg}")
|
|
@@ -617,12 +608,20 @@ if __name__ == "__main__":
|
|
| 617 |
print(f"Gradio Version: {gr.__version__}")
|
| 618 |
try:
|
| 619 |
if PYDANTIC_AI_LOADED:
|
| 620 |
-
|
| 621 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 622 |
else:
|
| 623 |
print("pydantic-ai could not be imported (version unknown). This is expected if the library has issues or is not installed.")
|
| 624 |
-
except
|
| 625 |
-
print("pydantic-ai
|
|
|
|
| 626 |
|
| 627 |
if space_host_startup:
|
| 628 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
|
| 28 |
# --- Pydantic AI Imports ---
|
| 29 |
PYDANTIC_AI_LOADED = False
|
| 30 |
try:
|
| 31 |
+
from pydantic_ai import Agent # Simplified import
|
| 32 |
+
print("DEBUG: pydantic-ai Agent imported successfully.")
|
|
|
|
| 33 |
PYDANTIC_AI_LOADED = True
|
| 34 |
except ImportError as e:
|
| 35 |
+
print(f"DEBUG: Failed to import pydantic-ai Agent. Error: {e}")
|
| 36 |
+
logging.error(f"Failed to import pydantic-ai Agent. Please ensure it is installed. Error: {e}")
|
| 37 |
+
# Dummy Agent class
|
| 38 |
class Agent:
|
| 39 |
def __init__(self, *args, **kwargs):
|
| 40 |
print("DEBUG: Dummy Pydantic AI Agent initialized.")
|
|
|
|
| 43 |
print("DEBUG: Dummy Pydantic AI Agent run called.")
|
| 44 |
logging.error("Dummy Pydantic AI Agent run called.")
|
| 45 |
return "Error: pydantic-ai Agent not loaded."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
from datetime import datetime
|
| 48 |
print("DEBUG: datetime imported")
|
|
|
|
| 54 |
QUESTIONS_URL_PATH = "/questions"
|
| 55 |
SUBMIT_URL_PATH = "/submit"
|
| 56 |
SCREENSHOTS_DIR = "screenshots"
|
| 57 |
+
OPENAI_MODEL_ID = "gpt-4-1106-preview"
|
| 58 |
SERPER_API_NUM_RESULTS = 3
|
| 59 |
WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
|
| 60 |
|
|
|
|
| 122 |
# --- Tool Definitions for Pydantic AI ---
|
| 123 |
print("DEBUG: Defining GoogleSearchTool for Pydantic AI.")
|
| 124 |
|
| 125 |
+
# web_search is now an undecorated async function.
|
| 126 |
+
# Its docstring and type hints will be important if pydantic-ai introspects them.
|
|
|
|
| 127 |
async def web_search(query: str) -> str:
|
| 128 |
+
"""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."""
|
| 129 |
+
print(f"DEBUG: Web_search tool (undecorated) called with query: '{query}'")
|
|
|
|
|
|
|
| 130 |
serper_api_key = os.environ.get('SERPER_API_KEY')
|
| 131 |
if not serper_api_key:
|
| 132 |
logger.error("SERPER_API_KEY not found in environment variables.")
|
|
|
|
| 202 |
print("DEBUG: ChuckAgent basic initialization complete (Pydantic AI version).")
|
| 203 |
|
| 204 |
def _ensure_agent_initialized(self):
|
| 205 |
+
global PYDANTIC_AI_LOADED
|
| 206 |
print("DEBUG: ChuckAgent._ensure_agent_initialized called.")
|
| 207 |
+
if self.agent_instance is None and PYDANTIC_AI_LOADED:
|
| 208 |
print("DEBUG: ChuckAgent - self.agent_instance is None. Initializing Pydantic AI Agent...")
|
| 209 |
logger.info("Initializing Pydantic AI Agent within ChuckAgent...")
|
| 210 |
try:
|
| 211 |
model_identifier = f"openai:{CONFIG.OPENAI_MODEL_ID}"
|
| 212 |
print(f"DEBUG: Initializing Pydantic AI Agent with model identifier: {model_identifier}")
|
| 213 |
self.agent_instance = Agent(
|
| 214 |
+
model_identifier, # Pass the model string directly
|
| 215 |
+
tools=[web_search], # Pass undecorated function
|
| 216 |
system_prompt=CONFIG.PYDANTIC_AI_SYSTEM_PROMPT,
|
| 217 |
debug=True
|
| 218 |
)
|
|
|
|
| 221 |
except Exception as e:
|
| 222 |
print(f"DEBUG: ERROR - ChuckAgent failed to initialize Pydantic AI Agent: {type(e).__name__} - {e}")
|
| 223 |
logger.error(f"Failed to initialize Pydantic AI Agent: {e}", exc_info=True)
|
| 224 |
+
PYDANTIC_AI_LOADED = False
|
| 225 |
+
if self.agent_instance is None:
|
| 226 |
+
self.agent_instance = Agent() # Fallback to dummy
|
| 227 |
raise
|
| 228 |
+
elif not PYDANTIC_AI_LOADED:
|
| 229 |
print("DEBUG: ERROR - Pydantic AI library not loaded (or failed previous init), cannot initialize real agent.")
|
| 230 |
logger.error("Pydantic AI library not loaded (or failed previous init), cannot initialize real agent.")
|
| 231 |
if self.agent_instance is None:
|
|
|
|
| 241 |
if self.agent_instance is None or not PYDANTIC_AI_LOADED:
|
| 242 |
logger.error("Pydantic AI Agent instance not available or library not loaded.")
|
| 243 |
print("DEBUG: ERROR - Pydantic AI Agent instance not available in _process_question_async.")
|
| 244 |
+
if hasattr(self.agent_instance, 'run'):
|
| 245 |
dummy_error = await self.agent_instance.run("")
|
| 246 |
return dummy_error, "Agent not properly initialized or pydantic-ai not loaded."
|
| 247 |
return "Error: Pydantic AI Agent not properly initialized.", "Agent not initialized at process time."
|
|
|
|
| 255 |
if match:
|
| 256 |
final_answer_for_submission = match.group(1).strip()
|
| 257 |
print(f"DEBUG: Pydantic AI Agent extracted FINAL ANSWER: '{final_answer_for_submission}'")
|
| 258 |
+
elif PYDANTIC_AI_LOADED: # Attempt fallback only if pydantic_ai was intended to be working
|
| 259 |
logger.warning("Could not find 'FINAL ANSWER:' in Pydantic AI Agent's output. Attempting LLM summarization fallback.")
|
| 260 |
print("DEBUG: WARNING - Pydantic AI Agent - Could not find 'FINAL ANSWER:'. Initiating LLM summarization fallback.")
|
| 261 |
summarizer_messages = [
|
|
|
|
| 274 |
concise_answer = response.choices[0].message.content.strip()
|
| 275 |
if concise_answer:
|
| 276 |
if "Could not determine answer from reasoning." in concise_answer:
|
| 277 |
+
print(f"DEBUG: LLM summarization fallback indicated no clear answer.")
|
| 278 |
final_answer_for_submission = "Could not determine answer from reasoning."
|
| 279 |
else:
|
| 280 |
final_answer_for_submission = concise_answer
|
|
|
|
| 286 |
print(f"DEBUG: ERROR - Exception during LLM summarization fallback: {type(e_summary).__name__} - {str(e_summary)}. Using full agent output.")
|
| 287 |
logger.error(f"Exception during LLM summarization fallback: {e_summary}.", exc_info=True)
|
| 288 |
final_answer_for_submission = reasoning_trace.strip()
|
| 289 |
+
else: # PYDANTIC_AI_LOADED is False, or some other case. Use raw output.
|
| 290 |
+
logger.warning("Could not find 'FINAL ANSWER:' and Pydantic AI not loaded or no fallback. Using agent's full output.")
|
| 291 |
final_answer_for_submission = reasoning_trace.strip()
|
| 292 |
|
| 293 |
if not final_answer_for_submission:
|
|
|
|
| 301 |
return final_answer_for_submission, reasoning_trace
|
| 302 |
|
| 303 |
def __call__(self, question: str) -> Tuple[str, str]:
|
| 304 |
+
global PYDANTIC_AI_LOADED
|
| 305 |
print(f"DEBUG: ChuckAgent.__call__ received question: '{question[:50]}...' (Pydantic AI version)")
|
| 306 |
try:
|
| 307 |
self._ensure_agent_initialized()
|
|
|
|
| 327 |
error_msg = f"Error running ChuckAgent (Pydantic AI): {type(e).__name__} - {str(e)}"
|
| 328 |
print(f"DEBUG: ERROR - Exception in ChuckAgent.__call__: {error_msg}")
|
| 329 |
logger.error(error_msg, exc_info=True)
|
| 330 |
+
# If error indicates agent problem, ensure PYDANTIC_AI_LOADED is False
|
| 331 |
+
if "Pydantic AI Agent" in str(e) or "dummy placeholder" in str(e) or "Agent instance is None" in str(e):
|
| 332 |
+
PYDANTIC_AI_LOADED = False
|
| 333 |
return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg}"
|
| 334 |
|
| 335 |
async def shutdown_async(self):
|
|
|
|
| 505 |
agent_instance._ensure_agent_initialized()
|
| 506 |
print("DEBUG: run_and_submit_all_evaluation - Agent ensured to be initialized.")
|
| 507 |
|
| 508 |
+
if not PYDANTIC_AI_LOADED: # Re-check after _ensure_agent_initialized could modify it
|
| 509 |
critical_error_msg = "Agent initialization failed post-import or a secondary import within Agent init failed. PydanticAI is not usable."
|
| 510 |
logger.critical(critical_error_msg)
|
| 511 |
print(f"DEBUG: CRITICAL - {critical_error_msg}")
|
|
|
|
| 608 |
print(f"Gradio Version: {gr.__version__}")
|
| 609 |
try:
|
| 610 |
if PYDANTIC_AI_LOADED:
|
| 611 |
+
# Attempt to get version from the imported Agent's module if __version__ is not top-level
|
| 612 |
+
try:
|
| 613 |
+
import pydantic_ai
|
| 614 |
+
if hasattr(pydantic_ai, '__version__'):
|
| 615 |
+
print(f"pydantic-ai Version: {pydantic_ai.__version__}")
|
| 616 |
+
else:
|
| 617 |
+
print("pydantic-ai Version: unknown (loaded, but __version__ attribute missing at top level)")
|
| 618 |
+
except ImportError: # Should not happen if PYDANTIC_AI_LOADED is True
|
| 619 |
+
print("pydantic-ai could not be imported for version check, though Agent was loaded.")
|
| 620 |
else:
|
| 621 |
print("pydantic-ai could not be imported (version unknown). This is expected if the library has issues or is not installed.")
|
| 622 |
+
except Exception as e_ver: # Catch any error during version printing
|
| 623 |
+
print(f"Error during pydantic-ai version check: {e_ver}")
|
| 624 |
+
|
| 625 |
|
| 626 |
if space_host_startup:
|
| 627 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|