pydantic conversation test
Browse files
app.py
CHANGED
|
@@ -15,57 +15,38 @@ import json
|
|
| 15 |
print("DEBUG: json imported")
|
| 16 |
import logging
|
| 17 |
print("DEBUG: logging imported")
|
| 18 |
-
import operator #
|
| 19 |
-
print("DEBUG: operator imported")
|
| 20 |
import aiohttp
|
| 21 |
print("DEBUG: aiohttp imported")
|
| 22 |
-
from typing import Optional, Dict, Any, List, Tuple
|
| 23 |
-
|
|
|
|
| 24 |
|
| 25 |
-
#
|
| 26 |
-
|
| 27 |
try:
|
| 28 |
-
from
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
| 37 |
def __init__(self, *args, **kwargs):
|
| 38 |
-
print("DEBUG: Dummy
|
| 39 |
-
logging.error("Dummy
|
| 40 |
-
def run(self, *args, **kwargs):
|
| 41 |
-
print("DEBUG: Dummy
|
| 42 |
-
logging.error("Dummy
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
text = "Error: smolagents CodeAgent not loaded."
|
| 46 |
-
def log_string(self):
|
| 47 |
-
return "Error: smolagents CodeAgent not loaded. No reasoning trace available."
|
| 48 |
-
return DummyRunResponse()
|
| 49 |
-
|
| 50 |
-
class Tool:
|
| 51 |
def __init__(self, *args, **kwargs):
|
| 52 |
-
|
| 53 |
-
logging.error("Dummy Tool initialized because smolagents failed to import.")
|
| 54 |
-
pass
|
| 55 |
|
| 56 |
-
class OpenAIServerModel:
|
| 57 |
-
def __init__(self, *args, **kwargs):
|
| 58 |
-
print("DEBUG: Dummy OpenAIServerModel initialized because smolagents failed to import.")
|
| 59 |
-
logging.error("Dummy OpenAIServerModel initialized because smolagents failed to import.")
|
| 60 |
-
|
| 61 |
-
async def generate_stream(self, messages, **kwargs): # Changed to generate_stream
|
| 62 |
-
print("DEBUG: Dummy OpenAIServerModel generate_stream called.")
|
| 63 |
-
# Simulate async generator behavior
|
| 64 |
-
class DummyStreamChunk:
|
| 65 |
-
text = "Error: smolagents.OpenAIServerModel not loaded or dummy generate_stream called."
|
| 66 |
-
yield DummyStreamChunk()
|
| 67 |
-
|
| 68 |
-
pass
|
| 69 |
|
| 70 |
from datetime import datetime
|
| 71 |
print("DEBUG: datetime imported")
|
|
@@ -76,63 +57,38 @@ class AppConfig:
|
|
| 76 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 77 |
QUESTIONS_URL_PATH = "/questions"
|
| 78 |
SUBMIT_URL_PATH = "/submit"
|
| 79 |
-
SCREENSHOTS_DIR = "screenshots"
|
| 80 |
-
OPENAI_MODEL_ID = "gpt-4
|
| 81 |
SERPER_API_NUM_RESULTS = 3
|
| 82 |
WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
|
| 83 |
-
AGENT_MAX_STEPS = 10
|
| 84 |
-
AGENT_VERBOSITY_LEVEL = 2
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
# REMEMBER: Use `await` and set provider="serpapi".
|
| 100 |
-
# ALWAYS print the result of the tool call.
|
| 101 |
-
# Example:
|
| 102 |
-
# search_result = await web_search(query="some specific query", provider="serpapi")
|
| 103 |
-
# print(search_result)
|
| 104 |
-
```<end_code>
|
| 105 |
-
4. OBSERVATION: [The system will insert the printed output of your tool call here.]
|
| 106 |
-
5. THOUGHT: Analyze the observation. Is it what you expected? Do you have enough information to answer the user's question now? If not, refine your search or decide on the next step.
|
| 107 |
-
6. If you have the information, formulate the final answer according to the formatting rules.
|
| 108 |
-
|
| 109 |
-
CRITICAL FINAL ANSWER INSTRUCTIONS:
|
| 110 |
-
Your *entire textual response* for this turn, after all thoughts and tool use, MUST CULMINATE in the final answer.
|
| 111 |
-
This final answer MUST be on its own new line and MUST start with the exact literal string "FINAL ANSWER: " (note the space after the colon).
|
| 112 |
-
Only the answer value itself should follow this "FINAL ANSWER: " prefix. Do NOT include any of your thought process, conversational text, or additional explanations *after* this "FINAL ANSWER: " prefix and its value. Your response effectively stops there.
|
| 113 |
-
|
| 114 |
-
Example of a full agent response structure (what you should output):
|
| 115 |
-
THOUGHT: The user is asking for the capital of France. I should use web_search to find this.
|
| 116 |
-
CODE:
|
| 117 |
-
```python
|
| 118 |
-
search_results = await web_search(query="capital of France", provider="serpapi")
|
| 119 |
-
print(search_results)
|
| 120 |
-
```<end_code>
|
| 121 |
-
OBSERVATION: Title: Paris - Wikipedia Snippet: Paris is the capital and most populous city of France...
|
| 122 |
-
THOUGHT: The search result clearly states that Paris is the capital of France. I have sufficient information. I will provide this as the final answer, following the formatting rules for a string.
|
| 123 |
FINAL ANSWER: Paris
|
| 124 |
|
| 125 |
-
|
| 126 |
-
|
|
|
|
|
|
|
| 127 |
FINAL ANSWER: right
|
| 128 |
|
| 129 |
Formatting rules for the value that comes *after* "FINAL ANSWER: ":
|
| 130 |
-
- If the question asks for a number: Provide only the number itself (e.g.,
|
| 131 |
-
- If the question asks for a string: Provide the most concise string possible (e.g.,
|
| 132 |
-
- If the question asks for a comma-separated list: Apply
|
| 133 |
-
- If the answer is a calculation result, provide just the number (e.g., `FINAL ANSWER: 10`).
|
| 134 |
-
|
| 135 |
-
Remember, the "FINAL ANSWER: " prefix is a literal string you must output as the very last part of your response, followed by the actual answer value. Do not confuse this with any internal `final_answer()` Python function you might generate in your CODE block; this instruction is about the final textual output of your entire turn.
|
| 136 |
"""
|
| 137 |
|
| 138 |
SUMMARIZER_SYSTEM_PROMPT = """You are an expert at extracting concise answers from text.
|
|
@@ -151,6 +107,8 @@ logging.basicConfig(
|
|
| 151 |
level=logging.INFO,
|
| 152 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
| 153 |
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
| 154 |
print("DEBUG: Logging configured.")
|
| 155 |
|
| 156 |
# --- Utility Functions ---
|
|
@@ -158,7 +116,6 @@ def ensure_dir_exists(directory_path: str):
|
|
| 158 |
os.makedirs(directory_path, exist_ok=True)
|
| 159 |
print(f"DEBUG: Ensured directory exists: {directory_path}")
|
| 160 |
|
| 161 |
-
|
| 162 |
ensure_dir_exists(CONFIG.SCREENSHOTS_DIR)
|
| 163 |
|
| 164 |
def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
|
|
@@ -171,358 +128,305 @@ def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
|
|
| 171 |
|
| 172 |
print("DEBUG: Utility functions defined.")
|
| 173 |
|
| 174 |
-
# --- Tool Definitions ---
|
| 175 |
-
print("DEBUG: Defining GoogleSearchTool.")
|
| 176 |
-
class GoogleSearchTool(Tool):
|
| 177 |
-
name = "web_search"
|
| 178 |
-
description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
|
| 179 |
-
inputs = {
|
| 180 |
-
"query": {"type": "string", "description": "The search query to execute."},
|
| 181 |
-
"provider": {
|
| 182 |
-
"type": "string",
|
| 183 |
-
"description": "The search provider. MUST be 'serpapi'.",
|
| 184 |
-
"default": "serpapi",
|
| 185 |
-
"nullable": True
|
| 186 |
-
}
|
| 187 |
-
}
|
| 188 |
-
output_type = "string"
|
| 189 |
-
is_async = True
|
| 190 |
-
|
| 191 |
-
# MODIFIED: __init__ no longer takes a session
|
| 192 |
-
def __init__(self):
|
| 193 |
-
super().__init__()
|
| 194 |
-
# self._session = session # REMOVED
|
| 195 |
-
print("DEBUG: GoogleSearchTool instance created (session will be created per-call).")
|
| 196 |
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
return "Error: Invalid search provider. Only 'serpapi' is supported for the web_search tool as per current agent configuration."
|
| 203 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
serper_api_key = os.environ.get('SERPER_API_KEY')
|
| 205 |
if not serper_api_key:
|
| 206 |
logger.error("SERPER_API_KEY not found in environment variables.")
|
| 207 |
print("DEBUG: ERROR - SERPER_API_KEY not found.")
|
| 208 |
-
return "Error: Serper API key not found in environment."
|
| 209 |
|
| 210 |
url = "https://google.serper.dev/search"
|
| 211 |
headers = {'X-API-KEY': serper_api_key, 'Content-Type': 'application/json'}
|
| 212 |
payload = json.dumps({'q': query, 'num': CONFIG.SERPER_API_NUM_RESULTS})
|
| 213 |
|
| 214 |
-
#
|
| 215 |
async with aiohttp.ClientSession() as session:
|
| 216 |
try:
|
| 217 |
-
# MODIFIED: Use the local 'session' instead of 'self._session'
|
| 218 |
async with session.post(url, headers=headers, data=payload, timeout=aiohttp.ClientTimeout(total=15)) as response:
|
| 219 |
response.raise_for_status()
|
| 220 |
data = await response.json()
|
| 221 |
-
print(f"DEBUG:
|
| 222 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
except asyncio.TimeoutError:
|
| 224 |
logger.error(f"Timeout performing search for '{query}'")
|
| 225 |
-
print(f"DEBUG: ERROR - Timeout in
|
| 226 |
return f"Error: Timeout during web search for '{query}'."
|
| 227 |
except aiohttp.ClientResponseError as e:
|
| 228 |
logger.error(f"HTTP Error performing search for '{query}': {e.status} {e.message} - Response: {await e.response.text()[:200]}")
|
| 229 |
-
print(f"DEBUG: ERROR - HTTP Error {e.status} in
|
| 230 |
return f"Error performing search (HTTP {e.status}): {e.message}"
|
| 231 |
except aiohttp.ClientError as e:
|
| 232 |
logger.error(f"ClientError performing search for '{query}': {type(e).__name__} - {str(e)}")
|
| 233 |
-
print(f"DEBUG: ERROR - ClientError in
|
| 234 |
return f"Error performing search (client error): {str(e)}"
|
| 235 |
except Exception as e:
|
| 236 |
logger.error(f"Unexpected error performing search for '{query}': {type(e).__name__} - {str(e)}", exc_info=True)
|
| 237 |
-
print(f"DEBUG: ERROR - Unexpected error in
|
| 238 |
return f"Error performing search: An unexpected error occurred."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
|
| 240 |
-
|
| 241 |
-
results = []
|
| 242 |
-
if 'organic' in data and data['organic']:
|
| 243 |
-
for result in data['organic'][:CONFIG.SERPER_API_NUM_RESULTS]:
|
| 244 |
-
title = result.get('title', 'N/A')
|
| 245 |
-
snippet = result.get('snippet', 'N/A')
|
| 246 |
-
results.append(f"Title: {title}\nSnippet: {snippet}\n---")
|
| 247 |
-
if not results and 'knowledgeGraph' in data:
|
| 248 |
-
kg = data['knowledgeGraph']
|
| 249 |
-
title = kg.get('title', '')
|
| 250 |
-
description = kg.get('description', '')
|
| 251 |
-
if title or description:
|
| 252 |
-
results.append(f"Knowledge Graph: {title}\n{description}\n---")
|
| 253 |
-
formatted_output = "\n".join(results) if results else "No relevant search results found."
|
| 254 |
-
return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
|
| 255 |
-
|
| 256 |
-
# --- Agent Definition ---
|
| 257 |
-
print("DEBUG: Defining QuestionAnsweringAgent.")
|
| 258 |
-
class QuestionAnsweringAgent(CodeAgent):
|
| 259 |
-
def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None): # http_session is still accepted but won't be used by GoogleSearchTool
|
| 260 |
-
print(f"DEBUG: QuestionAnsweringAgent.__init__ called. http_session: {http_session}, model: {model}")
|
| 261 |
-
tools = [
|
| 262 |
-
GoogleSearchTool(), # MODIFIED: Instantiate without session
|
| 263 |
-
]
|
| 264 |
-
print(f"DEBUG: QuestionAnsweringAgent tools: {tools}")
|
| 265 |
-
|
| 266 |
-
self.llm_for_fallback = model
|
| 267 |
-
if self.llm_for_fallback is None and SMOLAGENTS_LOADED: # Only create if smolagents loaded
|
| 268 |
-
print("DEBUG: QuestionAnsweringAgent self.llm_for_fallback is None, creating default OpenAIServerModel.")
|
| 269 |
-
openai_api_key = os.environ.get('OPENAI_API_KEY')
|
| 270 |
-
if not openai_api_key:
|
| 271 |
-
print("DEBUG: ERROR - OPENAI_API_KEY not found for QuestionAnsweringAgent.")
|
| 272 |
-
logger.critical("OPENAI_API_KEY not found. Cannot initialize OpenAIServerModel.")
|
| 273 |
-
raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
|
| 274 |
-
self.llm_for_fallback = OpenAIServerModel(
|
| 275 |
-
model_id=CONFIG.OPENAI_MODEL_ID,
|
| 276 |
-
api_key=openai_api_key
|
| 277 |
-
)
|
| 278 |
-
print(f"DEBUG: QuestionAnsweringAgent default OpenAIServerModel created with model_id: {CONFIG.OPENAI_MODEL_ID}")
|
| 279 |
-
elif not SMOLAGENTS_LOADED:
|
| 280 |
-
print("DEBUG: QuestionAnsweringAgent - smolagents not loaded, llm_for_fallback will use dummy.")
|
| 281 |
-
self.llm_for_fallback = OpenAIServerModel() # This will be the dummy if SMOLAGENTS_LOADED is False
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
minimal_super_args = {
|
| 285 |
-
"model": self.llm_for_fallback,
|
| 286 |
-
"tools": tools,
|
| 287 |
-
"max_steps": CONFIG.AGENT_MAX_STEPS,
|
| 288 |
-
}
|
| 289 |
-
# ... (rest of the __init__ method remains the same)
|
| 290 |
-
print(f"DEBUG: QuestionAnsweringAgent minimal_super_args for super().__init__: {minimal_super_args}")
|
| 291 |
try:
|
| 292 |
-
|
| 293 |
-
print("DEBUG:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
|
| 295 |
-
|
| 296 |
-
|
| 297 |
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
print("DEBUG: WARNING - QuestionAnsweringAgent could not set 'additional_authorized_imports' as an attribute after init.")
|
| 310 |
-
logger.warning("Could not set 'additional_authorized_imports' as an attribute after init.")
|
| 311 |
-
|
| 312 |
-
if not hasattr(self, 'code_writer') or self.code_writer is None:
|
| 313 |
-
print("DEBUG: WARNING - QuestionAnsweringAgent self.code_writer might not be initialized due to the __init__ workaround.")
|
| 314 |
-
logger.warning("self.code_writer might not be initialized due to the __init__ workaround. Agent may fail to generate or execute code.")
|
| 315 |
-
|
| 316 |
-
except TypeError as e:
|
| 317 |
-
print(f"DEBUG: ERROR - QuestionAnsweringAgent WORKAROUND FAILED: TypeError during minimal super().__init__: {e}")
|
| 318 |
-
logger.error(
|
| 319 |
-
f"WORKAROUND FAILED: Still encountered TypeError during minimal super().__init__ for QuestionAnsweringAgent: {e}. "
|
| 320 |
-
"This likely means the __init__ signature of smolagents.CodeAgent or its parent MultiStepAgent "
|
| 321 |
-
"is incompatible with this workaround or has changed.",
|
| 322 |
-
exc_info=True
|
| 323 |
-
)
|
| 324 |
-
raise
|
| 325 |
-
except Exception as e:
|
| 326 |
-
print(f"DEBUG: ERROR - QuestionAnsweringAgent Unexpected error during __init__ (possibly from tool validation): {type(e).__name__} - {e}")
|
| 327 |
-
logger.error(f"Unexpected error during QuestionAnsweringAgent __init__: {e}", exc_info=True)
|
| 328 |
-
raise
|
| 329 |
-
print(f"DEBUG: QuestionAnsweringAgent initialized with model: {CONFIG.OPENAI_MODEL_ID} and tools.")
|
| 330 |
-
|
| 331 |
-
async def process_question(self, question_text: str) -> Tuple[str, str]:
|
| 332 |
-
print(f"DEBUG: QuestionAnsweringAgent.process_question called for: '{question_text[:100]}...'")
|
| 333 |
-
reasoning_trace = "Agent execution started."
|
| 334 |
final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
|
| 335 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
try:
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
#
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
|
|
|
| 345 |
|
| 346 |
-
#
|
| 347 |
-
agent_final_text_output =
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
logger.warning(f"Raw output from agent.run() was of type {type(raw_output_obj)} and had no 'text' attribute. Using full log for parsing.")
|
| 354 |
-
agent_final_text_output = reasoning_trace # Parse the full log if .text is not available
|
| 355 |
|
| 356 |
-
print(f"DEBUG: QuestionAnsweringAgent agent_final_text_output (first 200 chars): {agent_final_text_output[:200]}")
|
| 357 |
-
|
| 358 |
-
match = re.search(r"FINAL ANSWER:\s*(.*)", agent_final_text_output, re.IGNORECASE | re.DOTALL)
|
| 359 |
-
|
| 360 |
if match:
|
| 361 |
final_answer_for_submission = match.group(1).strip()
|
| 362 |
-
print(f"DEBUG:
|
| 363 |
-
elif
|
| 364 |
-
logger.warning("Could not find 'FINAL ANSWER:' in
|
| 365 |
-
print("DEBUG: WARNING -
|
| 366 |
-
|
| 367 |
summarizer_messages = [
|
| 368 |
{"role": "system", "content": CONFIG.SUMMARIZER_SYSTEM_PROMPT},
|
| 369 |
-
{"role": "user", "content": f"Original Question: {question_text}\n\nAgent's Full
|
| 370 |
]
|
| 371 |
-
print(f"DEBUG: Summarizer LLM call with messages (user message snippet): {summarizer_messages[1]['content'][:200]}...")
|
| 372 |
try:
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
|
|
|
|
|
|
|
|
|
| 377 |
|
| 378 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 379 |
|
| 380 |
if concise_answer:
|
| 381 |
if "Could not determine answer from reasoning." in concise_answer:
|
| 382 |
print(f"DEBUG: LLM summarization fallback indicated no clear answer. Using placeholder.")
|
| 383 |
-
logger.warning("LLM summarization fallback indicated no clear answer. Using placeholder.")
|
| 384 |
final_answer_for_submission = "Could not determine answer."
|
| 385 |
else:
|
| 386 |
final_answer_for_submission = concise_answer
|
| 387 |
print(f"DEBUG: LLM summarization fallback successful. Concise answer: '{final_answer_for_submission}'")
|
| 388 |
-
logger.info(f"LLM summarization fallback used. Extracted concise answer: '{final_answer_for_submission}'")
|
| 389 |
else:
|
| 390 |
-
print("DEBUG: ERROR - LLM summarization fallback returned empty
|
| 391 |
-
|
| 392 |
-
final_answer_for_submission = reasoning_trace.strip() # Fallback to full reasoning if summary is empty
|
| 393 |
except Exception as e_summary:
|
| 394 |
-
print(f"DEBUG: ERROR - Exception during LLM summarization fallback: {type(e_summary).__name__} - {str(e_summary)}. Using
|
| 395 |
-
logger.error(f"Exception during LLM summarization fallback: {e_summary}.
|
| 396 |
-
final_answer_for_submission = reasoning_trace.strip()
|
| 397 |
-
else:
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
if not final_answer_for_submission:
|
| 404 |
-
logger.warning("Extracted final answer is empty after all fallbacks. Defaulting to a placeholder.")
|
| 405 |
-
print("DEBUG: WARNING - QuestionAnsweringAgent extracted final answer is empty after all fallbacks.")
|
| 406 |
final_answer_for_submission = "Could not determine answer."
|
| 407 |
|
| 408 |
-
except TypeError as te:
|
| 409 |
-
print(f"DEBUG: ERROR - TypeError in QuestionAnsweringAgent.process_question: {str(te)}")
|
| 410 |
-
logger.error(f"TypeError during agent processing, possibly due to __init__ workaround: {str(te)}", exc_info=True)
|
| 411 |
-
final_answer_for_submission = f"Error in agent processing (TypeError): {str(te)}"
|
| 412 |
-
reasoning_trace += f"\nTypeError encountered during processing: {str(te)}"
|
| 413 |
except Exception as e:
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
|
|
|
| 417 |
reasoning_trace += f"\nError encountered: {str(e)}"
|
| 418 |
-
return final_answer_for_submission, reasoning_trace
|
| 419 |
-
|
| 420 |
-
# --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
|
| 421 |
-
print("DEBUG: Defining ChuckAgent.")
|
| 422 |
-
class ChuckAgent:
|
| 423 |
-
def __init__(self):
|
| 424 |
-
print("DEBUG: ChuckAgent.__init__ called.")
|
| 425 |
-
logger.info("ChuckAgent initialization started.")
|
| 426 |
-
required_env_vars = ['OPENAI_API_KEY', 'SERPER_API_KEY']
|
| 427 |
-
missing_vars = [var for var in required_env_vars if not os.environ.get(var)]
|
| 428 |
-
if missing_vars:
|
| 429 |
-
error_msg = f"Missing required environment variables: {', '.join(missing_vars)}. Please set them in Space Secrets."
|
| 430 |
-
print(f"DEBUG: ERROR - ChuckAgent missing env vars: {error_msg}")
|
| 431 |
-
logger.critical(error_msg)
|
| 432 |
-
raise EnvironmentError(error_msg)
|
| 433 |
-
print("DEBUG: ChuckAgent environment variables checked.")
|
| 434 |
-
|
| 435 |
-
try:
|
| 436 |
-
self.loop = asyncio.get_running_loop()
|
| 437 |
-
except RuntimeError:
|
| 438 |
-
self.loop = asyncio.new_event_loop()
|
| 439 |
-
asyncio.set_event_loop(self.loop)
|
| 440 |
-
|
| 441 |
-
print(f"DEBUG: ChuckAgent using event loop: {self.loop}")
|
| 442 |
|
| 443 |
-
|
| 444 |
-
self.http_session = asyncio.run_coroutine_threadsafe(self._get_or_create_session(), self.loop).result(timeout=10)
|
| 445 |
-
else:
|
| 446 |
-
self.http_session = self.loop.run_until_complete(self._get_or_create_session())
|
| 447 |
-
|
| 448 |
-
print(f"DEBUG: ChuckAgent http_session created: {self.http_session}")
|
| 449 |
-
|
| 450 |
-
self.agent_instance: Optional[QuestionAnsweringAgent] = None
|
| 451 |
-
logger.info("ChuckAgent basic initialization complete. Actual QuestionAnsweringAgent will be created on first use.")
|
| 452 |
-
print("DEBUG: ChuckAgent basic initialization complete.")
|
| 453 |
-
|
| 454 |
-
async def _get_or_create_session(self) -> aiohttp.ClientSession:
|
| 455 |
-
print("DEBUG: ChuckAgent._get_or_create_session called.")
|
| 456 |
-
logger.info("Creating aiohttp.ClientSession for ChuckAgent.")
|
| 457 |
-
return aiohttp.ClientSession()
|
| 458 |
-
|
| 459 |
-
def _ensure_agent_initialized(self):
|
| 460 |
-
print("DEBUG: ChuckAgent._ensure_agent_initialized called.")
|
| 461 |
-
if self.agent_instance is None:
|
| 462 |
-
print("DEBUG: ChuckAgent - self.agent_instance is None. Initializing QuestionAnsweringAgent...")
|
| 463 |
-
logger.info("Initializing QuestionAnsweringAgent within ChuckAgent...")
|
| 464 |
-
try:
|
| 465 |
-
self.agent_instance = QuestionAnsweringAgent(http_session=self.http_session)
|
| 466 |
-
print("DEBUG: ChuckAgent - QuestionAnsweringAgent initialized successfully.")
|
| 467 |
-
logger.info("QuestionAnsweringAgent initialized successfully.")
|
| 468 |
-
except Exception as e:
|
| 469 |
-
print(f"DEBUG: ERROR - ChuckAgent failed to initialize QuestionAnsweringAgent: {type(e).__name__} - {e}")
|
| 470 |
-
logger.error(f"Failed to initialize QuestionAnsweringAgent: {e}", exc_info=True)
|
| 471 |
-
raise
|
| 472 |
-
else:
|
| 473 |
-
print("DEBUG: ChuckAgent - QuestionAnsweringAgent already initialized.")
|
| 474 |
-
|
| 475 |
|
| 476 |
def __call__(self, question: str) -> Tuple[str, str]:
|
| 477 |
-
print(f"DEBUG: ChuckAgent.__call__ received question: '{question[:50]}...'")
|
| 478 |
try:
|
| 479 |
-
self._ensure_agent_initialized()
|
| 480 |
-
if self.agent_instance is None
|
| 481 |
-
print("DEBUG: ERROR - ChuckAgent.__call__
|
| 482 |
-
raise RuntimeError("
|
| 483 |
|
| 484 |
print(f"DEBUG: ChuckAgent submitting task to event loop {self.loop} for question: '{question[:50]}...'")
|
| 485 |
if not self.loop.is_running():
|
| 486 |
-
|
|
|
|
| 487 |
else:
|
| 488 |
-
future = asyncio.run_coroutine_threadsafe(self.
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
|
|
|
| 492 |
logger.info(f"ChuckAgent returning answer (first 50 chars): '{final_answer[:50]}...'")
|
| 493 |
return final_answer, reasoning_trace
|
| 494 |
except Exception as e:
|
| 495 |
-
error_msg = f"Error running ChuckAgent: {type(e).__name__} - {str(e)}"
|
| 496 |
print(f"DEBUG: ERROR - Exception in ChuckAgent.__call__: {error_msg}")
|
| 497 |
logger.error(error_msg, exc_info=True)
|
| 498 |
return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg}"
|
| 499 |
|
| 500 |
-
async def shutdown_async(self):
|
| 501 |
-
print("DEBUG: ChuckAgent.shutdown_async called.")
|
| 502 |
-
logger.info("ChuckAgent async shutdown initiated.")
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
def close(self):
|
| 512 |
-
print("DEBUG: ChuckAgent.close called.")
|
| 513 |
-
if self.loop and self.loop.is_running() and self.http_session:
|
| 514 |
print("DEBUG: ChuckAgent.close - loop is running, scheduling async_shutdown.")
|
| 515 |
asyncio.run_coroutine_threadsafe(self.shutdown_async(), self.loop).result(timeout=10)
|
| 516 |
-
elif self.loop and not self.loop.is_running()
|
| 517 |
print("DEBUG: ChuckAgent.close - loop is not running, using run_until_complete for shutdown_async.")
|
| 518 |
self.loop.run_until_complete(self.shutdown_async())
|
| 519 |
else:
|
| 520 |
-
print("DEBUG: ChuckAgent.close - No running loop
|
| 521 |
-
print("DEBUG: ChuckAgent.close finished.")
|
|
|
|
|
|
|
|
|
|
| 522 |
|
| 523 |
-
|
|
|
|
|
|
|
|
|
|
| 524 |
|
| 525 |
-
# --- Orchestration Functions ---
|
| 526 |
def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
|
| 527 |
print(f"DEBUG: fetch_questions called with base_api_url: {base_api_url}")
|
| 528 |
questions_url = f"{base_api_url}{CONFIG.QUESTIONS_URL_PATH}"
|
|
@@ -541,32 +445,32 @@ def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
|
|
| 541 |
print(f"DEBUG: ERROR - Error fetching questions: {e}")
|
| 542 |
logger.error(f"Error fetching questions: {e}", exc_info=True)
|
| 543 |
raise ConnectionError(f"Error fetching questions: {e}")
|
| 544 |
-
except requests.exceptions.JSONDecodeError as e:
|
| 545 |
print(f"DEBUG: ERROR - Error decoding questions JSON: {e}")
|
| 546 |
logger.error(f"Error decoding questions JSON: {e}. Response: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True)
|
| 547 |
raise ValueError(f"Error decoding server response for questions: {e}")
|
| 548 |
|
| 549 |
def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
|
| 550 |
-
print(f"DEBUG: process_all_questions called with {len(questions_data)} questions.")
|
| 551 |
answers_payload = []
|
| 552 |
results_log_data = []
|
| 553 |
for i, item in enumerate(questions_data):
|
| 554 |
task_id = item.get("task_id")
|
| 555 |
question_text = item.get("question")
|
| 556 |
-
if not task_id or question_text is None:
|
| 557 |
logger.warning(f"Skipping item with missing task_id or question: {item}")
|
| 558 |
continue
|
| 559 |
print(f"DEBUG: Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
|
| 560 |
try:
|
| 561 |
-
model_ans, reasoning = agent(question_text)
|
| 562 |
payload_item = {"task_id": task_id, "submitted_answer": model_ans}
|
| 563 |
-
if reasoning:
|
| 564 |
payload_item["reasoning_trace"] = reasoning
|
| 565 |
answers_payload.append(payload_item)
|
| 566 |
-
|
| 567 |
results_log_data.append({
|
| 568 |
-
"Task ID": task_id, "Question": question_text,
|
| 569 |
-
"Submitted Answer": model_ans,
|
| 570 |
"Reasoning Trace": reasoning
|
| 571 |
})
|
| 572 |
except Exception as e:
|
|
@@ -585,7 +489,7 @@ def submit_answers(base_api_url: str, username: str, agent_code_url: str, answer
|
|
| 585 |
return "Agent did not produce any answers to submit."
|
| 586 |
submit_url = f"{base_api_url}{CONFIG.SUBMIT_URL_PATH}"
|
| 587 |
submission_data = {"username": username.strip(), "agent_code": agent_code_url, "answers": answers_payload}
|
| 588 |
-
|
| 589 |
if answers_payload:
|
| 590 |
print(f"DEBUG: Sample of first answer payload being sent: {answers_payload[0]}")
|
| 591 |
|
|
@@ -604,37 +508,38 @@ def submit_answers(base_api_url: str, username: str, agent_code_url: str, answer
|
|
| 604 |
error_detail = f"Server responded with {e.response.status_code}."
|
| 605 |
try:
|
| 606 |
error_json = e.response.json(); error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 607 |
-
except requests.exceptions.JSONDecodeError: error_detail += f" Raw Response: {e.response.text[:500]}"
|
| 608 |
final_status = f"Submission Failed: {error_detail}"; logger.error(final_status)
|
| 609 |
except requests.exceptions.Timeout:
|
| 610 |
final_status = "Submission Failed: The request timed out."; logger.error(final_status)
|
| 611 |
except requests.exceptions.RequestException as e:
|
| 612 |
final_status = f"Submission Failed: Network error - {e}"; logger.error(final_status, exc_info=True)
|
| 613 |
-
except Exception as e:
|
| 614 |
final_status = f"An unexpected error occurred during submission: {e}"; logger.error(final_status, exc_info=True)
|
| 615 |
print(f"DEBUG: submit_answers final_status: {final_status}")
|
| 616 |
return final_status
|
| 617 |
|
|
|
|
| 618 |
# --- Gradio Interface and Main Execution Logic ---
|
| 619 |
-
GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
|
| 620 |
|
| 621 |
print("DEBUG: Defining run_and_submit_all_evaluation function.")
|
| 622 |
def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
|
| 623 |
global GLOBAL_CHUCK_AGENT
|
| 624 |
print(f"DEBUG: run_and_submit_all_evaluation called. Profile type: {type(profile)}")
|
| 625 |
logger.info(f"run_and_submit_all_evaluation called. Profile type: {type(profile)}")
|
| 626 |
-
|
| 627 |
effective_profile: Optional[gr.OAuthProfile] = None
|
| 628 |
if isinstance(profile, gr.OAuthProfile):
|
| 629 |
effective_profile = profile
|
| 630 |
-
elif args:
|
| 631 |
logger.warning(f"Profile not directly passed or None. Checking *args: {args}")
|
| 632 |
for arg_val in args:
|
| 633 |
if isinstance(arg_val, gr.OAuthProfile):
|
| 634 |
effective_profile = arg_val
|
| 635 |
logger.info(f"Found gr.OAuthProfile in *args: {effective_profile.username if effective_profile else 'None (from args)'}")
|
| 636 |
break
|
| 637 |
-
|
| 638 |
if not effective_profile:
|
| 639 |
logger.warning("User not logged in or profile not correctly passed for evaluation.")
|
| 640 |
print("DEBUG: ERROR - User not logged in or profile not correctly passed for evaluation.")
|
|
@@ -644,64 +549,65 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
|
|
| 644 |
logger.info(f"User logged in: {username}")
|
| 645 |
print(f"DEBUG: User logged in: {username}")
|
| 646 |
|
| 647 |
-
_, agent_code_url = get_space_id_agent_code_url()
|
| 648 |
-
results_log_data: List[Dict[str, Any]] = []
|
| 649 |
|
| 650 |
try:
|
| 651 |
print("DEBUG: run_and_submit_all_evaluation - Attempting to initialize/get GLOBAL_CHUCK_AGENT.")
|
| 652 |
if GLOBAL_CHUCK_AGENT is None:
|
| 653 |
-
print("DEBUG: GLOBAL_CHUCK_AGENT is None. Creating new instance.")
|
| 654 |
-
logger.info("GLOBAL_CHUCK_AGENT is None. Attempting to create a new instance.")
|
| 655 |
-
GLOBAL_CHUCK_AGENT = ChuckAgent()
|
| 656 |
print("DEBUG: GLOBAL_CHUCK_AGENT new instance created.")
|
| 657 |
else:
|
| 658 |
print("DEBUG: GLOBAL_CHUCK_AGENT already exists.")
|
| 659 |
agent_instance = GLOBAL_CHUCK_AGENT
|
| 660 |
-
|
| 661 |
print("DEBUG: run_and_submit_all_evaluation - Ensuring agent_instance._ensure_agent_initialized().")
|
| 662 |
-
agent_instance._ensure_agent_initialized()
|
| 663 |
print("DEBUG: run_and_submit_all_evaluation - Agent ensured to be initialized.")
|
| 664 |
|
| 665 |
questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
|
| 666 |
answers_payload, results_log_data = process_all_questions(agent_instance, questions_data)
|
| 667 |
submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload)
|
| 668 |
|
| 669 |
-
except EnvironmentError as e:
|
| 670 |
print(f"DEBUG: ERROR - EnvironmentError in run_and_submit_all_evaluation: {e}")
|
| 671 |
logger.critical(f"Agent instantiation or operation failed due to missing env vars: {e}")
|
| 672 |
submission_status = f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets."
|
| 673 |
-
except (ConnectionError, ValueError) as e:
|
| 674 |
print(f"DEBUG: ERROR - ConnectionError/ValueError in run_and_submit_all_evaluation: {e}")
|
| 675 |
logger.error(f"Data handling or connection error during evaluation: {e}", exc_info=True)
|
| 676 |
submission_status = str(e)
|
| 677 |
-
except RuntimeError as e:
|
| 678 |
print(f"DEBUG: ERROR - RuntimeError in run_and_submit_all_evaluation: {e}")
|
| 679 |
logger.error(f"Runtime error during evaluation: {e}", exc_info=True)
|
| 680 |
submission_status = f"Runtime Error: {e}"
|
| 681 |
-
except Exception as e:
|
| 682 |
print(f"DEBUG: ERROR - Unexpected Exception in run_and_submit_all_evaluation: {type(e).__name__} - {e}")
|
| 683 |
logger.error(f"An unexpected error occurred during the evaluation pipeline: {e}", exc_info=True)
|
| 684 |
submission_status = f"An unexpected error occurred: {e}"
|
| 685 |
-
if not results_log_data:
|
| 686 |
results_log_data = [{"Task ID": "N/A", "Question": "N/A", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
|
| 687 |
|
| 688 |
results_df = pd.DataFrame(results_log_data if results_log_data else [])
|
| 689 |
print(f"DEBUG: run_and_submit_all_evaluation returning. Status: {submission_status[:100]}...")
|
| 690 |
return submission_status, results_df
|
| 691 |
|
|
|
|
| 692 |
print("DEBUG: Building Gradio interface.")
|
| 693 |
try:
|
| 694 |
with gr.Blocks(css=".gradio-container {max-width: 960px !important; margin: auto !important;}") as demo:
|
| 695 |
print("DEBUG: gr.Blocks context entered.")
|
| 696 |
-
gr.Markdown("# Chuck's Agent Evaluation Runner")
|
| 697 |
gr.Markdown(
|
| 698 |
"""
|
| 699 |
**Instructions:**
|
| 700 |
-
1. This interface allows you to evaluate your AI agent against a predefined set of questions.
|
| 701 |
2. **Log in** to your Hugging Face account using the button below. Your HF username is used for submitting results.
|
| 702 |
3. Click '**Run Evaluation & Submit All Answers**'. This will:
|
| 703 |
a. Fetch questions from the evaluation server.
|
| 704 |
-
b. Run your configured
|
| 705 |
c. Submit the answers back to the server.
|
| 706 |
d. Display the overall status and a table of questions, your agent's answers, and reasoning.
|
| 707 |
"""
|
|
@@ -709,15 +615,15 @@ try:
|
|
| 709 |
gr.Markdown(
|
| 710 |
f"""
|
| 711 |
---
|
| 712 |
-
**Technical Notes & Configuration:**
|
| 713 |
-
* **Agent Backend**: `
|
| 714 |
-
* **OpenAI Model**: `{CONFIG.OPENAI_MODEL_ID}`.
|
| 715 |
-
* **Web Search**: Serper API (`google.serper.dev`).
|
| 716 |
* **Required Secrets**: Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are correctly set in your Hugging Face Space Secrets.
|
| 717 |
-
* **Gradio Version**: This app is tested with `gradio>=4.0`.
|
| 718 |
-
* **`
|
| 719 |
---
|
| 720 |
-
**Disclaimer**: Processing all questions can take some time.
|
| 721 |
"""
|
| 722 |
)
|
| 723 |
print("DEBUG: Gradio Markdown elements created.")
|
|
@@ -726,15 +632,15 @@ try:
|
|
| 726 |
print("DEBUG: Gradio LoginButton created.")
|
| 727 |
run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
|
| 728 |
print("DEBUG: Gradio Run Button created.")
|
| 729 |
-
|
| 730 |
with gr.Column():
|
| 731 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=8, interactive=False, show_copy_button=True)
|
| 732 |
-
results_table = gr.DataFrame(label="Detailed Results: Questions and Agent Answers", wrap=True)
|
| 733 |
print("DEBUG: Gradio output elements (Textbox, DataFrame) created.")
|
| 734 |
|
| 735 |
run_button.click(
|
| 736 |
fn=run_and_submit_all_evaluation,
|
| 737 |
-
inputs=[login_button],
|
| 738 |
outputs=[status_output, results_table]
|
| 739 |
)
|
| 740 |
print("DEBUG: Gradio run_button.click event handler set.")
|
|
@@ -742,24 +648,24 @@ try:
|
|
| 742 |
except Exception as e:
|
| 743 |
print(f"DEBUG: ERROR - Exception during Gradio UI definition: {e}")
|
| 744 |
logger.critical(f"Gradio UI definition failed: {e}", exc_info=True)
|
| 745 |
-
|
| 746 |
-
demo = None
|
| 747 |
|
| 748 |
|
| 749 |
# --- Application Startup & Shutdown Handling ---
|
| 750 |
if __name__ == "__main__":
|
| 751 |
-
print("\n" + "="*15 + " Application Startup " + "="*15)
|
| 752 |
-
|
| 753 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 754 |
space_id_startup, agent_url_startup = get_space_id_agent_code_url()
|
| 755 |
|
| 756 |
-
print(f"Python Version: {'.'.join(map(str, asyncio.sys.version_info[:3]))}")
|
| 757 |
-
print(f"Gradio Version: {gr.__version__}")
|
| 758 |
try:
|
| 759 |
-
import
|
| 760 |
-
print(f"
|
| 761 |
except ImportError:
|
| 762 |
-
print("
|
|
|
|
| 763 |
|
| 764 |
if space_host_startup:
|
| 765 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
@@ -773,18 +679,18 @@ if __name__ == "__main__":
|
|
| 773 |
print(f" Agent Code URL reported to server: {agent_url_startup}")
|
| 774 |
else:
|
| 775 |
print("ℹ️ SPACE_ID environment variable not found. Repo URL cannot be determined.")
|
| 776 |
-
|
| 777 |
print(f" Default API URL for scoring: {CONFIG.DEFAULT_API_URL}")
|
| 778 |
print(f" OpenAI Model ID for Agent: {CONFIG.OPENAI_MODEL_ID}")
|
| 779 |
-
print("="* (30 + len(" Application Startup ")) + "\n")
|
| 780 |
-
|
| 781 |
-
print("Launching Gradio Interface for Chuck Agent Evaluation...")
|
| 782 |
print("Please ensure OPENAI_API_KEY and SERPER_API_KEY are set in your environment or Space Secrets.")
|
| 783 |
-
print("
|
| 784 |
|
| 785 |
-
if demo is not None:
|
| 786 |
try:
|
| 787 |
-
demo.launch(debug=True, share=False)
|
| 788 |
except Exception as e:
|
| 789 |
print(f"DEBUG: ERROR - Gradio demo.launch() failed: {e}")
|
| 790 |
logger.critical(f"Gradio demo launch failed: {e}", exc_info=True)
|
|
@@ -792,12 +698,12 @@ if __name__ == "__main__":
|
|
| 792 |
print("DEBUG: Gradio demo.launch() finished or was interrupted.")
|
| 793 |
logger.info("Gradio demo has been closed or failed to launch.")
|
| 794 |
if GLOBAL_CHUCK_AGENT:
|
| 795 |
-
print("DEBUG: Attempting to shutdown GLOBAL_CHUCK_AGENT.")
|
| 796 |
-
logger.info("Attempting to shutdown ChuckAgent
|
| 797 |
try:
|
| 798 |
-
GLOBAL_CHUCK_AGENT.close()
|
| 799 |
print("DEBUG: GLOBAL_CHUCK_AGENT.close() called.")
|
| 800 |
-
logger.info("ChuckAgent shutdown process completed.")
|
| 801 |
except Exception as e_shutdown:
|
| 802 |
print(f"DEBUG: ERROR during GLOBAL_CHUCK_AGENT.close(): {e_shutdown}")
|
| 803 |
logger.error(f"Error during ChuckAgent final shutdown: {e_shutdown}", exc_info=True)
|
|
@@ -806,7 +712,6 @@ if __name__ == "__main__":
|
|
| 806 |
else:
|
| 807 |
print("DEBUG: ERROR - Gradio demo object is None, cannot launch. Check for errors during UI definition.")
|
| 808 |
|
| 809 |
-
print("\n" + "="*15 + " Application Shutdown " + "="*15)
|
| 810 |
else:
|
| 811 |
-
print("DEBUG: Script is being imported, not run as main.")
|
| 812 |
-
|
|
|
|
| 15 |
print("DEBUG: json imported")
|
| 16 |
import logging
|
| 17 |
print("DEBUG: logging imported")
|
| 18 |
+
# import operator # Not currently used
|
| 19 |
+
# print("DEBUG: operator imported")
|
| 20 |
import aiohttp
|
| 21 |
print("DEBUG: aiohttp imported")
|
| 22 |
+
from typing import Optional, Dict, Any, List, Tuple, Type
|
| 23 |
+
from pydantic import BaseModel, Field
|
| 24 |
+
print("DEBUG: typing and pydantic imported")
|
| 25 |
|
| 26 |
+
# --- Pydantic AI Imports ---
|
| 27 |
+
PYDANTIC_AI_LOADED = False
|
| 28 |
try:
|
| 29 |
+
from pydantic_ai import Agent
|
| 30 |
+
from pydantic_ai.llms import OpenAI as PydanticOpenAI # Alias to avoid conflict
|
| 31 |
+
from pydantic_ai.tools import tool as pydantic_tool # Alias if needed
|
| 32 |
+
print("DEBUG: pydantic-ai components imported successfully.")
|
| 33 |
+
PYDANTIC_AI_LOADED = True
|
| 34 |
+
except ImportError as e:
|
| 35 |
+
print(f"DEBUG: Failed to import pydantic-ai. Error: {e}")
|
| 36 |
+
logging.error(f"Failed to import pydantic-ai. Please ensure it is installed. Error: {e}")
|
| 37 |
+
# Dummy classes for script parsing if pydantic-ai is not installed
|
| 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): # pydantic-ai Agent.run is async
|
| 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 |
+
class PydanticOpenAI:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
def __init__(self, *args, **kwargs):
|
| 48 |
+
pass
|
|
|
|
|
|
|
| 49 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
from datetime import datetime
|
| 52 |
print("DEBUG: datetime imported")
|
|
|
|
| 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"
|
| 61 |
+
OPENAI_MODEL_ID = "gpt-4-1106-preview" # Using a model known for good function calling
|
| 62 |
SERPER_API_NUM_RESULTS = 3
|
| 63 |
WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
|
| 64 |
+
# AGENT_MAX_STEPS = 10 # Pydantic AI manages loops differently, this might not directly apply
|
| 65 |
+
# AGENT_VERBOSITY_LEVEL = 2 # Pydantic AI logging is configured differently
|
| 66 |
+
|
| 67 |
+
# MODIFIED: System Prompt for Pydantic AI with OpenAI Function Calling
|
| 68 |
+
PYDANTIC_AI_SYSTEM_PROMPT = """You are a highly intelligent and meticulous AI assistant.
|
| 69 |
+
Your primary goal is to answer the user's question accurately and concisely.
|
| 70 |
+
You have access to tools. If you need to use a tool, you will be provided with its definition.
|
| 71 |
+
Respond with your thought process and then the final answer.
|
| 72 |
+
When you have the final answer, you MUST present it on a new line prefixed with "FINAL ANSWER: " (note the space after the colon).
|
| 73 |
+
Example:
|
| 74 |
+
User: What is the capital of France?
|
| 75 |
+
Assistant:
|
| 76 |
+
THOUGHT: The user is asking for the capital of France. I should use the web_search tool.
|
| 77 |
+
[LLM would then indicate use of web_search tool, pydantic-ai handles the call]
|
| 78 |
+
OBSERVATION: [Search results for capital of France, e.g., "Paris is the capital..."]
|
| 79 |
+
THOUGHT: The search result clearly states that Paris is the capital of France. I have sufficient information.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
FINAL ANSWER: Paris
|
| 81 |
|
| 82 |
+
Example for a question not needing a tool:
|
| 83 |
+
User: What is the opposite of left?
|
| 84 |
+
Assistant:
|
| 85 |
+
THOUGHT: The question asks for the opposite of the word "left". This is general knowledge and does not require a tool. The opposite of "left" is "right".
|
| 86 |
FINAL ANSWER: right
|
| 87 |
|
| 88 |
Formatting rules for the value that comes *after* "FINAL ANSWER: ":
|
| 89 |
+
- If the question asks for a number: Provide only the number itself (e.g., FINAL ANSWER: 42). Do not use commas for thousands separation.
|
| 90 |
+
- If the question asks for a string: Provide the most concise string possible (e.g., FINAL ANSWER: right).
|
| 91 |
+
- If the question asks for a comma-separated list: Apply string/number rules to each element. Separated ONLY by a comma (e.g., FINAL ANSWER: item one,item two,three). NO space after the comma unless it's part of an item.
|
|
|
|
|
|
|
|
|
|
| 92 |
"""
|
| 93 |
|
| 94 |
SUMMARIZER_SYSTEM_PROMPT = """You are an expert at extracting concise answers from text.
|
|
|
|
| 107 |
level=logging.INFO,
|
| 108 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
| 109 |
logger = logging.getLogger(__name__)
|
| 110 |
+
# For more detailed pydantic-ai logging, you can set its logger level:
|
| 111 |
+
# logging.getLogger("pydantic_ai").setLevel(logging.DEBUG)
|
| 112 |
print("DEBUG: Logging configured.")
|
| 113 |
|
| 114 |
# --- Utility Functions ---
|
|
|
|
| 116 |
os.makedirs(directory_path, exist_ok=True)
|
| 117 |
print(f"DEBUG: Ensured directory exists: {directory_path}")
|
| 118 |
|
|
|
|
| 119 |
ensure_dir_exists(CONFIG.SCREENSHOTS_DIR)
|
| 120 |
|
| 121 |
def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
|
|
|
|
| 128 |
|
| 129 |
print("DEBUG: Utility functions defined.")
|
| 130 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
+
# --- Tool Definitions for Pydantic AI ---
|
| 133 |
+
# Pydantic AI tools are typically simple functions decorated with @tool
|
| 134 |
+
# or methods of a class.
|
| 135 |
+
|
| 136 |
+
print("DEBUG: Defining GoogleSearchTool for Pydantic AI.")
|
|
|
|
| 137 |
|
| 138 |
+
# We will define web_search as a standalone async function tool
|
| 139 |
+
# Pydantic-AI's @tool decorator will handle the description for the LLM.
|
| 140 |
+
|
| 141 |
+
if PYDANTIC_AI_LOADED: # Only define if library is loaded
|
| 142 |
+
@pydantic_tool(
|
| 143 |
+
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."
|
| 144 |
+
)
|
| 145 |
+
async def web_search(query: str) -> str: # provider="serpapi" is implicit now or part of internal logic
|
| 146 |
+
print(f"DEBUG: Pydantic AI web_search tool called with query: '{query}'")
|
| 147 |
serper_api_key = os.environ.get('SERPER_API_KEY')
|
| 148 |
if not serper_api_key:
|
| 149 |
logger.error("SERPER_API_KEY not found in environment variables.")
|
| 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 |
|
| 157 |
+
# Create session per call to maximize compatibility with event loops
|
| 158 |
async with aiohttp.ClientSession() as session:
|
| 159 |
try:
|
|
|
|
| 160 |
async with session.post(url, headers=headers, data=payload, timeout=aiohttp.ClientTimeout(total=15)) as response:
|
| 161 |
response.raise_for_status()
|
| 162 |
data = await response.json()
|
| 163 |
+
print(f"DEBUG: web_search tool received data for query '{query}'.")
|
| 164 |
+
|
| 165 |
+
# Formatting results (same as your original _format_results)
|
| 166 |
+
results = []
|
| 167 |
+
if 'organic' in data and data['organic']:
|
| 168 |
+
for result in data['organic'][:CONFIG.SERPER_API_NUM_RESULTS]:
|
| 169 |
+
title = result.get('title', 'N/A')
|
| 170 |
+
snippet = result.get('snippet', 'N/A')
|
| 171 |
+
results.append(f"Title: {title}\nSnippet: {snippet}\n---")
|
| 172 |
+
if not results and 'knowledgeGraph' in data:
|
| 173 |
+
kg = data['knowledgeGraph']
|
| 174 |
+
title = kg.get('title', '')
|
| 175 |
+
description = kg.get('description', '')
|
| 176 |
+
if title or description:
|
| 177 |
+
results.append(f"Knowledge Graph: {title}\n{description}\n---")
|
| 178 |
+
formatted_output = "\n".join(results) if results else "No relevant search results found."
|
| 179 |
+
return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
|
| 180 |
+
|
| 181 |
except asyncio.TimeoutError:
|
| 182 |
logger.error(f"Timeout performing search for '{query}'")
|
| 183 |
+
print(f"DEBUG: ERROR - Timeout in web_search tool for query '{query}'.")
|
| 184 |
return f"Error: Timeout during web search for '{query}'."
|
| 185 |
except aiohttp.ClientResponseError as e:
|
| 186 |
logger.error(f"HTTP Error performing search for '{query}': {e.status} {e.message} - Response: {await e.response.text()[:200]}")
|
| 187 |
+
print(f"DEBUG: ERROR - HTTP Error {e.status} in web_search tool for query '{query}'.")
|
| 188 |
return f"Error performing search (HTTP {e.status}): {e.message}"
|
| 189 |
except aiohttp.ClientError as e:
|
| 190 |
logger.error(f"ClientError performing search for '{query}': {type(e).__name__} - {str(e)}")
|
| 191 |
+
print(f"DEBUG: ERROR - ClientError in web_search tool for query '{query}': {str(e)}.")
|
| 192 |
return f"Error performing search (client error): {str(e)}"
|
| 193 |
except Exception as e:
|
| 194 |
logger.error(f"Unexpected error performing search for '{query}': {type(e).__name__} - {str(e)}", exc_info=True)
|
| 195 |
+
print(f"DEBUG: ERROR - Unexpected error in web_search tool for query '{query}': {str(e)}.")
|
| 196 |
return f"Error performing search: An unexpected error occurred."
|
| 197 |
+
else: # Dummy if pydantic-ai not loaded
|
| 198 |
+
async def web_search(query: str) -> str:
|
| 199 |
+
return "Error: pydantic-ai not loaded, web_search tool unavailable."
|
| 200 |
+
|
| 201 |
+
# --- Pydantic AI Agent Definition ---
|
| 202 |
+
print("DEBUG: Defining PydanticQuestionAnsweringAgent (conceptual).")
|
| 203 |
+
|
| 204 |
+
# With Pydantic AI, we don't typically subclass Agent for this kind of use case.
|
| 205 |
+
# We instantiate it and provide it with an LLM, tools, and a system prompt.
|
| 206 |
+
# The 'QuestionAnsweringAgent' class is effectively replaced by an instance of pydantic_ai.Agent
|
| 207 |
+
# The logic for process_question will be part of ChuckAgent's interaction with the pydantic_ai.Agent
|
| 208 |
+
|
| 209 |
+
# --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
|
| 210 |
+
print("DEBUG: Defining ChuckAgent (modified for Pydantic AI).")
|
| 211 |
+
class ChuckAgent:
|
| 212 |
+
def __init__(self):
|
| 213 |
+
print("DEBUG: ChuckAgent.__init__ called.")
|
| 214 |
+
logger.info("ChuckAgent initialization started (Pydantic AI version).")
|
| 215 |
+
required_env_vars = ['OPENAI_API_KEY', 'SERPER_API_KEY']
|
| 216 |
+
missing_vars = [var for var in required_env_vars if not os.environ.get(var)]
|
| 217 |
+
if missing_vars:
|
| 218 |
+
error_msg = f"Missing required environment variables: {', '.join(missing_vars)}. Please set them in Space Secrets."
|
| 219 |
+
print(f"DEBUG: ERROR - ChuckAgent missing env vars: {error_msg}")
|
| 220 |
+
logger.critical(error_msg)
|
| 221 |
+
raise EnvironmentError(error_msg)
|
| 222 |
+
print("DEBUG: ChuckAgent environment variables checked.")
|
| 223 |
+
|
| 224 |
+
self.agent_instance: Optional[Agent] = None # Will hold the pydantic_ai.Agent
|
| 225 |
+
self.llm_for_fallback: Optional[PydanticOpenAI] = None # For the summarizer
|
| 226 |
|
| 227 |
+
# Event loop management for running async pydantic-ai agent from sync Gradio
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
try:
|
| 229 |
+
self.loop = asyncio.get_running_loop()
|
| 230 |
+
print(f"DEBUG: ChuckAgent obtained running event loop: {self.loop}")
|
| 231 |
+
except RuntimeError:
|
| 232 |
+
print("DEBUG: ChuckAgent - No current running event loop, creating a new one for this thread.")
|
| 233 |
+
self.loop = asyncio.new_event_loop()
|
| 234 |
+
asyncio.set_event_loop(self.loop)
|
| 235 |
+
print(f"DEBUG: ChuckAgent using event loop: {self.loop}")
|
| 236 |
+
|
| 237 |
+
# aiohttp.ClientSession is no longer managed by ChuckAgent directly for the search tool,
|
| 238 |
+
# as each tool call will create its own.
|
| 239 |
+
# self.http_session = None # Removed
|
| 240 |
|
| 241 |
+
logger.info("ChuckAgent basic initialization complete. Pydantic AI Agent will be created on first use.")
|
| 242 |
+
print("DEBUG: ChuckAgent basic initialization complete (Pydantic AI version).")
|
| 243 |
|
| 244 |
+
def _ensure_agent_initialized(self):
|
| 245 |
+
print("DEBUG: ChuckAgent._ensure_agent_initialized called.")
|
| 246 |
+
if self.agent_instance is None and PYDANTIC_AI_LOADED:
|
| 247 |
+
print("DEBUG: ChuckAgent - self.agent_instance is None. Initializing Pydantic AI Agent...")
|
| 248 |
+
logger.info("Initializing Pydantic AI Agent within ChuckAgent...")
|
| 249 |
+
try:
|
| 250 |
+
openai_api_key = os.environ.get('OPENAI_API_KEY')
|
| 251 |
+
# Pydantic AI's OpenAI LLM configuration
|
| 252 |
+
llm = PydanticOpenAI(
|
| 253 |
+
api_key=openai_api_key,
|
| 254 |
+
model=CONFIG.OPENAI_MODEL_ID,
|
| 255 |
+
# temperature=0.0 # Adjust as needed
|
| 256 |
+
)
|
| 257 |
+
self.llm_for_fallback = llm # Can reuse for summarizer
|
| 258 |
+
|
| 259 |
+
# Instantiate Pydantic AI Agent
|
| 260 |
+
self.agent_instance = Agent(
|
| 261 |
+
llm=llm,
|
| 262 |
+
tools=[web_search], # Pass the tool function directly
|
| 263 |
+
system_prompt=CONFIG.PYDANTIC_AI_SYSTEM_PROMPT,
|
| 264 |
+
debug=True # Enable pydantic-ai debug logging
|
| 265 |
+
)
|
| 266 |
+
print("DEBUG: ChuckAgent - Pydantic AI Agent initialized successfully.")
|
| 267 |
+
logger.info("Pydantic AI Agent initialized successfully.")
|
| 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.")
|
| 275 |
+
# Create a dummy agent if Pydantic AI isn't loaded to prevent crashes,
|
| 276 |
+
# but it won't be functional.
|
| 277 |
+
self.agent_instance = Agent() # This will be the dummy agent
|
| 278 |
+
else:
|
| 279 |
+
print("DEBUG: ChuckAgent - Pydantic AI Agent already initialized.")
|
| 280 |
|
| 281 |
+
# This method replaces the old QuestionAnsweringAgent.process_question
|
| 282 |
+
async def _process_question_async(self, question_text: str) -> Tuple[str, str]:
|
| 283 |
+
print(f"DEBUG: ChuckAgent._process_question_async called for: '{question_text[:100]}...'")
|
| 284 |
+
reasoning_trace = "Pydantic AI Agent execution started."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 285 |
final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
|
| 286 |
+
|
| 287 |
+
if not self.agent_instance or (not PYDANTIC_AI_LOADED and isinstance(self.agent_instance, Agent.__class__)): # check if it's the dummy
|
| 288 |
+
logger.error("Pydantic AI Agent instance not available or dummy.")
|
| 289 |
+
return "Error: Pydantic AI Agent not properly initialized.", "Agent not initialized."
|
| 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 for now
|
| 305 |
+
|
| 306 |
+
print(f"DEBUG: Pydantic AI Agent raw output (first 500 chars): {str(agent_final_text_output)[:500]}")
|
| 307 |
+
|
| 308 |
+
match = re.search(r"FINAL ANSWER:\s*(.*)", str(agent_final_text_output), re.IGNORECASE | re.DOTALL)
|
|
|
|
|
|
|
| 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 |
+
|
| 317 |
summarizer_messages = [
|
| 318 |
{"role": "system", "content": CONFIG.SUMMARIZER_SYSTEM_PROMPT},
|
| 319 |
+
{"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.'"}
|
| 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(
|
| 340 |
+
model=CONFIG.OPENAI_MODEL_ID, # Use the same model
|
| 341 |
+
messages=summarizer_messages,
|
| 342 |
+
temperature=0.0
|
| 343 |
+
)
|
| 344 |
+
concise_answer = response.choices[0].message.content.strip()
|
| 345 |
|
| 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 = str(agent_final_text_output).strip()
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
if not final_answer_for_submission:
|
|
|
|
|
|
|
|
|
|
| 366 |
final_answer_for_submission = "Could not determine answer."
|
| 367 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
except Exception as e:
|
| 369 |
+
error_msg = f"Error processing question with Pydantic AI Agent: {type(e).__name__} - {str(e)}"
|
| 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 |
+
if self.agent_instance is None or (not PYDANTIC_AI_LOADED and isinstance(self.agent_instance, Agent.__class__)):
|
| 382 |
+
print("DEBUG: ERROR - ChuckAgent.__call__ Pydantic AI Agent was not initialized or is dummy.")
|
| 383 |
+
raise RuntimeError("Pydantic AI Agent was not initialized or is dummy.")
|
| 384 |
|
| 385 |
print(f"DEBUG: ChuckAgent submitting task to event loop {self.loop} for question: '{question[:50]}...'")
|
| 386 |
if not self.loop.is_running():
|
| 387 |
+
print(f"DEBUG: WARNING - ChuckAgent event loop {self.loop} is not running. Attempting to run _process_question_async directly.")
|
| 388 |
+
final_answer, reasoning_trace = self.loop.run_until_complete(self._process_question_async(question))
|
| 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 |
+
final_answer, reasoning_trace = future.result(timeout=180) # Increased timeout for potentially longer chains
|
| 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]}...'")
|
| 396 |
return final_answer, reasoning_trace
|
| 397 |
except Exception as e:
|
| 398 |
+
error_msg = f"Error running ChuckAgent (Pydantic AI): {type(e).__name__} - {str(e)}"
|
| 399 |
print(f"DEBUG: ERROR - Exception in ChuckAgent.__call__: {error_msg}")
|
| 400 |
logger.error(error_msg, exc_info=True)
|
| 401 |
return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg}"
|
| 402 |
|
| 403 |
+
async def shutdown_async(self):
|
| 404 |
+
print("DEBUG: ChuckAgent.shutdown_async called (Pydantic AI version).")
|
| 405 |
+
logger.info("ChuckAgent async shutdown initiated (Pydantic AI version).")
|
| 406 |
+
# No explicit http_session to close here at ChuckAgent level for the search tool
|
| 407 |
+
logger.info("ChuckAgent async shutdown complete (Pydantic AI version).")
|
| 408 |
+
print("DEBUG: ChuckAgent async shutdown complete (Pydantic AI version).")
|
| 409 |
+
|
| 410 |
+
def close(self):
|
| 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 |
asyncio.run_coroutine_threadsafe(self.shutdown_async(), self.loop).result(timeout=10)
|
| 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 |
self.loop.run_until_complete(self.shutdown_async())
|
| 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 |
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: # Changed from requests.JSONDecodeError
|
| 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}")
|
| 452 |
|
| 453 |
def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
|
| 454 |
+
print(f"DEBUG: process_all_questions called with {len(questions_data)} questions (Pydantic AI version).")
|
| 455 |
answers_payload = []
|
| 456 |
results_log_data = []
|
| 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: # Keep None check for question_text
|
| 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) # This now calls the Pydantic AI powered ChuckAgent
|
| 466 |
payload_item = {"task_id": task_id, "submitted_answer": model_ans}
|
| 467 |
+
if reasoning:
|
| 468 |
payload_item["reasoning_trace"] = reasoning
|
| 469 |
answers_payload.append(payload_item)
|
| 470 |
+
|
| 471 |
results_log_data.append({
|
| 472 |
+
"Task ID": task_id, "Question": question_text,
|
| 473 |
+
"Submitted Answer": model_ans,
|
| 474 |
"Reasoning Trace": reasoning
|
| 475 |
})
|
| 476 |
except Exception as e:
|
|
|
|
| 489 |
return "Agent did not produce any answers to submit."
|
| 490 |
submit_url = f"{base_api_url}{CONFIG.SUBMIT_URL_PATH}"
|
| 491 |
submission_data = {"username": username.strip(), "agent_code": agent_code_url, "answers": answers_payload}
|
| 492 |
+
|
| 493 |
if answers_payload:
|
| 494 |
print(f"DEBUG: Sample of first answer payload being sent: {answers_payload[0]}")
|
| 495 |
|
|
|
|
| 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]}" # Changed from requests.JSONDecodeError
|
| 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
|
| 521 |
|
| 522 |
+
|
| 523 |
# --- Gradio Interface and Main Execution Logic ---
|
| 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)}")
|
| 530 |
logger.info(f"run_and_submit_all_evaluation called. Profile type: {type(profile)}")
|
| 531 |
+
|
| 532 |
effective_profile: Optional[gr.OAuthProfile] = None
|
| 533 |
if isinstance(profile, gr.OAuthProfile):
|
| 534 |
effective_profile = profile
|
| 535 |
+
elif args:
|
| 536 |
logger.warning(f"Profile not directly passed or None. Checking *args: {args}")
|
| 537 |
for arg_val in args:
|
| 538 |
if isinstance(arg_val, gr.OAuthProfile):
|
| 539 |
effective_profile = arg_val
|
| 540 |
logger.info(f"Found gr.OAuthProfile in *args: {effective_profile.username if effective_profile else 'None (from args)'}")
|
| 541 |
break
|
| 542 |
+
|
| 543 |
if not effective_profile:
|
| 544 |
logger.warning("User not logged in or profile not correctly passed for evaluation.")
|
| 545 |
print("DEBUG: ERROR - User not logged in or profile not correctly passed for evaluation.")
|
|
|
|
| 549 |
logger.info(f"User logged in: {username}")
|
| 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() # This will now init the Pydantic AI agent
|
| 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, results_log_data = process_all_questions(agent_instance, questions_data)
|
| 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 |
+
except (ConnectionError, ValueError) as e:
|
| 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 |
+
except RuntimeError as e:
|
| 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 |
+
except Exception as e:
|
| 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": "N/A", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
|
| 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
|
| 596 |
|
| 597 |
+
|
| 598 |
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)") # Updated Title
|
| 603 |
gr.Markdown(
|
| 604 |
"""
|
| 605 |
**Instructions:**
|
| 606 |
+
1. This interface allows you to evaluate your AI agent (now using Pydantic AI) against a predefined set of questions.
|
| 607 |
2. **Log in** to your Hugging Face account using the button below. Your HF username is used for submitting results.
|
| 608 |
3. Click '**Run Evaluation & Submit All Answers**'. This will:
|
| 609 |
a. Fetch questions from the evaluation server.
|
| 610 |
+
b. Run your configured Pydantic AI agent on each question.
|
| 611 |
c. Submit the answers back to the server.
|
| 612 |
d. Display the overall status and a table of questions, your agent's answers, and reasoning.
|
| 613 |
"""
|
|
|
|
| 615 |
gr.Markdown(
|
| 616 |
f"""
|
| 617 |
---
|
| 618 |
+
**Technical Notes & Configuration (Pydantic AI Version):**
|
| 619 |
+
* **Agent Backend**: `pydantic-ai` framework.
|
| 620 |
+
* **OpenAI Model**: `{CONFIG.OPENAI_MODEL_ID}` (ensure this model supports function calling well).
|
| 621 |
+
* **Web Search**: Serper API (`google.serper.dev`) via a Pydantic AI tool.
|
| 622 |
* **Required Secrets**: Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are correctly set in your Hugging Face Space Secrets.
|
| 623 |
+
* **Gradio Version**: This app is tested with `gradio>=4.0`.
|
| 624 |
+
* **`pydantic-ai`**: Ensure `pydantic-ai` and its dependencies (like `openai>=1.3.0`) are in `requirements.txt`.
|
| 625 |
---
|
| 626 |
+
**Disclaimer**: Processing all questions can take some time.
|
| 627 |
"""
|
| 628 |
)
|
| 629 |
print("DEBUG: Gradio Markdown elements created.")
|
|
|
|
| 632 |
print("DEBUG: Gradio LoginButton created.")
|
| 633 |
run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
|
| 634 |
print("DEBUG: Gradio Run Button created.")
|
| 635 |
+
|
| 636 |
with gr.Column():
|
| 637 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=8, interactive=False, show_copy_button=True)
|
| 638 |
+
results_table = gr.DataFrame(label="Detailed Results: Questions and Agent Answers", wrap=True)
|
| 639 |
print("DEBUG: Gradio output elements (Textbox, DataFrame) created.")
|
| 640 |
|
| 641 |
run_button.click(
|
| 642 |
fn=run_and_submit_all_evaluation,
|
| 643 |
+
inputs=[login_button],
|
| 644 |
outputs=[status_output, results_table]
|
| 645 |
)
|
| 646 |
print("DEBUG: Gradio run_button.click event handler set.")
|
|
|
|
| 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 ---
|
| 655 |
if __name__ == "__main__":
|
| 656 |
+
print("\n" + "="*15 + " Application Startup (Pydantic AI) " + "="*15)
|
| 657 |
+
|
| 658 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 659 |
space_id_startup, agent_url_startup = get_space_id_agent_code_url()
|
| 660 |
|
| 661 |
+
print(f"Python Version: {'.'.join(map(str, asyncio.sys.version_info[:3]))}")
|
| 662 |
+
print(f"Gradio Version: {gr.__version__}")
|
| 663 |
try:
|
| 664 |
+
import pydantic_ai
|
| 665 |
+
print(f"pydantic-ai Version: {pydantic_ai.__version__ if hasattr(pydantic_ai, '__version__') else 'unknown'}")
|
| 666 |
except ImportError:
|
| 667 |
+
print("pydantic-ai could not be imported (version unknown). This is expected if the library has issues or is not installed.")
|
| 668 |
+
|
| 669 |
|
| 670 |
if space_host_startup:
|
| 671 |
print(f"✅ SPACE_HOST found: {space_host_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.")
|
| 682 |
+
|
| 683 |
print(f" Default API URL for scoring: {CONFIG.DEFAULT_API_URL}")
|
| 684 |
print(f" OpenAI Model ID for Agent: {CONFIG.OPENAI_MODEL_ID}")
|
| 685 |
+
print("="* (30 + len(" Application Startup (Pydantic AI) ")) + "\n")
|
| 686 |
+
|
| 687 |
+
print("Launching Gradio Interface for Chuck Agent Evaluation (Pydantic AI Version)...")
|
| 688 |
print("Please ensure OPENAI_API_KEY and SERPER_API_KEY are set in your environment or Space Secrets.")
|
| 689 |
+
print("Ensure pydantic-ai and openai>=1.3.0 are in requirements.txt.")
|
| 690 |
|
| 691 |
+
if demo is not None:
|
| 692 |
try:
|
| 693 |
+
demo.launch(debug=True, share=False)
|
| 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)
|
|
|
|
| 698 |
print("DEBUG: Gradio demo.launch() finished or was interrupted.")
|
| 699 |
logger.info("Gradio demo has been closed or failed to launch.")
|
| 700 |
if GLOBAL_CHUCK_AGENT:
|
| 701 |
+
print("DEBUG: Attempting to shutdown GLOBAL_CHUCK_AGENT (Pydantic AI version).")
|
| 702 |
+
logger.info("Attempting to shutdown ChuckAgent (Pydantic AI version)...")
|
| 703 |
try:
|
| 704 |
+
GLOBAL_CHUCK_AGENT.close()
|
| 705 |
print("DEBUG: GLOBAL_CHUCK_AGENT.close() called.")
|
| 706 |
+
logger.info("ChuckAgent shutdown process completed (Pydantic AI version).")
|
| 707 |
except Exception as e_shutdown:
|
| 708 |
print(f"DEBUG: ERROR during GLOBAL_CHUCK_AGENT.close(): {e_shutdown}")
|
| 709 |
logger.error(f"Error during ChuckAgent final shutdown: {e_shutdown}", exc_info=True)
|
|
|
|
| 712 |
else:
|
| 713 |
print("DEBUG: ERROR - Gradio demo object is None, cannot launch. Check for errors during UI definition.")
|
| 714 |
|
| 715 |
+
print("\n" + "="*15 + " Application Shutdown (Pydantic AI) " + "="*15)
|
| 716 |
else:
|
| 717 |
+
print("DEBUG: Script is being imported, not run as main.")
|
|
|