GoodLuckChuck's picture
more instruction with gpt 4.1
d0370bd verified
Raw History Blame
44.2 kB
print("DEBUG: app.py execution started (top of file)")
import os
print("DEBUG: os imported")
import gradio as gr
print("DEBUG: gradio imported")
import requests
print("DEBUG: requests imported")
import pandas as pd
print("DEBUG: pandas imported")
import asyncio
print("DEBUG: asyncio imported")
import re
print("DEBUG: re imported")
import json
print("DEBUG: json imported")
import logging
print("DEBUG: logging imported")
import operator # Used by CalculatorTool (if you re-add it)
print("DEBUG: operator imported")
import aiohttp
print("DEBUG: aiohttp imported")
from typing import Optional, Dict, Any, List, Tuple # Added Tuple
print("DEBUG: typing imported")
# Import necessary components from smolagents
try:
from smolagents import CodeAgent, Tool, OpenAIServerModel
print("DEBUG: smolagents components (CodeAgent, Tool, OpenAIServerModel) imported successfully.")
except ImportError as e: # Catch the specific error for better logging
print(f"DEBUG: Failed to import smolagents. Error: {e}")
logging.error(f"Failed to import smolagents. Please ensure it is installed and not corrupted. Error: {e}")
# Dummy classes for script parsing if smolagents is not installed or fails to import
# This allows the rest of the script to be parsed, but it won't run correctly.
class CodeAgent:
def __init__(self, *args, **kwargs):
print("DEBUG: Dummy CodeAgent initialized because smolagents failed to import.")
logging.error("Dummy CodeAgent initialized because smolagents failed to import.")
def run(self, *args, **kwargs):
print("DEBUG: Dummy CodeAgent run called.")
logging.error("Dummy CodeAgent run called.")
return "Error: smolagents not loaded."
pass
class Tool:
def __init__(self, *args, **kwargs):
print("DEBUG: Dummy Tool initialized because smolagents failed to import.")
logging.error("Dummy Tool initialized because smolagents failed to import.")
pass
class OpenAIServerModel:
def __init__(self, *args, **kwargs):
print("DEBUG: Dummy OpenAIServerModel initialized because smolagents failed to import.")
logging.error("Dummy OpenAIServerModel initialized because smolagents failed to import.")
pass
from datetime import datetime
print("DEBUG: datetime imported")
# --- Configuration ---
print("DEBUG: Defining AppConfig.")
class AppConfig:
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
QUESTIONS_URL_PATH = "/questions"
SUBMIT_URL_PATH = "/submit"
SCREENSHOTS_DIR = "screenshots" # Currently not used, but kept for consistency
OPENAI_MODEL_ID = "gpt-4.1" # Using a newer model, ensure API key has access
SERPER_API_NUM_RESULTS = 3
WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
AGENT_MAX_STEPS = 10 # Increased max steps slightly
AGENT_VERBOSITY_LEVEL = 2 # 0: silent, 1: info, 2: debug
AGENT_SYSTEM_PROMPT = """You are a highly intelligent and meticulous AI assistant. Your primary goal is to answer the user's question accurately and concisely.
You have access to a specific set of Python tools. You MUST use these exact function names as provided when you decide to use a tool.
When you generate Python code to call a tool, you MUST print the result of the tool call so it can be observed.
Available Tools:
1. `web_search(query: str, provider: str) -> str`: Use this tool to search the internet for current information. The 'provider' parameter MUST be set to "serpapi". This tool is asynchronous, so your generated code MUST call it using `await`. Example: `search_results = await web_search(query="latest news on AI", provider="serpapi")\nprint(search_results)`
Follow this process for every question:
1. THOUGHT: Understand the user's question. Identify the core information needed.
2. THOUGHT: Determine if a tool is needed. If so, which one and with what arguments. You MUST use the `web_search` tool with `provider="serpapi"` to get information from the internet if current information is needed.
3. CODE (if using a tool):
```python
# Your Python code to call the web_search tool.
# REMEMBER: Use `await` and set provider="serpapi".
# ALWAYS print the result of the tool call.
# Example:
# search_result = await web_search(query="some specific query", provider="serpapi")
# print(search_result)
```<end_code>
4. OBSERVATION: [The system will insert the printed output of your tool call here.]
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.
6. If you have the information, formulate the final answer according to the formatting rules.
CRITICAL FINAL ANSWER INSTRUCTIONS:
Your entire response, after all thoughts and tool use, MUST end with the final answer.
This final answer MUST be on its own new line and MUST start with the exact phrase "FINAL ANSWER: " (note the space after the colon).
Only the answer itself should follow this prefix. Do NOT include any of your thought process, conversational text, or additional explanations after the "FINAL ANSWER: " prefix.
Example of a full agent response structure:
THOUGHT: I need to find the capital of France.
CODE:
```python
search_result = await web_search(query="capital of France", provider="serpapi")
print(search_result)
```<end_code>
OBSERVATION: Title: Paris - Wikipedia Snippet: Paris is the capital and most populous city of France...
THOUGHT: The capital of France is Paris. I have sufficient information and will provide this as the final answer, following the formatting rules for a string.
FINAL ANSWER: Paris
Another Example (for a question "what is the opposite of left?"):
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".
FINAL ANSWER: right
Formatting rules for the value *after* "FINAL ANSWER: ":
- If the question asks for a number: Provide only the number itself (e.g., `FINAL ANSWER: 42`). Do not use commas for thousands separation (e.g., use `FINAL ANSWER: 1234` not `FINAL ANSWER: 1,234`). Do not include units like '$' or '%' unless the question specifically asks for it and it's part of the answer.
- If the question asks for a string: Provide the most concise string possible (e.g., `FINAL ANSWER: right`). Avoid articles (a, an, the) unless grammatically essential. Avoid common abbreviations (e.g., for cities like "NYC" for "New York City") unless the question implies it. Write out numerical digits as words (e.g., `FINAL ANSWER: two` instead of `FINAL ANSWER: 2`) unless numerical digits are requested.
- If the question asks for a comma-separated list: Apply the above string/number rules to each element. Ensure elements are separated ONLY by a comma (e.g., `FINAL ANSWER: item one,item two,three`). NO space after the comma unless it's part of the item itself.
- If the answer is a calculation result, provide just the number (e.g., `FINAL ANSWER: 10`).
Remember, the "FINAL ANSWER: " prefix is a literal string you must output, followed by the actual answer. Do not try to call a function named `final_answer`. Your response stops after the value following "FINAL ANSWER: ".
"""
CONFIG = AppConfig()
print("DEBUG: AppConfig defined and CONFIG instance created.")
# --- Logging Setup ---
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
print("DEBUG: Logging configured.")
# --- Utility Functions ---
def ensure_dir_exists(directory_path: str):
"""Creates a directory if it doesn't already exist."""
print(f"DEBUG: Ensuring directory exists: {directory_path}")
os.makedirs(directory_path, exist_ok=True)
ensure_dir_exists(CONFIG.SCREENSHOTS_DIR)
def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
"""Gets Space ID and constructs the agent code URL."""
space_id = os.getenv("SPACE_ID")
if space_id:
agent_code_url = f"https://huggingface.co/spaces/{space_id}/tree/main"
else:
agent_code_url = "Agent code URL not found (SPACE_ID not set)"
# print(f"DEBUG: get_space_id_agent_code_url() -> space_id: {space_id}, url: {agent_code_url}")
return space_id, agent_code_url
print("DEBUG: Utility functions defined.")
# --- Tool Definitions ---
print("DEBUG: Defining GoogleSearchTool.")
class GoogleSearchTool(Tool):
name = "web_search" # This is the name the LLM will use to call the tool
description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
inputs = {
"query": {"type": "string", "description": "The search query to execute."},
"provider": {
"type": "string",
"description": "The search provider. MUST be 'serpapi'.",
"default": "serpapi",
"nullable": True
}
}
output_type = "string"
is_async = True # Important for smolagents to know this tool's forward method is async
def __init__(self, session: aiohttp.ClientSession):
super().__init__()
self._session = session # Use the session passed from ChuckAgent
print("DEBUG: GoogleSearchTool instance created.")
async def forward(self, query: str, provider: str = "serpapi") -> str:
print(f"DEBUG: GoogleSearchTool.forward called with query: '{query}', provider: '{provider}'")
if provider != "serpapi":
logger.warning(f"GoogleSearchTool called with an unexpected provider: '{provider}'. The system prompt and tool definition instruct the LLM to use 'serpapi'.")
return "Error: Invalid search provider. Only 'serpapi' is supported for the web_search tool as per current agent configuration."
serper_api_key = os.environ.get('SERPER_API_KEY')
if not serper_api_key:
logger.error("SERPER_API_KEY not found in environment variables.")
print("DEBUG: ERROR - SERPER_API_KEY not found.")
return "Error: Serper API key not found in environment."
url = "https://google.serper.dev/search"
headers = {'X-API-KEY': serper_api_key, 'Content-Type': 'application/json'}
payload = json.dumps({'q': query, 'num': CONFIG.SERPER_API_NUM_RESULTS})
try:
async with self._session.post(url, headers=headers, data=payload, timeout=aiohttp.ClientTimeout(total=15)) as response:
response.raise_for_status()
data = await response.json()
print(f"DEBUG: GoogleSearchTool.forward received data for query '{query}'.")
return self._format_results(data)
except asyncio.TimeoutError:
logger.error(f"Timeout performing search for '{query}'")
print(f"DEBUG: ERROR - Timeout in GoogleSearchTool for query '{query}'.")
return f"Error: Timeout during web search for '{query}'."
except aiohttp.ClientResponseError as e:
logger.error(f"HTTP Error performing search for '{query}': {e.status} {e.message} - Response: {await e.response.text()[:200]}")
print(f"DEBUG: ERROR - HTTP Error {e.status} in GoogleSearchTool for query '{query}'.")
return f"Error performing search (HTTP {e.status}): {e.message}"
except aiohttp.ClientError as e:
logger.error(f"ClientError performing search for '{query}': {type(e).__name__} - {str(e)}")
print(f"DEBUG: ERROR - ClientError in GoogleSearchTool for query '{query}': {str(e)}.")
return f"Error performing search (client error): {str(e)}"
except Exception as e:
logger.error(f"Unexpected error performing search for '{query}': {type(e).__name__} - {str(e)}", exc_info=True)
print(f"DEBUG: ERROR - Unexpected error in GoogleSearchTool for query '{query}': {str(e)}.")
return f"Error performing search: An unexpected error occurred."
def _format_results(self, data: Dict[str, Any]) -> str:
results = []
if 'organic' in data and data['organic']:
for result in data['organic'][:CONFIG.SERPER_API_NUM_RESULTS]:
title = result.get('title', 'N/A')
snippet = result.get('snippet', 'N/A')
results.append(f"Title: {title}\nSnippet: {snippet}\n---")
if not results and 'knowledgeGraph' in data:
kg = data['knowledgeGraph']
title = kg.get('title', '')
description = kg.get('description', '')
if title or description:
results.append(f"Knowledge Graph: {title}\n{description}\n---")
formatted_output = "\n".join(results) if results else "No relevant search results found."
return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
# --- Agent Definition ---
print("DEBUG: Defining QuestionAnsweringAgent.")
class QuestionAnsweringAgent(CodeAgent):
def __init__(self, http_session: aiohttp.ClientSession, model: Optional[OpenAIServerModel] = None):
print(f"DEBUG: QuestionAnsweringAgent.__init__ called. http_session: {http_session}, model: {model}")
tools = [
GoogleSearchTool(session=http_session),
]
print(f"DEBUG: QuestionAnsweringAgent tools: {tools}")
effective_model = model
if effective_model is None:
print("DEBUG: QuestionAnsweringAgent effective_model is None, creating default OpenAIServerModel.")
openai_api_key = os.environ.get('OPENAI_API_KEY')
if not openai_api_key:
print("DEBUG: ERROR - OPENAI_API_KEY not found for QuestionAnsweringAgent.")
logger.critical("OPENAI_API_KEY not found. Cannot initialize OpenAIServerModel.")
raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
effective_model = OpenAIServerModel(
model_id=CONFIG.OPENAI_MODEL_ID,
api_key=openai_api_key
)
print(f"DEBUG: QuestionAnsweringAgent default OpenAIServerModel created with model_id: {CONFIG.OPENAI_MODEL_ID}")
minimal_super_args = {
"model": effective_model,
"tools": tools,
"max_steps": CONFIG.AGENT_MAX_STEPS,
}
print(f"DEBUG: QuestionAnsweringAgent minimal_super_args for super().__init__: {minimal_super_args}")
try:
super().__init__(**minimal_super_args)
print("DEBUG: QuestionAnsweringAgent super().__init__ successful (workaround active).")
self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT
print(f"DEBUG: QuestionAnsweringAgent explicitly set self.system_prompt.")
if hasattr(self, 'verbosity_level'):
self.verbosity_level = CONFIG.AGENT_VERBOSITY_LEVEL
print(f"DEBUG: QuestionAnsweringAgent set self.verbosity_level to: {self.verbosity_level}")
else:
print("DEBUG: WARNING - QuestionAnsweringAgent could not set 'verbosity_level' as an attribute after init.")
logger.warning("Could not set 'verbosity_level' as an attribute after init. It might be handled internally by CodeAgent.")
if hasattr(self, 'additional_authorized_imports'):
self.additional_authorized_imports = ["PIL"]
print(f"DEBUG: QuestionAnsweringAgent set self.additional_authorized_imports to: {self.additional_authorized_imports}")
else:
print("DEBUG: WARNING - QuestionAnsweringAgent could not set 'additional_authorized_imports' as an attribute after init.")
logger.warning("Could not set 'additional_authorized_imports' as an attribute after init.")
if not hasattr(self, 'code_writer') or self.code_writer is None:
print("DEBUG: WARNING - QuestionAnsweringAgent self.code_writer might not be initialized due to the __init__ workaround.")
logger.warning("self.code_writer might not be initialized due to the __init__ workaround. Agent may fail to generate or execute code.")
except TypeError as e:
print(f"DEBUG: ERROR - QuestionAnsweringAgent WORKAROUND FAILED: TypeError during minimal super().__init__: {e}")
logger.error(
f"WORKAROUND FAILED: Still encountered TypeError during minimal super().__init__ for QuestionAnsweringAgent: {e}. "
"This likely means the __init__ signature of smolagents.CodeAgent or its parent MultiStepAgent "
"is incompatible with this workaround or has changed.",
exc_info=True
)
raise
except Exception as e: # This will catch other exceptions like the AssertionError from smolagents
print(f"DEBUG: ERROR - QuestionAnsweringAgent Unexpected error during __init__ (possibly from tool validation): {type(e).__name__} - {e}")
logger.error(f"Unexpected error during QuestionAnsweringAgent __init__: {e}", exc_info=True)
raise
print(f"DEBUG: QuestionAnsweringAgent initialized with model: {CONFIG.OPENAI_MODEL_ID} and tools.")
async def process_question(self, question_text: str) -> Tuple[str, str]:
print(f"DEBUG: QuestionAnsweringAgent.process_question called for: '{question_text[:100]}...'")
reasoning_trace = "Agent execution started."
final_answer_for_submission = "Error: Agent did not produce a recognizable answer."
try:
raw_output_obj = self.run(question_text)
print(f"DEBUG: QuestionAnsweringAgent.run() output type: {type(raw_output_obj)}")
if hasattr(raw_output_obj, 'log_string') and callable(raw_output_obj.log_string):
full_agent_response = str(raw_output_obj.log_string())
elif hasattr(raw_output_obj, 'text') and raw_output_obj.text is not None:
full_agent_response = str(raw_output_obj.text)
elif isinstance(raw_output_obj, str):
full_agent_response = raw_output_obj
elif hasattr(raw_output_obj, 'result') and raw_output_obj.result is not None:
full_agent_response = str(raw_output_obj.result)
else:
full_agent_response = str(raw_output_obj)
logger.warning(f"Raw output from agent.run() was of type {type(raw_output_obj)}. Used generic str() conversion.")
print(f"DEBUG: QuestionAnsweringAgent full_agent_response (first 200 chars): {full_agent_response[:200]}")
reasoning_trace = full_agent_response
match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response, re.IGNORECASE | re.DOTALL)
if match:
final_answer_for_submission = match.group(1).strip()
print(f"DEBUG: QuestionAnsweringAgent extracted FINAL ANSWER: '{final_answer_for_submission}'")
else:
logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback.")
print("DEBUG: WARNING - QuestionAnsweringAgent could not find 'FINAL ANSWER:' in agent's response.")
final_answer_for_submission = full_agent_response.strip()
if not final_answer_for_submission:
logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
print("DEBUG: WARNING - QuestionAnsweringAgent extracted final answer is empty.")
final_answer_for_submission = "Could not determine answer."
except TypeError as te:
print(f"DEBUG: ERROR - TypeError in QuestionAnsweringAgent.process_question: {str(te)}")
logger.error(f"TypeError during agent processing, possibly due to __init__ workaround: {str(te)}", exc_info=True)
final_answer_for_submission = f"Error in agent processing (TypeError): {str(te)}"
reasoning_trace += f"\nTypeError encountered during processing: {str(te)}"
except Exception as e:
print(f"DEBUG: ERROR - Exception in QuestionAnsweringAgent.process_question: {type(e).__name__} - {str(e)}")
logger.error(f"Error processing question in QuestionAnsweringAgent: {type(e).__name__} - {str(e)}", exc_info=True)
final_answer_for_submission = f"Error in agent processing: {str(e)}"
reasoning_trace += f"\nError encountered: {str(e)}"
return final_answer_for_submission, reasoning_trace
# --- Agent Adapter for Synchronous Use (e.g., Gradio) ---
print("DEBUG: Defining ChuckAgent.")
class ChuckAgent:
def __init__(self):
print("DEBUG: ChuckAgent.__init__ called.")
logger.info("ChuckAgent initialization started.")
required_env_vars = ['OPENAI_API_KEY', 'SERPER_API_KEY']
missing_vars = [var for var in required_env_vars if not os.environ.get(var)]
if missing_vars:
error_msg = f"Missing required environment variables: {', '.join(missing_vars)}. Please set them in Space Secrets."
print(f"DEBUG: ERROR - ChuckAgent missing env vars: {error_msg}")
logger.critical(error_msg)
raise EnvironmentError(error_msg)
print("DEBUG: ChuckAgent environment variables checked.")
try:
# Try to get the currently running event loop (e.g., from Gradio/Uvicorn)
self.loop = asyncio.get_running_loop()
print(f"DEBUG: ChuckAgent obtained running event loop: {self.loop}")
except RuntimeError: # No current event loop.
# This case should be less common if Gradio is running, but as a fallback:
print("DEBUG: ChuckAgent - No current running event loop, creating a new one for this thread.")
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop) # Set it for the current OS thread.
print(f"DEBUG: ChuckAgent using event loop: {self.loop}")
if self.loop.is_running():
self.http_session = asyncio.run_coroutine_threadsafe(self._get_or_create_session(), self.loop).result(timeout=10)
else: # If loop isn't running (e.g. new_event_loop that wasn't started), run it to create session
self.http_session = self.loop.run_until_complete(self._get_or_create_session())
print(f"DEBUG: ChuckAgent http_session created: {self.http_session}")
self.agent_instance: Optional[QuestionAnsweringAgent] = None
logger.info("ChuckAgent basic initialization complete. Actual QuestionAnsweringAgent will be created on first use.")
print("DEBUG: ChuckAgent basic initialization complete.")
async def _get_or_create_session(self) -> aiohttp.ClientSession:
print("DEBUG: ChuckAgent._get_or_create_session called.")
logger.info("Creating aiohttp.ClientSession for ChuckAgent.")
return aiohttp.ClientSession()
def _ensure_agent_initialized(self):
print("DEBUG: ChuckAgent._ensure_agent_initialized called.")
if self.agent_instance is None:
print("DEBUG: ChuckAgent - self.agent_instance is None. Initializing QuestionAnsweringAgent...")
logger.info("Initializing QuestionAnsweringAgent within ChuckAgent...")
try:
self.agent_instance = QuestionAnsweringAgent(http_session=self.http_session)
print("DEBUG: ChuckAgent - QuestionAnsweringAgent initialized successfully.")
logger.info("QuestionAnsweringAgent initialized successfully.")
except Exception as e:
print(f"DEBUG: ERROR - ChuckAgent failed to initialize QuestionAnsweringAgent: {type(e).__name__} - {e}")
logger.error(f"Failed to initialize QuestionAnsweringAgent: {e}", exc_info=True)
raise
else:
print("DEBUG: ChuckAgent - QuestionAnsweringAgent already initialized.")
def __call__(self, question: str) -> Tuple[str, str]:
print(f"DEBUG: ChuckAgent.__call__ received question: '{question[:50]}...'")
try:
self._ensure_agent_initialized()
if self.agent_instance is None:
print("DEBUG: ERROR - ChuckAgent.__call__ QuestionAnsweringAgent was not initialized.")
raise RuntimeError("QuestionAnsweringAgent was not initialized.")
print(f"DEBUG: ChuckAgent submitting task to event loop {self.loop} for question: '{question[:50]}...'")
if not self.loop.is_running():
print(f"DEBUG: WARNING - ChuckAgent event loop {self.loop} is not running. Attempting to run process_question directly.")
final_answer, reasoning_trace = self.loop.run_until_complete(self.agent_instance.process_question(question))
else:
future = asyncio.run_coroutine_threadsafe(self.agent_instance.process_question(question), self.loop)
print(f"DEBUG: ChuckAgent waiting for future.result() for question: '{question[:50]}...'")
final_answer, reasoning_trace = future.result(timeout=180) # Increased timeout
print(f"DEBUG: ChuckAgent future.result() obtained for question: '{question[:50]}...'. Answer: '{final_answer[:50]}...'")
logger.info(f"ChuckAgent returning answer (first 50 chars): '{final_answer[:50]}...'")
return final_answer, reasoning_trace
except Exception as e:
error_msg = f"Error running ChuckAgent: {type(e).__name__} - {str(e)}"
print(f"DEBUG: ERROR - Exception in ChuckAgent.__call__: {error_msg}")
logger.error(error_msg, exc_info=True)
return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg}"
async def shutdown_async(self):
print("DEBUG: ChuckAgent.shutdown_async called.")
logger.info("ChuckAgent async shutdown initiated.")
if self.http_session and not self.http_session.closed:
await self.http_session.close()
print("DEBUG: ChuckAgent closed its aiohttp.ClientSession during async shutdown.")
logger.info("Closed ChuckAgent's aiohttp.ClientSession.")
self.http_session = None
logger.info("ChuckAgent async shutdown complete.")
print("DEBUG: ChuckAgent async shutdown complete.")
def close(self):
print("DEBUG: ChuckAgent.close called.")
if self.loop and self.loop.is_running() and self.http_session:
print("DEBUG: ChuckAgent.close - loop is running, scheduling async_shutdown.")
asyncio.run_coroutine_threadsafe(self.shutdown_async(), self.loop).result(timeout=10)
elif self.loop and not self.loop.is_running() and self.http_session :
print("DEBUG: ChuckAgent.close - loop is not running, using run_until_complete for shutdown_async.")
self.loop.run_until_complete(self.shutdown_async())
else:
print("DEBUG: ChuckAgent.close - No running loop or http_session to close.")
print("DEBUG: ChuckAgent.close finished.")
print("DEBUG: ChuckAgent class defined.")
# --- Orchestration Functions ---
def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
print(f"DEBUG: fetch_questions called with base_api_url: {base_api_url}")
questions_url = f"{base_api_url}{CONFIG.QUESTIONS_URL_PATH}"
logger.info(f"Fetching questions from: {questions_url}")
try:
response = requests.get(questions_url, timeout=30)
response.raise_for_status()
questions_data = response.json()
if not isinstance(questions_data, list) or not questions_data:
logger.warning(f"Fetched questions empty or invalid format: {questions_data}")
raise ValueError("Fetched questions list is empty or not a list.")
logger.info(f"Fetched {len(questions_data)} questions.")
print(f"DEBUG: Fetched {len(questions_data)} questions.")
return questions_data
except requests.exceptions.RequestException as e:
print(f"DEBUG: ERROR - Error fetching questions: {e}")
logger.error(f"Error fetching questions: {e}", exc_info=True)
raise ConnectionError(f"Error fetching questions: {e}")
except requests.exceptions.JSONDecodeError as e:
print(f"DEBUG: ERROR - Error decoding questions JSON: {e}")
logger.error(f"Error decoding questions JSON: {e}. Response: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True)
raise ValueError(f"Error decoding server response for questions: {e}")
def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
print(f"DEBUG: process_all_questions called with {len(questions_data)} questions.")
answers_payload = []
results_log_data = []
for i, item in enumerate(questions_data):
task_id = item.get("task_id")
question_text = item.get("question")
if not task_id or question_text is None:
logger.warning(f"Skipping item with missing task_id or question: {item}")
continue
print(f"DEBUG: Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
try:
model_ans, reasoning = agent(question_text)
# Use 'submitted_answer' as the key for the server payload
payload_item = {"task_id": task_id, "submitted_answer": model_ans}
if reasoning:
payload_item["reasoning_trace"] = reasoning
answers_payload.append(payload_item)
# For local logging, you can keep 'Submitted Answer' or change it if you prefer
results_log_data.append({
"Task ID": task_id, "Question": question_text,
"Submitted Answer": model_ans,
"Reasoning Trace": reasoning
})
except Exception as e:
print(f"DEBUG: ERROR - Error running agent on task {task_id}: {e}")
logger.error(f"Error running agent on task {task_id} ('{question_text[:50]}...'): {e}", exc_info=True)
error_answer = f"AGENT_CALL_ERROR: {str(e)}"
# Use 'submitted_answer' as the key for the server payload in error cases too
answers_payload.append({"task_id": task_id, "submitted_answer": error_answer, "reasoning_trace": str(e)})
results_log_data.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": error_answer, "Reasoning Trace": str(e)})
print(f"DEBUG: process_all_questions finished. Produced {len(answers_payload)} answers.")
return answers_payload, results_log_data
def submit_answers(base_api_url: str, username: str, agent_code_url: str, answers_payload: List[Dict[str, Any]]) -> str:
print(f"DEBUG: submit_answers called for user '{username}' with {len(answers_payload)} answers.")
if not answers_payload:
logger.warning("No answers to submit.")
return "Agent did not produce any answers to submit."
submit_url = f"{base_api_url}{CONFIG.SUBMIT_URL_PATH}"
submission_data = {"username": username.strip(), "agent_code": agent_code_url, "answers": answers_payload}
if answers_payload:
print(f"DEBUG: Sample of first answer payload being sent: {answers_payload[0]}")
logger.info(f"Submitting {len(answers_payload)} answers for user '{username}' to {submit_url}...")
try:
response = requests.post(submit_url, json=submission_data, timeout=60)
response.raise_for_status()
result_data = response.json()
final_status = (
f"Submission Successful!\nUser: {result_data.get('username', 'N/A')}\n"
f"Overall Score: {result_data.get('score', 'N/A')}% ({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
f"Message: {result_data.get('message', 'No message received.')}"
)
logger.info(f"Submission successful for user '{username}'. Score: {result_data.get('score', 'N/A')}%")
except requests.exceptions.HTTPError as e:
error_detail = f"Server responded with {e.response.status_code}."
try:
error_json = e.response.json(); error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
except requests.exceptions.JSONDecodeError: error_detail += f" Raw Response: {e.response.text[:500]}"
final_status = f"Submission Failed: {error_detail}"; logger.error(final_status)
except requests.exceptions.Timeout:
final_status = "Submission Failed: The request timed out."; logger.error(final_status)
except requests.exceptions.RequestException as e:
final_status = f"Submission Failed: Network error - {e}"; logger.error(final_status, exc_info=True)
except Exception as e:
final_status = f"An unexpected error occurred during submission: {e}"; logger.error(final_status, exc_info=True)
print(f"DEBUG: submit_answers final_status: {final_status}")
return final_status
# --- Gradio Interface and Main Execution Logic ---
GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
print("DEBUG: Defining run_and_submit_all_evaluation function.")
def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
global GLOBAL_CHUCK_AGENT
print(f"DEBUG: run_and_submit_all_evaluation called. Profile type: {type(profile)}")
logger.info(f"run_and_submit_all_evaluation called. Profile type: {type(profile)}")
effective_profile: Optional[gr.OAuthProfile] = None
if isinstance(profile, gr.OAuthProfile):
effective_profile = profile
elif args:
logger.warning(f"Profile not directly passed or None. Checking *args: {args}")
for arg_val in args:
if isinstance(arg_val, gr.OAuthProfile):
effective_profile = arg_val
logger.info(f"Found gr.OAuthProfile in *args: {effective_profile.username if effective_profile else 'None (from args)'}")
break
if not effective_profile:
logger.warning("User not logged in or profile not correctly passed for evaluation.")
print("DEBUG: ERROR - User not logged in or profile not correctly passed for evaluation.")
return "Please Login to Hugging Face with the button to run the evaluation.", pd.DataFrame()
username = effective_profile.username
logger.info(f"User logged in: {username}")
print(f"DEBUG: User logged in: {username}")
_, agent_code_url = get_space_id_agent_code_url()
results_log_data: List[Dict[str, Any]] = []
try:
print("DEBUG: run_and_submit_all_evaluation - Attempting to initialize/get GLOBAL_CHUCK_AGENT.")
if GLOBAL_CHUCK_AGENT is None:
print("DEBUG: GLOBAL_CHUCK_AGENT is None. Creating new instance.")
logger.info("GLOBAL_CHUCK_AGENT is None. Attempting to create a new instance.")
GLOBAL_CHUCK_AGENT = ChuckAgent()
print("DEBUG: GLOBAL_CHUCK_AGENT new instance created.")
else:
print("DEBUG: GLOBAL_CHUCK_AGENT already exists.")
agent_instance = GLOBAL_CHUCK_AGENT
print("DEBUG: run_and_submit_all_evaluation - Ensuring agent_instance._ensure_agent_initialized().")
agent_instance._ensure_agent_initialized()
print("DEBUG: run_and_submit_all_evaluation - Agent ensured to be initialized.")
questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
answers_payload, results_log_data = process_all_questions(agent_instance, questions_data)
submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload)
except EnvironmentError as e:
print(f"DEBUG: ERROR - EnvironmentError in run_and_submit_all_evaluation: {e}")
logger.critical(f"Agent instantiation or operation failed due to missing env vars: {e}")
submission_status = f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets."
except (ConnectionError, ValueError) as e:
print(f"DEBUG: ERROR - ConnectionError/ValueError in run_and_submit_all_evaluation: {e}")
logger.error(f"Data handling or connection error during evaluation: {e}", exc_info=True)
submission_status = str(e)
except RuntimeError as e:
print(f"DEBUG: ERROR - RuntimeError in run_and_submit_all_evaluation: {e}")
logger.error(f"Runtime error during evaluation: {e}", exc_info=True)
submission_status = f"Runtime Error: {e}"
except Exception as e:
print(f"DEBUG: ERROR - Unexpected Exception in run_and_submit_all_evaluation: {type(e).__name__} - {e}")
logger.error(f"An unexpected error occurred during the evaluation pipeline: {e}", exc_info=True)
submission_status = f"An unexpected error occurred: {e}"
if not results_log_data:
results_log_data = [{"Task ID": "N/A", "Question": "N/A", "Submitted Answer": "ERROR", "Reasoning Trace": str(e)}]
results_df = pd.DataFrame(results_log_data if results_log_data else [])
print(f"DEBUG: run_and_submit_all_evaluation returning. Status: {submission_status[:100]}...")
return submission_status, results_df
print("DEBUG: Building Gradio interface.")
try:
with gr.Blocks(css=".gradio-container {max-width: 960px !important; margin: auto !important;}") as demo:
print("DEBUG: gr.Blocks context entered.")
gr.Markdown("# Chuck's Agent Evaluation Runner")
gr.Markdown(
"""
**Instructions:**
1. This interface allows you to evaluate your AI agent against a predefined set of questions.
2. **Log in** to your Hugging Face account using the button below. Your HF username is used for submitting results.
3. Click '**Run Evaluation & Submit All Answers**'. This will:
a. Fetch questions from the evaluation server.
b. Run your configured agent (defined in `app.py`) on each question.
c. Submit the answers back to the server.
d. Display the overall status and a table of questions, your agent's answers, and reasoning.
"""
)
gr.Markdown(
f"""
---
**Technical Notes & Configuration:**
* **Agent Backend**: `smolagents` framework.
* **OpenAI Model**: `{CONFIG.OPENAI_MODEL_ID}`.
* **Web Search**: Serper API (`google.serper.dev`).
* **Required Secrets**: Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are correctly set in your Hugging Face Space Secrets.
* **Gradio Version**: This app is tested with `gradio>=4.0`. Check `requirements.txt`.
* **`smolagents` Issue**: If you see import errors for `smolagents` or `SyntaxError: f-string: unmatched '('`, it's likely an issue within the `smolagents` library itself. Please ensure you have tried upgrading or reinstalling it in your Space's `requirements.txt` (e.g., `smolagents>=0.1.0`). A workaround for a *different* potential `TypeError` during `CodeAgent` initialization is active in this script but won't fix `smolagents` internal syntax errors.
---
**Disclaimer**: Processing all questions can take some time. The interface will update once the entire process is complete. For a production system, consider asynchronous operations or background tasks for a smoother user experience.
"""
)
print("DEBUG: Gradio Markdown elements created.")
login_button = gr.LoginButton()
print("DEBUG: Gradio LoginButton created.")
run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
print("DEBUG: Gradio Run Button created.")
with gr.Column():
status_output = gr.Textbox(label="Run Status / Submission Result", lines=8, interactive=False, show_copy_button=True)
results_table = gr.DataFrame(label="Detailed Results: Questions and Agent Answers", wrap=True) # max_rows removed
print("DEBUG: Gradio output elements (Textbox, DataFrame) created.")
run_button.click(
fn=run_and_submit_all_evaluation,
inputs=[login_button],
outputs=[status_output, results_table]
)
print("DEBUG: Gradio run_button.click event handler set.")
print("DEBUG: Gradio interface definition complete.")
except Exception as e:
print(f"DEBUG: ERROR - Exception during Gradio UI definition: {e}")
logger.critical(f"Gradio UI definition failed: {e}", exc_info=True)
# Fallback or exit if UI definition fails critically
demo = None
# --- Application Startup & Shutdown Handling ---
if __name__ == "__main__":
print("\n" + "="*15 + " Application Startup " + "="*15)
space_host_startup = os.getenv("SPACE_HOST")
space_id_startup, agent_url_startup = get_space_id_agent_code_url()
print(f"Python Version: {'.'.join(map(str, asyncio.sys.version_info[:3]))}")
print(f"Gradio Version: {gr.__version__}")
try:
import smolagents
print(f"smolagents Version: {smolagents.__version__ if hasattr(smolagents, '__version__') else 'unknown'}")
except ImportError:
print("smolagents could not be imported (version unknown). This is expected if the library has issues.")
if space_host_startup:
print(f"✅ SPACE_HOST found: {space_host_startup}")
print(f" Runtime URL might be: https://{space_host_startup}")
else:
print("ℹ️ SPACE_HOST environment variable not found (likely running locally).")
if space_id_startup:
print(f"✅ SPACE_ID found: {space_id_startup}")
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
print(f" Agent Code URL reported to server: {agent_url_startup}")
else:
print("ℹ️ SPACE_ID environment variable not found. Repo URL cannot be determined.")
print(f" Default API URL for scoring: {CONFIG.DEFAULT_API_URL}")
print(f" OpenAI Model ID for Agent: {CONFIG.OPENAI_MODEL_ID}")
print("="* (30 + len(" Application Startup ")) + "\n")
print("Launching Gradio Interface for Chuck Agent Evaluation...")
print("Please ensure OPENAI_API_KEY and SERPER_API_KEY are set in your environment or Space Secrets.")
print("If you encounter smolagents import errors, please check its installation and version in requirements.txt.")
if demo is not None: # Only launch if UI definition was successful
try:
demo.launch(debug=True, share=False)
except Exception as e:
print(f"DEBUG: ERROR - Gradio demo.launch() failed: {e}")
logger.critical(f"Gradio demo launch failed: {e}", exc_info=True)
finally:
print("DEBUG: Gradio demo.launch() finished or was interrupted.")
logger.info("Gradio demo has been closed or failed to launch.")
if GLOBAL_CHUCK_AGENT:
print("DEBUG: Attempting to shutdown GLOBAL_CHUCK_AGENT.")
logger.info("Attempting to shutdown ChuckAgent and close its HTTP session...")
try:
GLOBAL_CHUCK_AGENT.close() # Use the synchronous close method
print("DEBUG: GLOBAL_CHUCK_AGENT.close() called.")
logger.info("ChuckAgent shutdown process completed.")
except Exception as e_shutdown:
print(f"DEBUG: ERROR during GLOBAL_CHUCK_AGENT.close(): {e_shutdown}")
logger.error(f"Error during ChuckAgent final shutdown: {e_shutdown}", exc_info=True)
else:
print("DEBUG: No GLOBAL_CHUCK_AGENT instance to shutdown.")
else:
print("DEBUG: ERROR - Gradio demo object is None, cannot launch. Check for errors during UI definition.")
print("\n" + "="*15 + " Application Shutdown " + "="*15)
else:
print("DEBUG: Script is being imported, not run as main.")