Update app.py
Browse files
app.py
CHANGED
|
@@ -11,16 +11,21 @@ import aiohttp
|
|
| 11 |
from typing import Optional, Dict, Any, List, Tuple
|
| 12 |
|
| 13 |
# Import necessary components from smolagents
|
|
|
|
|
|
|
| 14 |
try:
|
| 15 |
from smolagents import CodeAgent, Tool, OpenAIServerModel
|
| 16 |
-
|
| 17 |
except ImportError:
|
| 18 |
-
logging.error("Failed to import smolagents
|
| 19 |
# Dummy classes for script parsing if smolagents is not installed
|
| 20 |
class CodeAgent: pass
|
| 21 |
class Tool: pass
|
| 22 |
-
class OpenAIServerModel:
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
from datetime import datetime
|
| 26 |
|
|
@@ -30,10 +35,10 @@ class AppConfig:
|
|
| 30 |
QUESTIONS_URL_PATH = "/questions"
|
| 31 |
SUBMIT_URL_PATH = "/submit"
|
| 32 |
SCREENSHOTS_DIR = "screenshots"
|
| 33 |
-
OPENAI_MODEL_ID = "gpt-4o"
|
| 34 |
SERPER_API_NUM_RESULTS = 3
|
| 35 |
WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
|
| 36 |
-
AGENT_MAX_STEPS = 10
|
| 37 |
AGENT_VERBOSITY_LEVEL = 2
|
| 38 |
|
| 39 |
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.
|
|
@@ -41,18 +46,9 @@ You have access to a specific set of Python tools. You MUST use these exact func
|
|
| 41 |
When you generate Python code to call a tool, you MUST print the result of the tool call so it can be observed.
|
| 42 |
|
| 43 |
Available Tools:
|
| 44 |
-
1. `web_search(query: str) -> str`: Use this tool to search the internet for current information or information you do not possess. This tool is asynchronous, so your generated code MUST call it using `await`.
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
print(search_results)
|
| 48 |
-
2. `calculator(expression: str) -> str`: Use this tool for any mathematical calculations. This tool is synchronous.
|
| 49 |
-
Example:
|
| 50 |
-
result = calculator(expression="((1024 / 8) + 55 - 5) * 2")
|
| 51 |
-
print(result)
|
| 52 |
-
3. `image_retriever(url: str) -> str`: Use this tool to retrieve an image from a specific URL. This tool is asynchronous and MUST be called using `await`. It returns a status message about the retrieval.
|
| 53 |
-
Example:
|
| 54 |
-
retrieval_status = await image_retriever(url="http://example.com/image.png")
|
| 55 |
-
print(retrieval_status)
|
| 56 |
|
| 57 |
Follow this process for every question:
|
| 58 |
1. THOUGHT: Understand the user's question. Identify the core information needed.
|
|
@@ -67,7 +63,7 @@ Follow this process for every question:
|
|
| 67 |
5. THOUGHT: Analyze the observation. Is it what you expected? Do you have enough information to answer the user's question now? If not, what is your next step? (e.g., use another tool, refine a previous tool call, or formulate the answer). If you need to use another tool, go back to step 2.
|
| 68 |
6. If you have the information, formulate the final answer according to the formatting rules.
|
| 69 |
|
| 70 |
-
CRITICAL: Your *entire response* for each turn
|
| 71 |
FINAL ANSWER: [Your concise answer, strictly following the formatting rules below. Do NOT include your thought process here, only the answer itself.]
|
| 72 |
|
| 73 |
Formatting rules for the value in FINAL ANSWER:
|
|
@@ -110,11 +106,11 @@ async def close_shared_http_session():
|
|
| 110 |
|
| 111 |
# --- Tool Definitions ---
|
| 112 |
class ImageRetrievalTool(Tool):
|
| 113 |
-
name = "image_retriever"
|
| 114 |
description = "Retrieves an image from a web URL. Input: a string URL. Output: a status message."
|
| 115 |
inputs = {"url": {"type": "string", "description": "The direct URL of the image to retrieve."}}
|
| 116 |
output_type = "string"
|
| 117 |
-
is_async = True
|
| 118 |
|
| 119 |
def __init__(self, session: aiohttp.ClientSession):
|
| 120 |
super().__init__()
|
|
@@ -145,7 +141,7 @@ class ImageRetrievalTool(Tool):
|
|
| 145 |
return f"Error retrieving image: {str(e)}"
|
| 146 |
|
| 147 |
class WebSearchTool(Tool):
|
| 148 |
-
name = "web_search"
|
| 149 |
description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
|
| 150 |
inputs = {"query": {"type": "string", "description": "The search query to execute."}}
|
| 151 |
output_type = "string"
|
|
@@ -198,7 +194,7 @@ class WebSearchTool(Tool):
|
|
| 198 |
return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
|
| 199 |
|
| 200 |
class CalculatorTool(Tool):
|
| 201 |
-
name = "calculator"
|
| 202 |
description = "Performs mathematical calculations. Input: a string mathematical expression. Output: calculation result string."
|
| 203 |
inputs = {"expression": {"type": "string", "description": "The mathematical expression to evaluate (e.g., '2+2*5')."}}
|
| 204 |
output_type = "string"
|
|
@@ -213,13 +209,12 @@ class CalculatorTool(Tool):
|
|
| 213 |
}
|
| 214 |
self.allowed_chars = "0123456789+-*/^(). "
|
| 215 |
|
| 216 |
-
async def forward(self, expression: str) -> str:
|
| 217 |
logger.info(f"CalculatorTool called with expression: {expression}")
|
| 218 |
try:
|
| 219 |
safe_expr = "".join(c for c in expression if c in self.allowed_chars)
|
| 220 |
if not safe_expr:
|
| 221 |
return "Error: Empty or invalid expression for calculator."
|
| 222 |
-
# Using eval safely
|
| 223 |
result = eval(safe_expr, {"__builtins__": {}}, self.operations) # type: ignore
|
| 224 |
return f"Calculation result: {safe_expr} = {float(result)}"
|
| 225 |
except Exception as e:
|
|
@@ -240,59 +235,35 @@ class QuestionAnsweringAgent(CodeAgent):
|
|
| 240 |
openai_api_key = os.environ.get('OPENAI_API_KEY')
|
| 241 |
if not openai_api_key:
|
| 242 |
raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
|
|
|
|
|
|
|
|
|
|
| 243 |
effective_model = OpenAIServerModel(
|
| 244 |
model_id=CONFIG.OPENAI_MODEL_ID,
|
| 245 |
-
api_key=openai_api_key
|
| 246 |
)
|
| 247 |
|
| 248 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
try:
|
| 250 |
-
|
| 251 |
-
# We provide only arguments that MultiStepAgent directly accepts to avoid TypeError.
|
| 252 |
-
# MultiStepAgent's signature is typically (model, tools, max_steps, code_writer, verbosity_level, etc.)
|
| 253 |
-
# However, the TypeError indicates it's not accepting 'system_prompt' if passed through kwargs.
|
| 254 |
-
# The 'code_writer' is normally created by CodeAgent and passed to its super.
|
| 255 |
-
# To be safe, we initialize MultiStepAgent with its core, non-problematic args.
|
| 256 |
-
super(CodeAgent, self).__init__( # Calling parent of CodeAgent (MultiStepAgent)
|
| 257 |
model=effective_model,
|
| 258 |
tools=tools_list,
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
logger.info("QuestionAnsweringAgent > MultiStepAgent super().__init__ called with MINIMAL args (workaround).")
|
| 264 |
-
|
| 265 |
-
# Step 2: Now set CodeAgent's own attributes and initialize its CodeWriter
|
| 266 |
-
self.model = effective_model # Already passed to MultiStepAgent, but good to have on self.
|
| 267 |
-
self.tools = tools_list # Already passed to MultiStepAgent, but good to have on self.
|
| 268 |
-
self.system_prompt = CONFIG.AGENT_SYSTEM_PROMPT # CRITICAL: for CodeWriter
|
| 269 |
-
self.additional_authorized_imports = ["PIL", "pandas"] # AUTHORIZED PANDAS
|
| 270 |
-
self.verbosity_level = CONFIG.AGENT_VERBOSITY_LEVEL # For CodeAgent's own logging if it uses this attribute
|
| 271 |
-
# self.max_steps is handled by MultiStepAgent.
|
| 272 |
-
|
| 273 |
-
# Step 3: Manually create and assign the CodeWriter.
|
| 274 |
-
# This is the most important part of the workaround to ensure the system_prompt is used.
|
| 275 |
-
# CodeWriter is imported at the top of the file.
|
| 276 |
-
self.code_writer = CodeWriter(
|
| 277 |
-
model=self.model,
|
| 278 |
-
tools=self.tools,
|
| 279 |
-
system_prompt=self.system_prompt,
|
| 280 |
-
additional_authorized_imports=self.additional_authorized_imports
|
| 281 |
-
# CodeWriter might accept other parameters; refer to its definition if needed.
|
| 282 |
)
|
| 283 |
-
logger.info("
|
| 284 |
-
|
| 285 |
except TypeError as e:
|
| 286 |
-
logger.error(f"
|
| 287 |
-
raise e
|
| 288 |
-
except
|
| 289 |
-
logger.error(f"
|
| 290 |
-
raise e_imp
|
| 291 |
-
except Exception as e_init: # Catch any other exception during this delicate init
|
| 292 |
-
logger.error(f"Unexpected error during QuestionAnsweringAgent __init__ (workaround): {e_init}", exc_info=True)
|
| 293 |
raise e_init
|
| 294 |
-
|
| 295 |
-
logger.info(f"QuestionAnsweringAgent initialized (with workaround) with model: {CONFIG.OPENAI_MODEL_ID}.")
|
| 296 |
|
| 297 |
|
| 298 |
async def process_question(self, question_text: str) -> Tuple[str, str]:
|
|
@@ -301,42 +272,37 @@ class QuestionAnsweringAgent(CodeAgent):
|
|
| 301 |
try:
|
| 302 |
logger.info(f"Processing question with CodeAgent: {question_text[:100]}...")
|
| 303 |
|
| 304 |
-
# self.run() is synchronous for CodeAgent
|
| 305 |
raw_output_obj = self.run(question_text)
|
| 306 |
|
| 307 |
-
# Attempt to get the most complete textual output from the agent's run
|
| 308 |
if hasattr(raw_output_obj, 'log_string') and callable(raw_output_obj.log_string):
|
| 309 |
full_agent_response = str(raw_output_obj.log_string())
|
| 310 |
-
elif hasattr(raw_output_obj, 'text') and raw_output_obj.text is not None:
|
| 311 |
full_agent_response = str(raw_output_obj.text)
|
| 312 |
-
elif isinstance(raw_output_obj, str):
|
| 313 |
full_agent_response = raw_output_obj
|
| 314 |
-
elif hasattr(raw_output_obj, 'result') and raw_output_obj.result is not None:
|
| 315 |
full_agent_response = str(raw_output_obj.result)
|
| 316 |
else:
|
| 317 |
-
full_agent_response = str(raw_output_obj)
|
| 318 |
|
| 319 |
-
reasoning_trace = full_agent_response
|
| 320 |
logger.info(f"CodeAgent full response (first 500 chars): {full_agent_response[:500]}...")
|
| 321 |
|
| 322 |
-
# Regex to find "FINAL ANSWER:" and capture everything after it.
|
| 323 |
-
# re.DOTALL allows '.' to match newlines.
|
| 324 |
match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response, re.IGNORECASE | re.DOTALL)
|
| 325 |
if match:
|
| 326 |
final_answer_for_submission = match.group(1).strip()
|
| 327 |
logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}")
|
| 328 |
else:
|
| 329 |
logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback.")
|
| 330 |
-
# The full response might contain reasoning steps, not just the answer.
|
| 331 |
-
# This might need further cleaning if it's too verbose for submission.
|
| 332 |
final_answer_for_submission = full_agent_response.strip()
|
| 333 |
|
| 334 |
-
if not final_answer_for_submission:
|
| 335 |
logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
|
| 336 |
final_answer_for_submission = "Could not determine answer."
|
| 337 |
|
| 338 |
-
except TypeError as te:
|
| 339 |
-
logger.error(f"TypeError during agent processing
|
| 340 |
final_answer_for_submission = f"Error in agent processing (TypeError): {str(te)}"
|
| 341 |
reasoning_trace += f"\nTypeError encountered: {str(te)}"
|
| 342 |
except Exception as e:
|
|
@@ -359,18 +325,27 @@ class ChuckAgent:
|
|
| 359 |
logger.info("ChuckAgent initialization started")
|
| 360 |
try:
|
| 361 |
self.loop = asyncio.get_running_loop()
|
| 362 |
-
except RuntimeError:
|
| 363 |
self.loop = asyncio.new_event_loop()
|
| 364 |
asyncio.set_event_loop(self.loop)
|
| 365 |
|
| 366 |
self.http_session = self.loop.run_until_complete(get_shared_http_session())
|
| 367 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
logger.info("ChuckAgent fully initialized")
|
| 369 |
|
| 370 |
def __call__(self, question: str) -> Tuple[str, str]:
|
| 371 |
logger.info(f"ChuckAgent received question (first 50 chars): {question[:50]}...")
|
| 372 |
try:
|
| 373 |
-
# Ensure the correct event loop is set for this thread if Gradio runs in a separate one.
|
| 374 |
if asyncio.get_event_loop() is not self.loop:
|
| 375 |
asyncio.set_event_loop(self.loop)
|
| 376 |
|
|
@@ -390,6 +365,7 @@ class ChuckAgent:
|
|
| 390 |
logger.info("ChuckAgent shutdown complete.")
|
| 391 |
|
| 392 |
# --- Core Evaluation Logic ---
|
|
|
|
| 393 |
def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
|
| 394 |
space_id = os.getenv("SPACE_ID")
|
| 395 |
agent_code_url = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Agent code URL not found (SPACE_ID not set)"
|
|
@@ -410,7 +386,7 @@ def fetch_questions(base_api_url: str) -> List[Dict[str, Any]]:
|
|
| 410 |
except requests.exceptions.RequestException as e:
|
| 411 |
logger.error(f"Error fetching questions: {e}", exc_info=True)
|
| 412 |
raise ConnectionError(f"Error fetching questions: {e}") from e
|
| 413 |
-
except (requests.exceptions.JSONDecodeError, ValueError) as e:
|
| 414 |
logger.error(f"Error decoding questions JSON or invalid data: {e}. Response text: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True)
|
| 415 |
raise ValueError(f"Error decoding server response for questions: {e}") from e
|
| 416 |
|
|
@@ -422,24 +398,24 @@ def process_all_questions(agent: ChuckAgent, questions_data: List[Dict[str, Any]
|
|
| 422 |
for i, item in enumerate(questions_data):
|
| 423 |
task_id = item.get("task_id")
|
| 424 |
question_text = item.get("question")
|
| 425 |
-
if not task_id or question_text is None:
|
| 426 |
logger.warning(f"Skipping item {i+1} with missing data: {item}")
|
| 427 |
continue
|
| 428 |
logger.info(f"Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
|
| 429 |
model_ans, reasoning = "Error: Agent did not run", "No reasoning generated."
|
| 430 |
try:
|
| 431 |
model_ans, reasoning = agent(question_text)
|
| 432 |
-
except Exception as e:
|
| 433 |
logger.error(f"Error running agent on task {task_id}: {e}", exc_info=True)
|
| 434 |
-
model_ans = f"AGENT_CALL_ERROR: {e}"
|
| 435 |
-
reasoning = str(e)
|
| 436 |
|
| 437 |
payload_item = {"task_id": task_id, "submitted_answer": model_ans}
|
| 438 |
-
if reasoning:
|
| 439 |
payload_item["reasoning_trace"] = reasoning
|
| 440 |
answers_payload.append(payload_item)
|
| 441 |
|
| 442 |
-
results_log.append({
|
| 443 |
"Task ID": task_id,
|
| 444 |
"Question": question_text,
|
| 445 |
"Submitted Answer": model_ans,
|
|
@@ -456,8 +432,8 @@ def submit_answers(base_api_url: str, username: str, agent_code_url: str, answer
|
|
| 456 |
submission_data = {"username": username.strip(), "agent_code": agent_code_url, "answers": answers_payload}
|
| 457 |
logger.info(f"Submitting {len(answers_payload)} answers for user '{username}'...")
|
| 458 |
try:
|
| 459 |
-
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 460 |
-
response.raise_for_status()
|
| 461 |
result_data = response.json()
|
| 462 |
return (
|
| 463 |
f"Submission Successful!\nUser: {result_data.get('username', 'N/A')}\n"
|
|
@@ -468,50 +444,47 @@ def submit_answers(base_api_url: str, username: str, agent_code_url: str, answer
|
|
| 468 |
except requests.exceptions.HTTPError as e:
|
| 469 |
error_detail = f"Server responded with {e.response.status_code}."
|
| 470 |
try:
|
| 471 |
-
error_json = e.response.json()
|
| 472 |
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 473 |
-
except requests.exceptions.JSONDecodeError:
|
| 474 |
-
error_detail += f" Raw Response: {e.response.text[:500]}"
|
| 475 |
logger.error(f"Submission Failed: {error_detail}")
|
| 476 |
return f"Submission Failed: {error_detail}"
|
| 477 |
except requests.exceptions.Timeout:
|
| 478 |
logger.error("Submission Failed: The request timed out.")
|
| 479 |
return "Submission Failed: The request timed out."
|
| 480 |
-
except requests.exceptions.RequestException as e:
|
| 481 |
logger.error(f"Submission Failed: Network error - {e}", exc_info=True)
|
| 482 |
return f"Submission Failed: Network error - {e}"
|
| 483 |
-
except Exception as e:
|
| 484 |
logger.error(f"An unexpected error occurred during submission: {e}", exc_info=True)
|
| 485 |
return f"An unexpected error occurred during submission: {e}"
|
| 486 |
|
| 487 |
# --- Gradio Interface Main Function ---
|
| 488 |
GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
|
| 489 |
|
| 490 |
-
# Gradio function signature adjustment to handle potential extra args from LoginButton
|
| 491 |
def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
|
| 492 |
global GLOBAL_CHUCK_AGENT
|
| 493 |
logger.info(f"run_and_submit_all_evaluation received profile: {type(profile)}")
|
| 494 |
-
if args:
|
| 495 |
logger.warning(f"run_and_submit_all_evaluation received unexpected additional args: {args}")
|
| 496 |
|
| 497 |
-
# Ensure 'profile' is the actual OAuthProfile object
|
| 498 |
if not isinstance(profile, gr.OAuthProfile) and profile is not None:
|
| 499 |
logger.warning(f"Profile argument is not of type gr.OAuthProfile or None. Received: {profile}")
|
| 500 |
-
# Attempt to find the profile in args if it was misplaced by Gradio's event system
|
| 501 |
found_profile_in_args = False
|
| 502 |
-
for arg_val in args:
|
| 503 |
if isinstance(arg_val, gr.OAuthProfile):
|
| 504 |
-
profile = arg_val
|
| 505 |
found_profile_in_args = True
|
| 506 |
logger.info(f"Found gr.OAuthProfile in *args: {profile.username if profile else 'None (from args)'}")
|
| 507 |
break
|
| 508 |
-
if not found_profile_in_args and profile is None:
|
| 509 |
logger.error("Could not identify a valid gr.OAuthProfile object.")
|
| 510 |
return "Login error: Could not identify user profile.", pd.DataFrame()
|
| 511 |
|
| 512 |
logger.info(f"Effective profile for processing: {profile.username if profile else 'None'}")
|
| 513 |
|
| 514 |
-
if not profile:
|
| 515 |
logger.warning("User not logged in for evaluation.")
|
| 516 |
return "Please Login to Hugging Face with the button to run the evaluation.", pd.DataFrame()
|
| 517 |
|
|
@@ -520,26 +493,26 @@ def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *ar
|
|
| 520 |
|
| 521 |
_, agent_code_url = get_space_id_agent_code_url()
|
| 522 |
logger.info(f"Agent code URL: {agent_code_url}")
|
| 523 |
-
results_log_data: List[Dict[str, Any]] = []
|
| 524 |
|
| 525 |
try:
|
| 526 |
if GLOBAL_CHUCK_AGENT is None:
|
| 527 |
-
GLOBAL_CHUCK_AGENT = ChuckAgent()
|
| 528 |
-
agent_instance = GLOBAL_CHUCK_AGENT
|
| 529 |
-
except EnvironmentError as e:
|
| 530 |
logger.critical(f"Agent instantiation failed due to missing env vars: {e}")
|
| 531 |
return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
|
| 532 |
-
except Exception as e:
|
| 533 |
-
logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
|
| 534 |
return f"Error initializing agent: {e}", pd.DataFrame()
|
| 535 |
|
| 536 |
try:
|
| 537 |
questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
|
| 538 |
-
answers_payload, results_log_data = process_all_questions(agent_instance, questions_data)
|
| 539 |
submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload)
|
| 540 |
-
except (ConnectionError, ValueError) as e:
|
| 541 |
submission_status = str(e)
|
| 542 |
-
except Exception as e:
|
| 543 |
logger.error(f"An unexpected error occurred during evaluation pipeline: {e}", exc_info=True)
|
| 544 |
submission_status = f"An unexpected error occurred: {e}"
|
| 545 |
|
|
@@ -568,15 +541,15 @@ with gr.Blocks() as demo:
|
|
| 568 |
**Technical Notes:**
|
| 569 |
* The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
|
| 570 |
* Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets.
|
| 571 |
-
*
|
| 572 |
-
* `
|
| 573 |
"""
|
| 574 |
)
|
| 575 |
|
| 576 |
login_button = gr.LoginButton()
|
| 577 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 578 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=10, interactive=False)
|
| 579 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 580 |
|
| 581 |
run_button.click(
|
| 582 |
fn=run_and_submit_all_evaluation,
|
|
@@ -604,34 +577,32 @@ if __name__ == "__main__":
|
|
| 604 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 605 |
|
| 606 |
print(f" Default API URL: {CONFIG.DEFAULT_API_URL}")
|
| 607 |
-
print(f" OpenAI Model ID: {CONFIG.OPENAI_MODEL_ID}")
|
| 608 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 609 |
print("Launching Gradio Interface for Chuck Agent Evaluation...")
|
| 610 |
|
| 611 |
try:
|
| 612 |
-
demo.launch(debug=True, share=False)
|
| 613 |
finally:
|
| 614 |
-
# Attempt to gracefully close the aiohttp session on exit
|
| 615 |
loop_to_use = None
|
| 616 |
-
# Check if event loop for http_session exists and is running
|
| 617 |
if GLOBAL_CHUCK_AGENT and hasattr(GLOBAL_CHUCK_AGENT, 'http_session') and GLOBAL_CHUCK_AGENT.http_session:
|
| 618 |
loop_to_use = GLOBAL_CHUCK_AGENT.http_session.loop
|
| 619 |
-
elif SHARED_HTTP_SESSION:
|
| 620 |
loop_to_use = SHARED_HTTP_SESSION.loop
|
| 621 |
|
| 622 |
if loop_to_use and loop_to_use.is_running():
|
| 623 |
logger.info("Attempting to shutdown agent and close HTTP session in finally block...")
|
| 624 |
try:
|
| 625 |
-
|
| 626 |
-
current_loop
|
| 627 |
-
if current_loop is not loop_to_use and not loop_to_use.is_closed(): # Check if loop_to_use is not closed
|
| 628 |
asyncio.set_event_loop(loop_to_use)
|
| 629 |
|
| 630 |
if GLOBAL_CHUCK_AGENT:
|
| 631 |
loop_to_use.run_until_complete(GLOBAL_CHUCK_AGENT.shutdown())
|
| 632 |
-
elif SHARED_HTTP_SESSION and not SHARED_HTTP_SESSION.closed:
|
| 633 |
loop_to_use.run_until_complete(close_shared_http_session())
|
| 634 |
-
except Exception as e:
|
| 635 |
logger.error(f"Error during final cleanup of HTTP session: {e}", exc_info=True)
|
| 636 |
else:
|
| 637 |
-
logger.info("No active HTTP session or running loop to close in finally block.")
|
|
|
|
|
|
| 11 |
from typing import Optional, Dict, Any, List, Tuple
|
| 12 |
|
| 13 |
# Import necessary components from smolagents
|
| 14 |
+
# We will try to import only the main components.
|
| 15 |
+
# The explicit CodeWriter import is removed as it might be causing the root import error.
|
| 16 |
try:
|
| 17 |
from smolagents import CodeAgent, Tool, OpenAIServerModel
|
| 18 |
+
# If this base import works, OpenAIServerModel will be the real one.
|
| 19 |
except ImportError:
|
| 20 |
+
logging.error("CRITICAL: Failed to import base smolagents components (CodeAgent, Tool, OpenAIServerModel). Ensure smolagents is correctly installed via requirements.txt.")
|
| 21 |
# Dummy classes for script parsing if smolagents is not installed
|
| 22 |
class CodeAgent: pass
|
| 23 |
class Tool: pass
|
| 24 |
+
class OpenAIServerModel: # This dummy is what's causing the TypeError if import fails
|
| 25 |
+
def __init__(self, *args, **kwargs): # Make dummy accept args to avoid immediate crash
|
| 26 |
+
logging.warning("Using DUMMY OpenAIServerModel due to import failure.")
|
| 27 |
+
pass
|
| 28 |
+
# We don't need a dummy CodeWriter if we are not explicitly importing it.
|
| 29 |
|
| 30 |
from datetime import datetime
|
| 31 |
|
|
|
|
| 35 |
QUESTIONS_URL_PATH = "/questions"
|
| 36 |
SUBMIT_URL_PATH = "/submit"
|
| 37 |
SCREENSHOTS_DIR = "screenshots"
|
| 38 |
+
OPENAI_MODEL_ID = "gpt-4o"
|
| 39 |
SERPER_API_NUM_RESULTS = 3
|
| 40 |
WEB_SEARCH_MAX_OUTPUT_LENGTH = 3000
|
| 41 |
+
AGENT_MAX_STEPS = 10
|
| 42 |
AGENT_VERBOSITY_LEVEL = 2
|
| 43 |
|
| 44 |
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.
|
|
|
|
| 46 |
When you generate Python code to call a tool, you MUST print the result of the tool call so it can be observed.
|
| 47 |
|
| 48 |
Available Tools:
|
| 49 |
+
1. `web_search(query: str) -> str`: Use this tool to search the internet for current information or information you do not possess. This tool is asynchronous, so your generated code MUST call it using `await`. Example: `search_results = await web_search(query="latest news on AI")\nprint(search_results)`
|
| 50 |
+
2. `calculator(expression: str) -> str`: Use this tool for any mathematical calculations. This tool is synchronous. Example: `result = calculator(expression="((1024 / 8) + 55 - 5) * 2")\nprint(result)`
|
| 51 |
+
3. `image_retriever(url: str) -> str`: Use this tool to retrieve an image from a specific URL. This tool is asynchronous and MUST be called using `await`. Example: `retrieval_status = await image_retriever(url="http://example.com/image.png")\nprint(retrieval_status)`. The tool returns a status message.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
Follow this process for every question:
|
| 54 |
1. THOUGHT: Understand the user's question. Identify the core information needed.
|
|
|
|
| 63 |
5. THOUGHT: Analyze the observation. Is it what you expected? Do you have enough information to answer the user's question now? If not, what is your next step? (e.g., use another tool, refine a previous tool call, or formulate the answer). If you need to use another tool, go back to step 2.
|
| 64 |
6. If you have the information, formulate the final answer according to the formatting rules.
|
| 65 |
|
| 66 |
+
CRITICAL: Your *entire response* for each turn must culminate in the final answer using this exact template on a new line:
|
| 67 |
FINAL ANSWER: [Your concise answer, strictly following the formatting rules below. Do NOT include your thought process here, only the answer itself.]
|
| 68 |
|
| 69 |
Formatting rules for the value in FINAL ANSWER:
|
|
|
|
| 106 |
|
| 107 |
# --- Tool Definitions ---
|
| 108 |
class ImageRetrievalTool(Tool):
|
| 109 |
+
name = "image_retriever"
|
| 110 |
description = "Retrieves an image from a web URL. Input: a string URL. Output: a status message."
|
| 111 |
inputs = {"url": {"type": "string", "description": "The direct URL of the image to retrieve."}}
|
| 112 |
output_type = "string"
|
| 113 |
+
is_async = True
|
| 114 |
|
| 115 |
def __init__(self, session: aiohttp.ClientSession):
|
| 116 |
super().__init__()
|
|
|
|
| 141 |
return f"Error retrieving image: {str(e)}"
|
| 142 |
|
| 143 |
class WebSearchTool(Tool):
|
| 144 |
+
name = "web_search"
|
| 145 |
description = "Searches the web using Serper API for information. Input: a string search query. Output: formatted search results string."
|
| 146 |
inputs = {"query": {"type": "string", "description": "The search query to execute."}}
|
| 147 |
output_type = "string"
|
|
|
|
| 194 |
return formatted_output[:CONFIG.WEB_SEARCH_MAX_OUTPUT_LENGTH]
|
| 195 |
|
| 196 |
class CalculatorTool(Tool):
|
| 197 |
+
name = "calculator"
|
| 198 |
description = "Performs mathematical calculations. Input: a string mathematical expression. Output: calculation result string."
|
| 199 |
inputs = {"expression": {"type": "string", "description": "The mathematical expression to evaluate (e.g., '2+2*5')."}}
|
| 200 |
output_type = "string"
|
|
|
|
| 209 |
}
|
| 210 |
self.allowed_chars = "0123456789+-*/^(). "
|
| 211 |
|
| 212 |
+
async def forward(self, expression: str) -> str:
|
| 213 |
logger.info(f"CalculatorTool called with expression: {expression}")
|
| 214 |
try:
|
| 215 |
safe_expr = "".join(c for c in expression if c in self.allowed_chars)
|
| 216 |
if not safe_expr:
|
| 217 |
return "Error: Empty or invalid expression for calculator."
|
|
|
|
| 218 |
result = eval(safe_expr, {"__builtins__": {}}, self.operations) # type: ignore
|
| 219 |
return f"Calculation result: {safe_expr} = {float(result)}"
|
| 220 |
except Exception as e:
|
|
|
|
| 235 |
openai_api_key = os.environ.get('OPENAI_API_KEY')
|
| 236 |
if not openai_api_key:
|
| 237 |
raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
|
| 238 |
+
# This is where the TypeError "OpenAIServerModel() takes no arguments" occurred
|
| 239 |
+
# because the DUMMY OpenAIServerModel was being used due to earlier import failure.
|
| 240 |
+
# If the main `from smolagents import ... OpenAIServerModel` works, this will be the REAL one.
|
| 241 |
effective_model = OpenAIServerModel(
|
| 242 |
model_id=CONFIG.OPENAI_MODEL_ID,
|
| 243 |
+
api_key=openai_api_key # The real OpenAIServerModel picks this from env if not passed
|
| 244 |
)
|
| 245 |
|
| 246 |
+
# REVERTED TO STANDARD CodeAgent INITIALIZATION
|
| 247 |
+
# This assumes that if `smolagents` imports correctly, its internal
|
| 248 |
+
# `CodeAgent` -> `MultiStepAgent` initialization will work.
|
| 249 |
+
# If the "MultiStepAgent TypeError" returns, it means the installed `smolagents` version
|
| 250 |
+
# still has that internal issue.
|
| 251 |
try:
|
| 252 |
+
super().__init__(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
model=effective_model,
|
| 254 |
tools=tools_list,
|
| 255 |
+
system_prompt=CONFIG.AGENT_SYSTEM_PROMPT,
|
| 256 |
+
additional_authorized_imports=["PIL", "pandas"], # Added "pandas"
|
| 257 |
+
max_steps=CONFIG.AGENT_MAX_STEPS,
|
| 258 |
+
verbosity_level=CONFIG.AGENT_VERBOSITY_LEVEL
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
)
|
| 260 |
+
logger.info(f"QuestionAnsweringAgent initialized successfully with model: {CONFIG.OPENAI_MODEL_ID}.")
|
|
|
|
| 261 |
except TypeError as e:
|
| 262 |
+
logger.error(f"TypeError during QuestionAnsweringAgent super().__init__: {e}. This might be the 'MultiStepAgent' issue if smolagents version is problematic.", exc_info=True)
|
| 263 |
+
raise e # Re-raise to see the error clearly if it happens
|
| 264 |
+
except Exception as e_init:
|
| 265 |
+
logger.error(f"Unexpected error during QuestionAnsweringAgent __init__: {e_init}", exc_info=True)
|
|
|
|
|
|
|
|
|
|
| 266 |
raise e_init
|
|
|
|
|
|
|
| 267 |
|
| 268 |
|
| 269 |
async def process_question(self, question_text: str) -> Tuple[str, str]:
|
|
|
|
| 272 |
try:
|
| 273 |
logger.info(f"Processing question with CodeAgent: {question_text[:100]}...")
|
| 274 |
|
| 275 |
+
# self.run() is synchronous for CodeAgent in some smolagents versions/setups
|
| 276 |
raw_output_obj = self.run(question_text)
|
| 277 |
|
|
|
|
| 278 |
if hasattr(raw_output_obj, 'log_string') and callable(raw_output_obj.log_string):
|
| 279 |
full_agent_response = str(raw_output_obj.log_string())
|
| 280 |
+
elif hasattr(raw_output_obj, 'text') and raw_output_obj.text is not None:
|
| 281 |
full_agent_response = str(raw_output_obj.text)
|
| 282 |
+
elif isinstance(raw_output_obj, str):
|
| 283 |
full_agent_response = raw_output_obj
|
| 284 |
+
elif hasattr(raw_output_obj, 'result') and raw_output_obj.result is not None:
|
| 285 |
full_agent_response = str(raw_output_obj.result)
|
| 286 |
else:
|
| 287 |
+
full_agent_response = str(raw_output_obj)
|
| 288 |
|
| 289 |
+
reasoning_trace = full_agent_response
|
| 290 |
logger.info(f"CodeAgent full response (first 500 chars): {full_agent_response[:500]}...")
|
| 291 |
|
|
|
|
|
|
|
| 292 |
match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response, re.IGNORECASE | re.DOTALL)
|
| 293 |
if match:
|
| 294 |
final_answer_for_submission = match.group(1).strip()
|
| 295 |
logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}")
|
| 296 |
else:
|
| 297 |
logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response as fallback.")
|
|
|
|
|
|
|
| 298 |
final_answer_for_submission = full_agent_response.strip()
|
| 299 |
|
| 300 |
+
if not final_answer_for_submission:
|
| 301 |
logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
|
| 302 |
final_answer_for_submission = "Could not determine answer."
|
| 303 |
|
| 304 |
+
except TypeError as te:
|
| 305 |
+
logger.error(f"TypeError during agent processing: {str(te)}", exc_info=True)
|
| 306 |
final_answer_for_submission = f"Error in agent processing (TypeError): {str(te)}"
|
| 307 |
reasoning_trace += f"\nTypeError encountered: {str(te)}"
|
| 308 |
except Exception as e:
|
|
|
|
| 325 |
logger.info("ChuckAgent initialization started")
|
| 326 |
try:
|
| 327 |
self.loop = asyncio.get_running_loop()
|
| 328 |
+
except RuntimeError:
|
| 329 |
self.loop = asyncio.new_event_loop()
|
| 330 |
asyncio.set_event_loop(self.loop)
|
| 331 |
|
| 332 |
self.http_session = self.loop.run_until_complete(get_shared_http_session())
|
| 333 |
+
# This is where QuestionAnsweringAgent is instantiated
|
| 334 |
+
# If the import of smolagents failed, OpenAIServerModel(...) will use the dummy and raise TypeError
|
| 335 |
+
# If smolagents imported but has internal issues, QuestionAnsweringAgent's super().__init__ might raise
|
| 336 |
+
try:
|
| 337 |
+
self.agent = QuestionAnsweringAgent(http_session=self.http_session)
|
| 338 |
+
except Exception as agent_init_error:
|
| 339 |
+
logger.error(f"Failed to initialize QuestionAnsweringAgent: {agent_init_error}", exc_info=True)
|
| 340 |
+
# Close the session if agent init fails to prevent resource leak
|
| 341 |
+
self.loop.run_until_complete(close_shared_http_session())
|
| 342 |
+
raise # Re-raise the error to stop ChuckAgent creation
|
| 343 |
+
|
| 344 |
logger.info("ChuckAgent fully initialized")
|
| 345 |
|
| 346 |
def __call__(self, question: str) -> Tuple[str, str]:
|
| 347 |
logger.info(f"ChuckAgent received question (first 50 chars): {question[:50]}...")
|
| 348 |
try:
|
|
|
|
| 349 |
if asyncio.get_event_loop() is not self.loop:
|
| 350 |
asyncio.set_event_loop(self.loop)
|
| 351 |
|
|
|
|
| 365 |
logger.info("ChuckAgent shutdown complete.")
|
| 366 |
|
| 367 |
# --- Core Evaluation Logic ---
|
| 368 |
+
# (This section remains unchanged from your last version)
|
| 369 |
def get_space_id_agent_code_url() -> Tuple[Optional[str], str]:
|
| 370 |
space_id = os.getenv("SPACE_ID")
|
| 371 |
agent_code_url = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Agent code URL not found (SPACE_ID not set)"
|
|
|
|
| 386 |
except requests.exceptions.RequestException as e:
|
| 387 |
logger.error(f"Error fetching questions: {e}", exc_info=True)
|
| 388 |
raise ConnectionError(f"Error fetching questions: {e}") from e
|
| 389 |
+
except (requests.exceptions.JSONDecodeError, ValueError) as e:
|
| 390 |
logger.error(f"Error decoding questions JSON or invalid data: {e}. Response text: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True)
|
| 391 |
raise ValueError(f"Error decoding server response for questions: {e}") from e
|
| 392 |
|
|
|
|
| 398 |
for i, item in enumerate(questions_data):
|
| 399 |
task_id = item.get("task_id")
|
| 400 |
question_text = item.get("question")
|
| 401 |
+
if not task_id or question_text is None:
|
| 402 |
logger.warning(f"Skipping item {i+1} with missing data: {item}")
|
| 403 |
continue
|
| 404 |
logger.info(f"Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
|
| 405 |
model_ans, reasoning = "Error: Agent did not run", "No reasoning generated."
|
| 406 |
try:
|
| 407 |
model_ans, reasoning = agent(question_text)
|
| 408 |
+
except Exception as e:
|
| 409 |
logger.error(f"Error running agent on task {task_id}: {e}", exc_info=True)
|
| 410 |
+
model_ans = f"AGENT_CALL_ERROR: {e}"
|
| 411 |
+
reasoning = str(e)
|
| 412 |
|
| 413 |
payload_item = {"task_id": task_id, "submitted_answer": model_ans}
|
| 414 |
+
if reasoning:
|
| 415 |
payload_item["reasoning_trace"] = reasoning
|
| 416 |
answers_payload.append(payload_item)
|
| 417 |
|
| 418 |
+
results_log.append({
|
| 419 |
"Task ID": task_id,
|
| 420 |
"Question": question_text,
|
| 421 |
"Submitted Answer": model_ans,
|
|
|
|
| 432 |
submission_data = {"username": username.strip(), "agent_code": agent_code_url, "answers": answers_payload}
|
| 433 |
logger.info(f"Submitting {len(answers_payload)} answers for user '{username}'...")
|
| 434 |
try:
|
| 435 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 436 |
+
response.raise_for_status()
|
| 437 |
result_data = response.json()
|
| 438 |
return (
|
| 439 |
f"Submission Successful!\nUser: {result_data.get('username', 'N/A')}\n"
|
|
|
|
| 444 |
except requests.exceptions.HTTPError as e:
|
| 445 |
error_detail = f"Server responded with {e.response.status_code}."
|
| 446 |
try:
|
| 447 |
+
error_json = e.response.json()
|
| 448 |
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 449 |
+
except requests.exceptions.JSONDecodeError:
|
| 450 |
+
error_detail += f" Raw Response: {e.response.text[:500]}"
|
| 451 |
logger.error(f"Submission Failed: {error_detail}")
|
| 452 |
return f"Submission Failed: {error_detail}"
|
| 453 |
except requests.exceptions.Timeout:
|
| 454 |
logger.error("Submission Failed: The request timed out.")
|
| 455 |
return "Submission Failed: The request timed out."
|
| 456 |
+
except requests.exceptions.RequestException as e:
|
| 457 |
logger.error(f"Submission Failed: Network error - {e}", exc_info=True)
|
| 458 |
return f"Submission Failed: Network error - {e}"
|
| 459 |
+
except Exception as e:
|
| 460 |
logger.error(f"An unexpected error occurred during submission: {e}", exc_info=True)
|
| 461 |
return f"An unexpected error occurred during submission: {e}"
|
| 462 |
|
| 463 |
# --- Gradio Interface Main Function ---
|
| 464 |
GLOBAL_CHUCK_AGENT: Optional[ChuckAgent] = None
|
| 465 |
|
|
|
|
| 466 |
def run_and_submit_all_evaluation(profile: Optional[gr.OAuthProfile] = None, *args) -> Tuple[str, pd.DataFrame]:
|
| 467 |
global GLOBAL_CHUCK_AGENT
|
| 468 |
logger.info(f"run_and_submit_all_evaluation received profile: {type(profile)}")
|
| 469 |
+
if args:
|
| 470 |
logger.warning(f"run_and_submit_all_evaluation received unexpected additional args: {args}")
|
| 471 |
|
|
|
|
| 472 |
if not isinstance(profile, gr.OAuthProfile) and profile is not None:
|
| 473 |
logger.warning(f"Profile argument is not of type gr.OAuthProfile or None. Received: {profile}")
|
|
|
|
| 474 |
found_profile_in_args = False
|
| 475 |
+
for arg_val in args:
|
| 476 |
if isinstance(arg_val, gr.OAuthProfile):
|
| 477 |
+
profile = arg_val
|
| 478 |
found_profile_in_args = True
|
| 479 |
logger.info(f"Found gr.OAuthProfile in *args: {profile.username if profile else 'None (from args)'}")
|
| 480 |
break
|
| 481 |
+
if not found_profile_in_args and profile is None:
|
| 482 |
logger.error("Could not identify a valid gr.OAuthProfile object.")
|
| 483 |
return "Login error: Could not identify user profile.", pd.DataFrame()
|
| 484 |
|
| 485 |
logger.info(f"Effective profile for processing: {profile.username if profile else 'None'}")
|
| 486 |
|
| 487 |
+
if not profile:
|
| 488 |
logger.warning("User not logged in for evaluation.")
|
| 489 |
return "Please Login to Hugging Face with the button to run the evaluation.", pd.DataFrame()
|
| 490 |
|
|
|
|
| 493 |
|
| 494 |
_, agent_code_url = get_space_id_agent_code_url()
|
| 495 |
logger.info(f"Agent code URL: {agent_code_url}")
|
| 496 |
+
results_log_data: List[Dict[str, Any]] = []
|
| 497 |
|
| 498 |
try:
|
| 499 |
if GLOBAL_CHUCK_AGENT is None:
|
| 500 |
+
GLOBAL_CHUCK_AGENT = ChuckAgent()
|
| 501 |
+
agent_instance = GLOBAL_CHUCK_AGENT
|
| 502 |
+
except EnvironmentError as e:
|
| 503 |
logger.critical(f"Agent instantiation failed due to missing env vars: {e}")
|
| 504 |
return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
|
| 505 |
+
except Exception as e:
|
| 506 |
+
logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True) # This will catch the OpenAIServerModel TypeError if dummy is used
|
| 507 |
return f"Error initializing agent: {e}", pd.DataFrame()
|
| 508 |
|
| 509 |
try:
|
| 510 |
questions_data = fetch_questions(CONFIG.DEFAULT_API_URL)
|
| 511 |
+
answers_payload, results_log_data = process_all_questions(agent_instance, questions_data)
|
| 512 |
submission_status = submit_answers(CONFIG.DEFAULT_API_URL, username, agent_code_url, answers_payload)
|
| 513 |
+
except (ConnectionError, ValueError) as e:
|
| 514 |
submission_status = str(e)
|
| 515 |
+
except Exception as e:
|
| 516 |
logger.error(f"An unexpected error occurred during evaluation pipeline: {e}", exc_info=True)
|
| 517 |
submission_status = f"An unexpected error occurred: {e}"
|
| 518 |
|
|
|
|
| 541 |
**Technical Notes:**
|
| 542 |
* The agent uses `smolagents`, OpenAI (model: `{CONFIG.OPENAI_MODEL_ID}`), and Serper API for searches.
|
| 543 |
* Ensure `OPENAI_API_KEY` and `SERPER_API_KEY` are set as Space Secrets.
|
| 544 |
+
* `requirements.txt` should specify a compatible `gradio` version and `smolagents`.
|
| 545 |
+
* If `smolagents` initialization errors occur, it might be due to internal library issues with the installed version.
|
| 546 |
"""
|
| 547 |
)
|
| 548 |
|
| 549 |
login_button = gr.LoginButton()
|
| 550 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 551 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=10, interactive=False)
|
| 552 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 553 |
|
| 554 |
run_button.click(
|
| 555 |
fn=run_and_submit_all_evaluation,
|
|
|
|
| 577 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 578 |
|
| 579 |
print(f" Default API URL: {CONFIG.DEFAULT_API_URL}")
|
| 580 |
+
print(f" OpenAI Model ID: {CONFIG.OPENAI_MODEL_ID}")
|
| 581 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 582 |
print("Launching Gradio Interface for Chuck Agent Evaluation...")
|
| 583 |
|
| 584 |
try:
|
| 585 |
+
demo.launch(debug=True, share=False)
|
| 586 |
finally:
|
|
|
|
| 587 |
loop_to_use = None
|
|
|
|
| 588 |
if GLOBAL_CHUCK_AGENT and hasattr(GLOBAL_CHUCK_AGENT, 'http_session') and GLOBAL_CHUCK_AGENT.http_session:
|
| 589 |
loop_to_use = GLOBAL_CHUCK_AGENT.http_session.loop
|
| 590 |
+
elif SHARED_HTTP_SESSION:
|
| 591 |
loop_to_use = SHARED_HTTP_SESSION.loop
|
| 592 |
|
| 593 |
if loop_to_use and loop_to_use.is_running():
|
| 594 |
logger.info("Attempting to shutdown agent and close HTTP session in finally block...")
|
| 595 |
try:
|
| 596 |
+
current_loop = asyncio.get_event_loop_policy().get_event_loop()
|
| 597 |
+
if current_loop is not loop_to_use and not loop_to_use.is_closed():
|
|
|
|
| 598 |
asyncio.set_event_loop(loop_to_use)
|
| 599 |
|
| 600 |
if GLOBAL_CHUCK_AGENT:
|
| 601 |
loop_to_use.run_until_complete(GLOBAL_CHUCK_AGENT.shutdown())
|
| 602 |
+
elif SHARED_HTTP_SESSION and not SHARED_HTTP_SESSION.closed:
|
| 603 |
loop_to_use.run_until_complete(close_shared_http_session())
|
| 604 |
+
except Exception as e:
|
| 605 |
logger.error(f"Error during final cleanup of HTTP session: {e}", exc_info=True)
|
| 606 |
else:
|
| 607 |
+
logger.info("No active HTTP session or running loop to close in finally block.")
|
| 608 |
+
|