Update app.py
Browse files
app.py
CHANGED
|
@@ -28,18 +28,17 @@ print("DEBUG: typing and pydantic imported")
|
|
| 28 |
# --- Pydantic AI Imports ---
|
| 29 |
PYDANTIC_AI_LOADED = False
|
| 30 |
try:
|
| 31 |
-
from pydantic_ai import Agent
|
| 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
|
| 38 |
-
class Agent:
|
| 39 |
def __init__(self, *args, **kwargs):
|
| 40 |
print("DEBUG: Dummy Pydantic AI Agent initialized.")
|
| 41 |
logging.error("Dummy Pydantic AI Agent initialized.")
|
| 42 |
-
async def run(self, *args, **kwargs):
|
| 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."
|
|
@@ -122,8 +121,6 @@ print("DEBUG: Utility functions defined.")
|
|
| 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}'")
|
|
@@ -211,8 +208,8 @@ class ChuckAgent:
|
|
| 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,
|
| 215 |
-
tools=[web_search],
|
| 216 |
system_prompt=CONFIG.PYDANTIC_AI_SYSTEM_PROMPT,
|
| 217 |
debug=True
|
| 218 |
)
|
|
@@ -223,7 +220,7 @@ class ChuckAgent:
|
|
| 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()
|
| 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.")
|
|
@@ -250,12 +247,13 @@ class ChuckAgent:
|
|
| 250 |
agent_final_text_output = await self.agent_instance.run(question_text)
|
| 251 |
reasoning_trace = str(agent_final_text_output)
|
| 252 |
print(f"DEBUG: Pydantic AI Agent raw output (first 500 chars): {reasoning_trace[:500]}")
|
|
|
|
| 253 |
match = re.search(r"FINAL ANSWER:\s*(.*)", reasoning_trace, re.IGNORECASE | re.DOTALL)
|
| 254 |
|
| 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:
|
| 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 = [
|
|
@@ -281,23 +279,35 @@ class ChuckAgent:
|
|
| 281 |
print(f"DEBUG: LLM summarization fallback successful. Concise answer: '{final_answer_for_submission}'")
|
| 282 |
else:
|
| 283 |
print("DEBUG: ERROR - LLM summarization fallback returned empty. Using full agent output.")
|
| 284 |
-
final_answer_for_submission = reasoning_trace.strip()
|
| 285 |
except Exception as e_summary:
|
| 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:
|
| 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:
|
| 294 |
final_answer_for_submission = "Could not determine answer."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
except Exception as e:
|
| 296 |
error_msg = f"Error processing question with Pydantic AI Agent: {type(e).__name__} - {str(e)}"
|
| 297 |
print(f"DEBUG: ERROR - {error_msg}")
|
| 298 |
logger.error(error_msg, exc_info=True)
|
| 299 |
-
final_answer_for_submission = f"Error in Pydantic AI agent processing: {str(e)}"
|
| 300 |
reasoning_trace += f"\nError encountered during processing: {str(e)}"
|
|
|
|
| 301 |
return final_answer_for_submission, reasoning_trace
|
| 302 |
|
| 303 |
def __call__(self, question: str) -> Tuple[str, str]:
|
|
@@ -327,7 +337,6 @@ class ChuckAgent:
|
|
| 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}"
|
|
@@ -608,21 +617,19 @@ if __name__ == "__main__":
|
|
| 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:
|
| 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:
|
| 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}")
|
| 628 |
print(f" Runtime URL might be: https://{space_host_startup}")
|
|
|
|
| 28 |
# --- Pydantic AI Imports ---
|
| 29 |
PYDANTIC_AI_LOADED = False
|
| 30 |
try:
|
| 31 |
+
from pydantic_ai import Agent
|
| 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 |
+
class Agent: # Dummy Agent
|
|
|
|
| 38 |
def __init__(self, *args, **kwargs):
|
| 39 |
print("DEBUG: Dummy Pydantic AI Agent initialized.")
|
| 40 |
logging.error("Dummy Pydantic AI Agent initialized.")
|
| 41 |
+
async def run(self, *args, **kwargs):
|
| 42 |
print("DEBUG: Dummy Pydantic AI Agent run called.")
|
| 43 |
logging.error("Dummy Pydantic AI Agent run called.")
|
| 44 |
return "Error: pydantic-ai Agent not loaded."
|
|
|
|
| 121 |
# --- Tool Definitions for Pydantic AI ---
|
| 122 |
print("DEBUG: Defining GoogleSearchTool for Pydantic AI.")
|
| 123 |
|
|
|
|
|
|
|
| 124 |
async def web_search(query: str) -> str:
|
| 125 |
"""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."""
|
| 126 |
print(f"DEBUG: Web_search tool (undecorated) called with query: '{query}'")
|
|
|
|
| 208 |
model_identifier = f"openai:{CONFIG.OPENAI_MODEL_ID}"
|
| 209 |
print(f"DEBUG: Initializing Pydantic AI Agent with model identifier: {model_identifier}")
|
| 210 |
self.agent_instance = Agent(
|
| 211 |
+
model_identifier,
|
| 212 |
+
tools=[web_search],
|
| 213 |
system_prompt=CONFIG.PYDANTIC_AI_SYSTEM_PROMPT,
|
| 214 |
debug=True
|
| 215 |
)
|
|
|
|
| 220 |
logger.error(f"Failed to initialize Pydantic AI Agent: {e}", exc_info=True)
|
| 221 |
PYDANTIC_AI_LOADED = False
|
| 222 |
if self.agent_instance is None:
|
| 223 |
+
self.agent_instance = Agent()
|
| 224 |
raise
|
| 225 |
elif not PYDANTIC_AI_LOADED:
|
| 226 |
print("DEBUG: ERROR - Pydantic AI library not loaded (or failed previous init), cannot initialize real agent.")
|
|
|
|
| 247 |
agent_final_text_output = await self.agent_instance.run(question_text)
|
| 248 |
reasoning_trace = str(agent_final_text_output)
|
| 249 |
print(f"DEBUG: Pydantic AI Agent raw output (first 500 chars): {reasoning_trace[:500]}")
|
| 250 |
+
|
| 251 |
match = re.search(r"FINAL ANSWER:\s*(.*)", reasoning_trace, re.IGNORECASE | re.DOTALL)
|
| 252 |
|
| 253 |
if match:
|
| 254 |
final_answer_for_submission = match.group(1).strip()
|
| 255 |
+
print(f"DEBUG: Pydantic AI Agent extracted FINAL ANSWER candidate: '{final_answer_for_submission}'")
|
| 256 |
+
elif PYDANTIC_AI_LOADED:
|
| 257 |
logger.warning("Could not find 'FINAL ANSWER:' in Pydantic AI Agent's output. Attempting LLM summarization fallback.")
|
| 258 |
print("DEBUG: WARNING - Pydantic AI Agent - Could not find 'FINAL ANSWER:'. Initiating LLM summarization fallback.")
|
| 259 |
summarizer_messages = [
|
|
|
|
| 279 |
print(f"DEBUG: LLM summarization fallback successful. Concise answer: '{final_answer_for_submission}'")
|
| 280 |
else:
|
| 281 |
print("DEBUG: ERROR - LLM summarization fallback returned empty. Using full agent output.")
|
| 282 |
+
final_answer_for_submission = reasoning_trace.strip() # Fallback to full trace
|
| 283 |
except Exception as e_summary:
|
| 284 |
print(f"DEBUG: ERROR - Exception during LLM summarization fallback: {type(e_summary).__name__} - {str(e_summary)}. Using full agent output.")
|
| 285 |
logger.error(f"Exception during LLM summarization fallback: {e_summary}.", exc_info=True)
|
| 286 |
+
final_answer_for_submission = reasoning_trace.strip() # Fallback to full trace
|
| 287 |
+
else:
|
| 288 |
logger.warning("Could not find 'FINAL ANSWER:' and Pydantic AI not loaded or no fallback. Using agent's full output.")
|
| 289 |
final_answer_for_submission = reasoning_trace.strip()
|
| 290 |
|
| 291 |
if not final_answer_for_submission:
|
| 292 |
final_answer_for_submission = "Could not determine answer."
|
| 293 |
+
|
| 294 |
+
# --- TARGETED FIX FOR TRAILING "')" ---
|
| 295 |
+
if isinstance(final_answer_for_submission, str) and \
|
| 296 |
+
final_answer_for_submission.endswith("')") and \
|
| 297 |
+
len(final_answer_for_submission) > 2:
|
| 298 |
+
|
| 299 |
+
original_before_cleanup = final_answer_for_submission
|
| 300 |
+
final_answer_for_submission = final_answer_for_submission[:-2] # Remove last two characters: ' and )
|
| 301 |
+
print(f"DEBUG: Applied trailing ') cleanup. Original: '{original_before_cleanup}', Cleaned: '{final_answer_for_submission}'")
|
| 302 |
+
# --- END TARGETED FIX ---
|
| 303 |
+
|
| 304 |
except Exception as e:
|
| 305 |
error_msg = f"Error processing question with Pydantic AI Agent: {type(e).__name__} - {str(e)}"
|
| 306 |
print(f"DEBUG: ERROR - {error_msg}")
|
| 307 |
logger.error(error_msg, exc_info=True)
|
| 308 |
+
final_answer_for_submission = f"Error in Pydantic AI agent processing: {str(e)}" # Ensure it's a string
|
| 309 |
reasoning_trace += f"\nError encountered during processing: {str(e)}"
|
| 310 |
+
|
| 311 |
return final_answer_for_submission, reasoning_trace
|
| 312 |
|
| 313 |
def __call__(self, question: str) -> Tuple[str, str]:
|
|
|
|
| 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 |
if "Pydantic AI Agent" in str(e) or "dummy placeholder" in str(e) or "Agent instance is None" in str(e):
|
| 341 |
PYDANTIC_AI_LOADED = False
|
| 342 |
return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg}"
|
|
|
|
| 617 |
print(f"Gradio Version: {gr.__version__}")
|
| 618 |
try:
|
| 619 |
if PYDANTIC_AI_LOADED:
|
|
|
|
| 620 |
try:
|
| 621 |
import pydantic_ai
|
| 622 |
if hasattr(pydantic_ai, '__version__'):
|
| 623 |
print(f"pydantic-ai Version: {pydantic_ai.__version__}")
|
| 624 |
else:
|
| 625 |
print("pydantic-ai Version: unknown (loaded, but __version__ attribute missing at top level)")
|
| 626 |
+
except ImportError:
|
| 627 |
print("pydantic-ai could not be imported for version check, though Agent was loaded.")
|
| 628 |
else:
|
| 629 |
print("pydantic-ai could not be imported (version unknown). This is expected if the library has issues or is not installed.")
|
| 630 |
+
except Exception as e_ver:
|
| 631 |
print(f"Error during pydantic-ai version check: {e_ver}")
|
| 632 |
|
|
|
|
| 633 |
if space_host_startup:
|
| 634 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 635 |
print(f" Runtime URL might be: https://{space_host_startup}")
|