Spaces:
No application file
No application file
updated script
Browse files
app.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
import os
|
| 2 |
-
import gradio as gr
|
| 3 |
import requests
|
| 4 |
-
|
| 5 |
import pandas as pd
|
| 6 |
import asyncio
|
| 7 |
import re
|
|
@@ -15,19 +15,22 @@ from typing import Optional, Dict, Any, List, Union
|
|
| 15 |
# Import necessary components from smolagents
|
| 16 |
try:
|
| 17 |
from smolagents import CodeAgent, Tool, OpenAIServerModel
|
|
|
|
|
|
|
| 18 |
except ImportError:
|
| 19 |
logging.error("Failed to import smolagents. Please ensure it is installed.")
|
| 20 |
-
#
|
| 21 |
-
# so the rest of the script can be parsed, though it won't function.
|
| 22 |
class CodeAgent: pass
|
| 23 |
class Tool: pass
|
| 24 |
class OpenAIServerModel: pass
|
|
|
|
|
|
|
| 25 |
|
| 26 |
from datetime import datetime
|
| 27 |
|
| 28 |
# --- Constants ---
|
| 29 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 30 |
-
OUTPUT_DOC_PATH = "agent_answers.jsonl"
|
| 31 |
SCREENSHOTS_DIR = "screenshots"
|
| 32 |
|
| 33 |
# Configure logging
|
|
@@ -39,56 +42,38 @@ logger = logging.getLogger(__name__)
|
|
| 39 |
# Ensure screenshots directory exists
|
| 40 |
os.makedirs(SCREENSHOTS_DIR, exist_ok=True)
|
| 41 |
|
| 42 |
-
# --- Tool Definitions ---
|
| 43 |
class ImageRetrievalTool(Tool):
|
| 44 |
name = "image_retriever"
|
| 45 |
description = "Retrieves and processes images from web pages. Input is a URL to an image."
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
"type": "string",
|
| 50 |
-
"description": "The URL of the image to retrieve"
|
| 51 |
-
}
|
| 52 |
-
}
|
| 53 |
-
output_type = "object" # Or string if you return a path or image_id
|
| 54 |
-
|
| 55 |
def __init__(self):
|
| 56 |
super().__init__()
|
| 57 |
-
self.image_memory = {}
|
| 58 |
-
self.screenshot_count = 0
|
| 59 |
-
|
| 60 |
-
async def forward(self, url: str) ->
|
| 61 |
logger.info(f"ImageRetrievalTool called with URL: {url}")
|
| 62 |
try:
|
| 63 |
async with aiohttp.ClientSession() as session:
|
| 64 |
async with session.get(url) as response:
|
| 65 |
-
response.raise_for_status()
|
| 66 |
-
image_data = await response.read()
|
| 67 |
image_id = f"image_{self.screenshot_count}"
|
| 68 |
-
|
| 69 |
-
self.image_memory[image_id] = {
|
| 70 |
-
'data': image_data, # Raw image data
|
| 71 |
-
'url': url,
|
| 72 |
-
'timestamp': datetime.now().isoformat()
|
| 73 |
-
}
|
| 74 |
self.screenshot_count += 1
|
| 75 |
-
|
| 76 |
-
return {"image_id": image_id, "status": "success", "message": f"Image from {url} retrieved."}
|
| 77 |
except Exception as e:
|
| 78 |
logger.error(f"Error retrieving image {url}: {str(e)}")
|
| 79 |
-
return
|
| 80 |
|
| 81 |
class WebSearchTool(Tool):
|
| 82 |
name = "web_search"
|
| 83 |
description = "Performs web searches using Serper API to find information. Input is a search query."
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
"query": {
|
| 87 |
-
"type": "string",
|
| 88 |
-
"description": "The search query to execute"
|
| 89 |
-
}
|
| 90 |
-
}
|
| 91 |
-
output_type = "string" # Output is a string summarizing search results
|
| 92 |
|
| 93 |
async def forward(self, query: str) -> str:
|
| 94 |
logger.info(f"WebSearchTool called with query: {query}")
|
|
@@ -98,19 +83,13 @@ class WebSearchTool(Tool):
|
|
| 98 |
return "Error: Serper API key not found in environment."
|
| 99 |
|
| 100 |
url = "https://google.serper.dev/search"
|
| 101 |
-
headers = {
|
| 102 |
-
|
| 103 |
-
'Content-Type': 'application/json'
|
| 104 |
-
}
|
| 105 |
-
payload = json.dumps({ # Ensure payload is a JSON string for older aiohttp or some servers
|
| 106 |
-
'q': query,
|
| 107 |
-
'num': 5 # Number of results
|
| 108 |
-
})
|
| 109 |
|
| 110 |
try:
|
| 111 |
async with aiohttp.ClientSession() as session:
|
| 112 |
-
async with session.post(url, headers=headers, data=payload) as response:
|
| 113 |
-
response.raise_for_status()
|
| 114 |
data = await response.json()
|
| 115 |
return self._format_results(data)
|
| 116 |
except Exception as e:
|
|
@@ -120,265 +99,209 @@ class WebSearchTool(Tool):
|
|
| 120 |
def _format_results(self, data: Dict) -> str:
|
| 121 |
results = []
|
| 122 |
if 'organic' in data and data['organic']:
|
| 123 |
-
for result in data['organic'][:3]: # Limit to top 3
|
| 124 |
-
title = result.get('title', '
|
| 125 |
-
snippet = result.get('snippet', '
|
| 126 |
-
link = result.get('link', '#')
|
| 127 |
-
results.append(f"Title: {title}\nSnippet: {snippet}\
|
| 128 |
-
if not results and 'knowledgeGraph' in data:
|
| 129 |
kg = data['knowledgeGraph']
|
| 130 |
title = kg.get('title', '')
|
| 131 |
description = kg.get('description', '')
|
| 132 |
if title or description:
|
| 133 |
results.append(f"Knowledge Graph: {title}\n{description}\n---")
|
| 134 |
-
|
| 135 |
-
return
|
| 136 |
|
| 137 |
class CalculatorTool(Tool):
|
| 138 |
name = "calculator"
|
| 139 |
-
description = "Performs mathematical calculations. Input is a mathematical expression string."
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
"expression": {
|
| 143 |
-
"type": "string",
|
| 144 |
-
"description": "The mathematical expression to evaluate (e.g., '2+2', '10*5/2')"
|
| 145 |
-
}
|
| 146 |
-
}
|
| 147 |
-
output_type = "string" # Return result as string to avoid type issues in agent observation
|
| 148 |
|
| 149 |
def __init__(self):
|
| 150 |
super().__init__()
|
| 151 |
-
# Limited safe operations
|
| 152 |
self.operations = {
|
| 153 |
'+': operator.add, '-': operator.sub,
|
| 154 |
'*': operator.mul, '/': operator.truediv,
|
| 155 |
'^': operator.pow
|
| 156 |
}
|
| 157 |
-
# For single argument functions like sqrt, abs, they need special handling if using eval
|
| 158 |
-
# A more robust calculator would parse expressions or use a safer math library
|
| 159 |
-
# For now, focusing on basic arithmetic.
|
| 160 |
|
| 161 |
async def forward(self, expression: str) -> str:
|
| 162 |
logger.info(f"CalculatorTool called with expression: {expression}")
|
| 163 |
try:
|
| 164 |
-
#
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
if not expression:
|
| 168 |
return "Error: Empty or invalid expression for calculator."
|
| 169 |
-
|
| 170 |
-
#
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
return f"Calculation result: {expression} = {float(result)}"
|
| 174 |
except Exception as e:
|
| 175 |
logger.error(f"Error evaluating expression '{expression}': {str(e)}")
|
| 176 |
-
return f"Error: Could not evaluate expression '{expression}'.
|
| 177 |
-
|
| 178 |
-
# Original _prepare_expression was okay, but eval safety is the bigger concern.
|
| 179 |
-
# The above forward method simplifies this.
|
| 180 |
|
| 181 |
# --- Agent Definition ---
|
| 182 |
class QuestionAnsweringAgent(CodeAgent):
|
| 183 |
def __init__(self, model: Optional[OpenAIServerModel] = None):
|
| 184 |
-
tools = [
|
| 185 |
-
WebSearchTool(),
|
| 186 |
-
CalculatorTool(),
|
| 187 |
-
ImageRetrievalTool() # Ensure this tool is useful or remove if not actively used by the agent's plan
|
| 188 |
-
]
|
| 189 |
|
| 190 |
if model is None:
|
| 191 |
-
# Ensure OPENAI_API_KEY is available for this default model
|
| 192 |
if not os.environ.get('OPENAI_API_KEY'):
|
| 193 |
raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
|
| 194 |
model = OpenAIServerModel(
|
| 195 |
-
model_id="gpt-4", #
|
| 196 |
-
api_key=os.environ.get('OPENAI_API_KEY')
|
| 197 |
)
|
| 198 |
|
| 199 |
-
#
|
| 200 |
-
|
| 201 |
-
system_prompt = """You are Chuck, a helpful AI assistant. Your goal is to answer questions accurately and concisely.
|
| 202 |
-
You have access to the following tools:
|
| 203 |
-
- web_search: Use this to search the internet for information when the answer is not common knowledge or requires up-to-date details.
|
| 204 |
-
- calculator: Use this for mathematical calculations. Input should be a simple expression string like "10+5*2".
|
| 205 |
-
- image_retriever: Use this to fetch an image if a URL is provided and image content is needed.
|
| 206 |
-
|
| 207 |
-
When you receive a question:
|
| 208 |
-
1. Think step-by-step to create a plan to answer the question.
|
| 209 |
-
2. Decide if any tools are needed. If so, specify the tool and the exact input for it.
|
| 210 |
-
3. Execute the tools if necessary and observe the results.
|
| 211 |
-
4. If multiple steps or tools are needed, repeat step 2 and 3.
|
| 212 |
-
5. Based on the information gathered (or if no tools were needed), formulate a final answer to the original question.
|
| 213 |
-
6. Respond with only the final answer. Do not explain your plan or tool usage in the final answer unless explicitly asked.
|
| 214 |
-
"""
|
| 215 |
|
| 216 |
super().__init__(
|
| 217 |
tools=tools,
|
| 218 |
model=model,
|
| 219 |
-
system_prompt=system_prompt,
|
| 220 |
-
additional_authorized_imports=["PIL"],
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
verbosity_level=2 # 0 (silent), 1 (info), 2 (debug)
|
| 224 |
)
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
async def _process_visual_memory(self, step_num: int, description: str):
|
| 233 |
-
# This callback might need adjustment based on how `smolagents.CodeAgent`
|
| 234 |
-
# provides image observations or if `ImageRetrievalTool` directly gives usable output.
|
| 235 |
-
# For now, assume `description` might contain info about image retrieval.
|
| 236 |
-
logger.debug(f"Step {step_num} visual memory callback: {description}")
|
| 237 |
-
# if hasattr(self, 'current_observation_images'): # This attribute would be set by CodeAgent
|
| 238 |
-
# self.visual_memory[step_num] = {
|
| 239 |
-
# 'images': self.current_observation_images,
|
| 240 |
-
# 'description': description,
|
| 241 |
-
# 'timestamp': datetime.now().isoformat()
|
| 242 |
-
# }
|
| 243 |
-
|
| 244 |
-
async def process_question(self, question_data: str) -> str:
|
| 245 |
try:
|
| 246 |
logger.info(f"Processing question with CodeAgent: {question_data[:100]}...")
|
| 247 |
self.step_count += 1
|
| 248 |
|
| 249 |
-
#
|
| 250 |
-
# It
|
| 251 |
-
#
|
| 252 |
-
#
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
|
| 258 |
except Exception as e:
|
| 259 |
logger.error(f"Error processing question in QuestionAnsweringAgent: {str(e)}", exc_info=True)
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
# They are commented out for now.
|
| 265 |
-
#
|
| 266 |
-
# async def plan_execution(self, question: str) -> str:
|
| 267 |
-
# prompt = f"""
|
| 268 |
-
# Create a plan to answer the following question: {question}
|
| 269 |
-
# Available tools:
|
| 270 |
-
# - web_search: Search the web for information
|
| 271 |
-
# - calculator: Perform mathematical calculations
|
| 272 |
-
# """
|
| 273 |
-
# response = self.model([ # This is a direct model call, not agent planning
|
| 274 |
-
# {"role": "system", "content": "You are a planning assistant. Create a step-by-step plan to answer the question."},
|
| 275 |
-
# {"role": "user", "content": prompt}
|
| 276 |
-
# ])
|
| 277 |
-
# result = response.content if hasattr(response, 'content') else str(response)
|
| 278 |
-
# return result.strip()
|
| 279 |
-
|
| 280 |
-
# def _prepare_context(
|
| 281 |
-
# self,
|
| 282 |
-
# question: str,
|
| 283 |
-
# search_results: str = "",
|
| 284 |
-
# calc_result: Optional[Union[float, str]] = None
|
| 285 |
-
# ) -> str:
|
| 286 |
-
# context = f"Question: {question}\n\n"
|
| 287 |
-
# if search_results:
|
| 288 |
-
# context += f"Search Results:\n{search_results[:2000]}...\n\n"
|
| 289 |
-
# if calc_result is not None:
|
| 290 |
-
# context += f"Calculation Result: {calc_result}\n\n"
|
| 291 |
-
# # if self.visual_memory: # If using custom visual_memory
|
| 292 |
-
# # context += "\nVisual Information:\n"
|
| 293 |
-
# # for step, memory in self.visual_memory.items():
|
| 294 |
-
# # context += f"Step {step}: {memory['description']}\n"
|
| 295 |
-
# return context
|
| 296 |
|
| 297 |
# Adapter to fit interface with original app.py
|
| 298 |
class ChuckAgent:
|
| 299 |
def __init__(self):
|
| 300 |
-
|
| 301 |
-
required_env_vars = [
|
| 302 |
-
'OPENAI_API_KEY',
|
| 303 |
-
'SERPER_API_KEY'
|
| 304 |
-
]
|
| 305 |
-
|
| 306 |
missing_vars = [var for var in required_env_vars if not os.environ.get(var)]
|
| 307 |
if missing_vars:
|
| 308 |
-
# Log and raise error if critical API keys are missing
|
| 309 |
error_msg = f"Missing required environment variables: {', '.join(missing_vars)}"
|
| 310 |
-
logger.critical(error_msg)
|
| 311 |
raise EnvironmentError(error_msg)
|
| 312 |
|
| 313 |
logger.info("ChuckAgent initialization started")
|
| 314 |
-
|
| 315 |
-
# Model is now initialized within QuestionAnsweringAgent if not provided
|
| 316 |
-
# This means QuestionAnsweringAgent is self-contained regarding model creation
|
| 317 |
-
self.agent = QuestionAnsweringAgent() # Let it use its default model
|
| 318 |
-
|
| 319 |
self.loop = asyncio.new_event_loop()
|
| 320 |
asyncio.set_event_loop(self.loop)
|
| 321 |
logger.info("ChuckAgent fully initialized")
|
| 322 |
|
| 323 |
-
|
|
|
|
| 324 |
logger.info(f"ChuckAgent received question (first 50 chars): {question[:50]}...")
|
|
|
|
|
|
|
| 325 |
try:
|
| 326 |
-
#
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
|
|
|
|
|
|
| 330 |
except Exception as e:
|
| 331 |
error_msg = f"Error running ChuckAgent: {str(e)}"
|
| 332 |
logger.error(error_msg, exc_info=True)
|
| 333 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 334 |
|
| 335 |
-
def run_and_submit_all(profile: gr.OAuthProfile | None, click_event_data: gr.ClickData, request_obj: gr.Request):
|
| 336 |
-
"""
|
| 337 |
-
Fetches all questions, runs the ChuckAgent on them, submits all answers,
|
| 338 |
-
and displays the results.
|
| 339 |
-
"""
|
| 340 |
space_id = os.getenv("SPACE_ID")
|
| 341 |
|
| 342 |
-
if profile:
|
| 343 |
-
username = f"{profile.username}"
|
| 344 |
-
logger.info(f"User logged in: {username}")
|
| 345 |
-
else:
|
| 346 |
logger.warning("User not logged in for run_and_submit_all.")
|
| 347 |
return "Please Login to Hugging Face with the button to run the evaluation.", pd.DataFrame()
|
| 348 |
|
|
|
|
|
|
|
|
|
|
| 349 |
api_url = DEFAULT_API_URL
|
| 350 |
questions_url = f"{api_url}/questions"
|
| 351 |
submit_url = f"{api_url}/submit"
|
| 352 |
|
| 353 |
try:
|
| 354 |
agent = ChuckAgent()
|
| 355 |
-
except EnvironmentError as e:
|
| 356 |
logger.critical(f"Agent instantiation failed due to missing env vars: {e}")
|
| 357 |
-
return f"Agent Initialization Error: {e}.
|
| 358 |
except Exception as e:
|
| 359 |
logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
|
| 360 |
-
return f"Error initializing agent: {e}", pd.DataFrame()
|
| 361 |
|
| 362 |
-
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Agent code URL not
|
| 363 |
logger.info(f"Agent code URL: {agent_code}")
|
| 364 |
|
| 365 |
logger.info(f"Fetching questions from: {questions_url}")
|
| 366 |
try:
|
| 367 |
-
response = requests.get(questions_url, timeout=30)
|
| 368 |
response.raise_for_status()
|
| 369 |
questions_data = response.json()
|
| 370 |
-
if not questions_data or not isinstance(questions_data, list):
|
| 371 |
-
logger.warning(f"Fetched questions
|
| 372 |
return "Fetched questions list is empty or not a list.", pd.DataFrame()
|
| 373 |
logger.info(f"Fetched {len(questions_data)} questions.")
|
| 374 |
except requests.exceptions.RequestException as e:
|
| 375 |
logger.error(f"Error fetching questions: {e}", exc_info=True)
|
| 376 |
return f"Error fetching questions: {e}", pd.DataFrame()
|
| 377 |
except requests.exceptions.JSONDecodeError as e:
|
| 378 |
-
logger.error(f"Error decoding
|
| 379 |
return f"Error decoding server response for questions: {e}", pd.DataFrame()
|
| 380 |
-
except Exception as e:
|
| 381 |
-
logger.error(f"
|
| 382 |
return f"An unexpected error occurred fetching questions: {e}", pd.DataFrame()
|
| 383 |
|
| 384 |
results_log = []
|
|
@@ -388,33 +311,41 @@ def run_and_submit_all(profile: gr.OAuthProfile | None, click_event_data: gr.Cli
|
|
| 388 |
task_id = item.get("task_id")
|
| 389 |
question_text = item.get("question")
|
| 390 |
if not task_id or question_text is None:
|
| 391 |
-
logger.warning(f"Skipping item with missing
|
| 392 |
continue
|
| 393 |
|
| 394 |
logger.info(f"Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
|
| 395 |
try:
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
except Exception as e:
|
| 400 |
logger.error(f"Error running agent on task {task_id}: {e}", exc_info=True)
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer_error})
|
| 405 |
-
|
| 406 |
|
| 407 |
if not answers_payload:
|
| 408 |
-
logger.warning("Agent did not produce any answers
|
| 409 |
-
# Return empty DataFrame if results_log is also empty or structure as needed
|
| 410 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log if results_log else [])
|
| 411 |
|
| 412 |
-
|
| 413 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 414 |
-
|
| 415 |
-
logger.
|
|
|
|
| 416 |
|
| 417 |
-
logger.info(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 418 |
try:
|
| 419 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 420 |
response.raise_for_status()
|
|
@@ -428,12 +359,12 @@ def run_and_submit_all(profile: gr.OAuthProfile | None, click_event_data: gr.Cli
|
|
| 428 |
)
|
| 429 |
logger.info("Submission successful.")
|
| 430 |
except requests.exceptions.HTTPError as e:
|
| 431 |
-
error_detail = f"Server responded with
|
| 432 |
try:
|
| 433 |
error_json = e.response.json()
|
| 434 |
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 435 |
-
except requests.exceptions.JSONDecodeError:
|
| 436 |
-
error_detail += f" Raw Response: {e.response.text[:500]}"
|
| 437 |
final_status = f"Submission Failed: {error_detail}"
|
| 438 |
logger.error(final_status)
|
| 439 |
except requests.exceptions.Timeout:
|
|
@@ -446,7 +377,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None, click_event_data: gr.Cli
|
|
| 446 |
final_status = f"An unexpected error occurred during submission: {e}"
|
| 447 |
logger.error(final_status, exc_info=True)
|
| 448 |
|
| 449 |
-
results_df = pd.DataFrame(results_log if results_log else [])
|
| 450 |
return final_status, results_df
|
| 451 |
|
| 452 |
|
|
@@ -463,22 +394,18 @@ with gr.Blocks() as demo:
|
|
| 463 |
Make sure you have the following **Secrets** correctly set in your Hugging Face Space settings:
|
| 464 |
- `OPENAI_API_KEY` (Your OpenAI API key)
|
| 465 |
- `SERPER_API_KEY` (Your Serper API key)
|
|
|
|
| 466 |
"""
|
| 467 |
)
|
| 468 |
|
| 469 |
-
# The Gradio LoginButton will use OAuth details if `hf_oauth: true` is in README.md
|
| 470 |
-
# It provides the `profile` object to the click function.
|
| 471 |
login_button = gr.LoginButton()
|
| 472 |
-
|
| 473 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
|
|
|
|
|
|
| 474 |
|
| 475 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 476 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 477 |
-
|
| 478 |
-
# Pass login_button (which resolves to the profile) as an input to run_and_submit_all
|
| 479 |
run_button.click(
|
| 480 |
fn=run_and_submit_all,
|
| 481 |
-
inputs=[login_button],
|
| 482 |
outputs=[status_output, results_table]
|
| 483 |
)
|
| 484 |
|
|
@@ -489,9 +416,6 @@ if __name__ == "__main__":
|
|
| 489 |
|
| 490 |
if space_host_startup:
|
| 491 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 492 |
-
# Corrected the runtime URL construction slightly.
|
| 493 |
-
# Typically, it's just https://{SPACE_ID_WITH_DASHES}.hf.space or similar.
|
| 494 |
-
# The SPACE_HOST itself is often the full hostname.
|
| 495 |
print(f" Runtime URL might be: https://{space_host_startup}")
|
| 496 |
else:
|
| 497 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
|
@@ -506,4 +430,4 @@ if __name__ == "__main__":
|
|
| 506 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 507 |
|
| 508 |
print("Launching Gradio Interface for Chuck Agent Evaluation...")
|
| 509 |
-
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
import os
|
| 2 |
+
import gradio as gr # Make sure this import is present
|
| 3 |
import requests
|
| 4 |
+
# inspect is not used, can be removed
|
| 5 |
import pandas as pd
|
| 6 |
import asyncio
|
| 7 |
import re
|
|
|
|
| 15 |
# Import necessary components from smolagents
|
| 16 |
try:
|
| 17 |
from smolagents import CodeAgent, Tool, OpenAIServerModel
|
| 18 |
+
# If CodeAgent has a specific return type for run that includes reasoning
|
| 19 |
+
# from smolagents.types import AgentOutput # Or similar, check smolagents docs
|
| 20 |
except ImportError:
|
| 21 |
logging.error("Failed to import smolagents. Please ensure it is installed.")
|
| 22 |
+
# Dummy classes for script parsing if smolagents is not installed
|
|
|
|
| 23 |
class CodeAgent: pass
|
| 24 |
class Tool: pass
|
| 25 |
class OpenAIServerModel: pass
|
| 26 |
+
# class AgentOutput: pass
|
| 27 |
+
|
| 28 |
|
| 29 |
from datetime import datetime
|
| 30 |
|
| 31 |
# --- Constants ---
|
| 32 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 33 |
+
OUTPUT_DOC_PATH = "agent_answers.jsonl" # Not actively used in this script for submission
|
| 34 |
SCREENSHOTS_DIR = "screenshots"
|
| 35 |
|
| 36 |
# Configure logging
|
|
|
|
| 42 |
# Ensure screenshots directory exists
|
| 43 |
os.makedirs(SCREENSHOTS_DIR, exist_ok=True)
|
| 44 |
|
| 45 |
+
# --- Tool Definitions (Largely Unchanged, but ensure descriptions are good for the LLM) ---
|
| 46 |
class ImageRetrievalTool(Tool):
|
| 47 |
name = "image_retriever"
|
| 48 |
description = "Retrieves and processes images from web pages. Input is a URL to an image."
|
| 49 |
+
inputs = {"url": {"type": "string", "description": "The URL of the image to retrieve"}}
|
| 50 |
+
output_type = "string" # Output a message or image identifier
|
| 51 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
def __init__(self):
|
| 53 |
super().__init__()
|
| 54 |
+
self.image_memory = {}
|
| 55 |
+
self.screenshot_count = 0
|
| 56 |
+
|
| 57 |
+
async def forward(self, url: str) -> str: # Changed output to string for simplicity
|
| 58 |
logger.info(f"ImageRetrievalTool called with URL: {url}")
|
| 59 |
try:
|
| 60 |
async with aiohttp.ClientSession() as session:
|
| 61 |
async with session.get(url) as response:
|
| 62 |
+
response.raise_for_status()
|
| 63 |
+
image_data = await response.read() # In a real scenario, you might save this
|
| 64 |
image_id = f"image_{self.screenshot_count}"
|
| 65 |
+
self.image_memory[image_id] = {'data': image_data, 'url': url, 'timestamp': datetime.now().isoformat()}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
self.screenshot_count += 1
|
| 67 |
+
return f"Image retrieved successfully from {url}. Stored as {image_id}."
|
|
|
|
| 68 |
except Exception as e:
|
| 69 |
logger.error(f"Error retrieving image {url}: {str(e)}")
|
| 70 |
+
return f"Error retrieving image: {str(e)}"
|
| 71 |
|
| 72 |
class WebSearchTool(Tool):
|
| 73 |
name = "web_search"
|
| 74 |
description = "Performs web searches using Serper API to find information. Input is a search query."
|
| 75 |
+
inputs = {"query": {"type": "string", "description": "The search query to execute"}}
|
| 76 |
+
output_type = "string"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
async def forward(self, query: str) -> str:
|
| 79 |
logger.info(f"WebSearchTool called with query: {query}")
|
|
|
|
| 83 |
return "Error: Serper API key not found in environment."
|
| 84 |
|
| 85 |
url = "https://google.serper.dev/search"
|
| 86 |
+
headers = {'X-API-KEY': serper_api_key, 'Content-Type': 'application/json'}
|
| 87 |
+
payload = json.dumps({'q': query, 'num': 3}) # Request fewer results for faster processing
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
try:
|
| 90 |
async with aiohttp.ClientSession() as session:
|
| 91 |
+
async with session.post(url, headers=headers, data=payload) as response:
|
| 92 |
+
response.raise_for_status()
|
| 93 |
data = await response.json()
|
| 94 |
return self._format_results(data)
|
| 95 |
except Exception as e:
|
|
|
|
| 99 |
def _format_results(self, data: Dict) -> str:
|
| 100 |
results = []
|
| 101 |
if 'organic' in data and data['organic']:
|
| 102 |
+
for result in data['organic'][:3]: # Limit to top 3
|
| 103 |
+
title = result.get('title', 'N/A')
|
| 104 |
+
snippet = result.get('snippet', 'N/A')
|
| 105 |
+
# link = result.get('link', '#') # Links might not be useful for the LLM context
|
| 106 |
+
results.append(f"Title: {title}\nSnippet: {snippet}\n---")
|
| 107 |
+
if not results and 'knowledgeGraph' in data:
|
| 108 |
kg = data['knowledgeGraph']
|
| 109 |
title = kg.get('title', '')
|
| 110 |
description = kg.get('description', '')
|
| 111 |
if title or description:
|
| 112 |
results.append(f"Knowledge Graph: {title}\n{description}\n---")
|
| 113 |
+
formatted_output = "\n".join(results) if results else "No relevant search results found."
|
| 114 |
+
return formatted_output[:3000] # Truncate to keep context manageable
|
| 115 |
|
| 116 |
class CalculatorTool(Tool):
|
| 117 |
name = "calculator"
|
| 118 |
+
description = "Performs mathematical calculations. Input is a mathematical expression string (e.g., '2+2*5')."
|
| 119 |
+
inputs = {"expression": {"type": "string", "description": "The mathematical expression to evaluate"}}
|
| 120 |
+
output_type = "string"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
def __init__(self):
|
| 123 |
super().__init__()
|
|
|
|
| 124 |
self.operations = {
|
| 125 |
'+': operator.add, '-': operator.sub,
|
| 126 |
'*': operator.mul, '/': operator.truediv,
|
| 127 |
'^': operator.pow
|
| 128 |
}
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
async def forward(self, expression: str) -> str:
|
| 131 |
logger.info(f"CalculatorTool called with expression: {expression}")
|
| 132 |
try:
|
| 133 |
+
# More robust sanitization
|
| 134 |
+
safe_expr = "".join(c for c in expression if c in "0123456789+-*/^(). ")
|
| 135 |
+
if not safe_expr:
|
|
|
|
| 136 |
return "Error: Empty or invalid expression for calculator."
|
| 137 |
+
# Using a safer eval approach is complex; this remains a simplified version.
|
| 138 |
+
# For production, a proper math expression parser is crucial.
|
| 139 |
+
result = eval(safe_expr, {"__builtins__": {}}, self.operations) # type: ignore
|
| 140 |
+
return f"Calculation result: {safe_expr} = {float(result)}"
|
|
|
|
| 141 |
except Exception as e:
|
| 142 |
logger.error(f"Error evaluating expression '{expression}': {str(e)}")
|
| 143 |
+
return f"Error: Could not evaluate expression '{expression}'. Ensure it's a simple arithmetic expression."
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
# --- Agent Definition ---
|
| 146 |
class QuestionAnsweringAgent(CodeAgent):
|
| 147 |
def __init__(self, model: Optional[OpenAIServerModel] = None):
|
| 148 |
+
tools = [WebSearchTool(), CalculatorTool(), ImageRetrievalTool()]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
|
| 150 |
if model is None:
|
|
|
|
| 151 |
if not os.environ.get('OPENAI_API_KEY'):
|
| 152 |
raise EnvironmentError("OPENAI_API_KEY not found, cannot initialize default OpenAIServerModel.")
|
| 153 |
model = OpenAIServerModel(
|
| 154 |
+
model_id="gpt-4", # Consider "gpt-3.5-turbo" for faster/cheaper testing
|
| 155 |
+
api_key=os.environ.get('OPENAI_API_KEY')
|
| 156 |
)
|
| 157 |
|
| 158 |
+
# MODIFICATION 2: Use the specified system prompt
|
| 159 |
+
system_prompt = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
|
| 161 |
super().__init__(
|
| 162 |
tools=tools,
|
| 163 |
model=model,
|
| 164 |
+
system_prompt=system_prompt,
|
| 165 |
+
additional_authorized_imports=["PIL"],
|
| 166 |
+
max_steps=10,
|
| 167 |
+
verbosity_level=2
|
|
|
|
| 168 |
)
|
| 169 |
+
self.step_count = 0
|
| 170 |
+
logger.info("QuestionAnsweringAgent initialized with tools and new system prompt.")
|
| 171 |
+
|
| 172 |
+
async def process_question(self, question_data: str) -> tuple[str, str]: # Return (final_answer, reasoning_trace)
|
| 173 |
+
full_agent_response = ""
|
| 174 |
+
final_answer_for_submission = ""
|
| 175 |
+
reasoning_trace = "Agent execution started."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
try:
|
| 177 |
logger.info(f"Processing question with CodeAgent: {question_data[:100]}...")
|
| 178 |
self.step_count += 1
|
| 179 |
|
| 180 |
+
# self.run() is the method from CodeAgent to execute the task
|
| 181 |
+
# It should return the full text output from the LLM, including thoughts and FINAL ANSWER
|
| 182 |
+
# The exact return type of self.run() might need checking in smolagents docs
|
| 183 |
+
# It could be a string, or an object with more details.
|
| 184 |
+
raw_output = await self.run(question_data)
|
| 185 |
+
full_agent_response = str(raw_output) # Assuming it's a string or can be stringified
|
| 186 |
+
reasoning_trace = full_agent_response # Use the full response as the trace for now
|
| 187 |
+
|
| 188 |
+
logger.info(f"CodeAgent full response: {full_agent_response[:500]}...")
|
| 189 |
+
|
| 190 |
+
# MODIFICATION 2 (continued): Extract the final answer
|
| 191 |
+
match = re.search(r"FINAL ANSWER:\s*(.*)", full_agent_response, re.IGNORECASE | re.DOTALL)
|
| 192 |
+
if match:
|
| 193 |
+
final_answer_for_submission = match.group(1).strip()
|
| 194 |
+
# Further clean up if necessary, e.g., removing trailing thoughts
|
| 195 |
+
# For now, this takes everything after "FINAL ANSWER:"
|
| 196 |
+
logger.info(f"Extracted FINAL ANSWER: {final_answer_for_submission}")
|
| 197 |
+
else:
|
| 198 |
+
logger.warning("Could not find 'FINAL ANSWER:' in agent's response. Using full response.")
|
| 199 |
+
# As per instructions, if "FINAL ANSWER" is not found, this might be an issue.
|
| 200 |
+
# However, the scoring server note says "don't include the text 'FINAL ANSWER' in your submission"
|
| 201 |
+
# This implies the agent *should* be producing it, and we extract the content.
|
| 202 |
+
# If it's not producing it, then the raw_output might be the best guess, but it's not ideal.
|
| 203 |
+
final_answer_for_submission = full_agent_response.strip() # Fallback, might be incorrect for submission
|
| 204 |
+
|
| 205 |
+
if not final_answer_for_submission: # If empty after stripping
|
| 206 |
+
logger.warning("Extracted final answer is empty. Defaulting to a placeholder.")
|
| 207 |
+
final_answer_for_submission = "Could not determine answer."
|
| 208 |
+
|
| 209 |
|
| 210 |
except Exception as e:
|
| 211 |
logger.error(f"Error processing question in QuestionAnsweringAgent: {str(e)}", exc_info=True)
|
| 212 |
+
final_answer_for_submission = f"Error in agent processing: {str(e)}"
|
| 213 |
+
reasoning_trace += f"\nError encountered: {str(e)}"
|
| 214 |
+
|
| 215 |
+
return final_answer_for_submission, reasoning_trace
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
|
| 217 |
# Adapter to fit interface with original app.py
|
| 218 |
class ChuckAgent:
|
| 219 |
def __init__(self):
|
| 220 |
+
required_env_vars = ['OPENAI_API_KEY', 'SERPER_API_KEY']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
missing_vars = [var for var in required_env_vars if not os.environ.get(var)]
|
| 222 |
if missing_vars:
|
|
|
|
| 223 |
error_msg = f"Missing required environment variables: {', '.join(missing_vars)}"
|
| 224 |
+
logger.critical(error_msg)
|
| 225 |
raise EnvironmentError(error_msg)
|
| 226 |
|
| 227 |
logger.info("ChuckAgent initialization started")
|
| 228 |
+
self.agent = QuestionAnsweringAgent()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
self.loop = asyncio.new_event_loop()
|
| 230 |
asyncio.set_event_loop(self.loop)
|
| 231 |
logger.info("ChuckAgent fully initialized")
|
| 232 |
|
| 233 |
+
# MODIFICATION 3: __call__ should now return a tuple (answer, reasoning_trace)
|
| 234 |
+
def __call__(self, question: str) -> tuple[str, str]:
|
| 235 |
logger.info(f"ChuckAgent received question (first 50 chars): {question[:50]}...")
|
| 236 |
+
final_answer_for_submission = "Error: Agent call failed"
|
| 237 |
+
reasoning_trace = "No reasoning trace generated due to an error."
|
| 238 |
try:
|
| 239 |
+
# process_question now returns a tuple
|
| 240 |
+
final_answer_for_submission, reasoning_trace = self.loop.run_until_complete(
|
| 241 |
+
self.agent.process_question(question)
|
| 242 |
+
)
|
| 243 |
+
logger.info(f"ChuckAgent returning answer (first 50 chars): {final_answer_for_submission[:50]}...")
|
| 244 |
+
return final_answer_for_submission, reasoning_trace
|
| 245 |
except Exception as e:
|
| 246 |
error_msg = f"Error running ChuckAgent: {str(e)}"
|
| 247 |
logger.error(error_msg, exc_info=True)
|
| 248 |
+
# Ensure tuple is returned even in case of error before process_question
|
| 249 |
+
return f"AGENT_ERROR: {error_msg}", f"AGENT_ERROR_TRACE: {error_msg}"
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
# MODIFICATION for Gradio `ClickData` AttributeError:
|
| 253 |
+
# Reverting to simpler signature for `run_and_submit_all` temporarily.
|
| 254 |
+
# The AttributeError: module 'gradio' has no attribute 'ClickData'
|
| 255 |
+
# needs to be solved by ensuring the correct Gradio version in requirements.txt.
|
| 256 |
+
# For now, this signature will accept the profile and use *args for others.
|
| 257 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None, *args): # Using *args
|
| 258 |
+
logger.info(f"run_and_submit_all called. Profile: {profile.username if profile else 'None'}")
|
| 259 |
+
if args:
|
| 260 |
+
logger.info(f"Additional args received by run_and_submit_all: {args}")
|
| 261 |
+
|
| 262 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
space_id = os.getenv("SPACE_ID")
|
| 264 |
|
| 265 |
+
if not profile:
|
|
|
|
|
|
|
|
|
|
| 266 |
logger.warning("User not logged in for run_and_submit_all.")
|
| 267 |
return "Please Login to Hugging Face with the button to run the evaluation.", pd.DataFrame()
|
| 268 |
|
| 269 |
+
username = profile.username
|
| 270 |
+
logger.info(f"User logged in: {username}")
|
| 271 |
+
|
| 272 |
api_url = DEFAULT_API_URL
|
| 273 |
questions_url = f"{api_url}/questions"
|
| 274 |
submit_url = f"{api_url}/submit"
|
| 275 |
|
| 276 |
try:
|
| 277 |
agent = ChuckAgent()
|
| 278 |
+
except EnvironmentError as e:
|
| 279 |
logger.critical(f"Agent instantiation failed due to missing env vars: {e}")
|
| 280 |
+
return f"Agent Initialization Error: {e}. Ensure API keys are in Space Secrets.", pd.DataFrame()
|
| 281 |
except Exception as e:
|
| 282 |
logger.error(f"Error instantiating ChuckAgent: {e}", exc_info=True)
|
| 283 |
+
return f"Error initializing agent: {e}", pd.DataFrame()
|
| 284 |
|
| 285 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Agent code URL not found"
|
| 286 |
logger.info(f"Agent code URL: {agent_code}")
|
| 287 |
|
| 288 |
logger.info(f"Fetching questions from: {questions_url}")
|
| 289 |
try:
|
| 290 |
+
response = requests.get(questions_url, timeout=30)
|
| 291 |
response.raise_for_status()
|
| 292 |
questions_data = response.json()
|
| 293 |
+
if not questions_data or not isinstance(questions_data, list):
|
| 294 |
+
logger.warning(f"Fetched questions empty or invalid: {questions_data}")
|
| 295 |
return "Fetched questions list is empty or not a list.", pd.DataFrame()
|
| 296 |
logger.info(f"Fetched {len(questions_data)} questions.")
|
| 297 |
except requests.exceptions.RequestException as e:
|
| 298 |
logger.error(f"Error fetching questions: {e}", exc_info=True)
|
| 299 |
return f"Error fetching questions: {e}", pd.DataFrame()
|
| 300 |
except requests.exceptions.JSONDecodeError as e:
|
| 301 |
+
logger.error(f"Error decoding questions JSON: {e}. Response: {getattr(response, 'text', 'N/A')[:500]}", exc_info=True)
|
| 302 |
return f"Error decoding server response for questions: {e}", pd.DataFrame()
|
| 303 |
+
except Exception as e:
|
| 304 |
+
logger.error(f"Unexpected error fetching questions: {e}", exc_info=True)
|
| 305 |
return f"An unexpected error occurred fetching questions: {e}", pd.DataFrame()
|
| 306 |
|
| 307 |
results_log = []
|
|
|
|
| 311 |
task_id = item.get("task_id")
|
| 312 |
question_text = item.get("question")
|
| 313 |
if not task_id or question_text is None:
|
| 314 |
+
logger.warning(f"Skipping item with missing data: {item}")
|
| 315 |
continue
|
| 316 |
|
| 317 |
logger.info(f"Processing task {i+1}/{len(questions_data)}, ID: {task_id}")
|
| 318 |
try:
|
| 319 |
+
# MODIFICATION 3: Agent now returns a tuple (answer, reasoning_trace)
|
| 320 |
+
model_ans, reasoning = agent(question_text)
|
| 321 |
+
|
| 322 |
+
# Prepare payload item
|
| 323 |
+
payload_item = {"task_id": task_id, "model_answer": model_ans}
|
| 324 |
+
if reasoning: # Add reasoning_trace if it's available and not empty
|
| 325 |
+
payload_item["reasoning_trace"] = reasoning
|
| 326 |
+
answers_payload.append(payload_item)
|
| 327 |
+
|
| 328 |
+
results_log.append({
|
| 329 |
+
"Task ID": task_id,
|
| 330 |
+
"Question": question_text,
|
| 331 |
+
"Submitted Answer": model_ans,
|
| 332 |
+
"Reasoning Trace": reasoning
|
| 333 |
+
})
|
| 334 |
except Exception as e:
|
| 335 |
logger.error(f"Error running agent on task {task_id}: {e}", exc_info=True)
|
| 336 |
+
error_answer = f"AGENT_CALL_ERROR: {e}"
|
| 337 |
+
answers_payload.append({"task_id": task_id, "model_answer": error_answer, "reasoning_trace": str(e)})
|
| 338 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": error_answer, "Reasoning Trace": str(e)})
|
|
|
|
|
|
|
| 339 |
|
| 340 |
if not answers_payload:
|
| 341 |
+
logger.warning("Agent did not produce any answers.")
|
|
|
|
| 342 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log if results_log else [])
|
| 343 |
|
|
|
|
| 344 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 345 |
+
logger.info(f"Submitting {len(answers_payload)} answers for user '{username}'...")
|
| 346 |
+
# logger.debug(f"Submission payload: {json.dumps(submission_data, indent=2)}")
|
| 347 |
+
|
| 348 |
|
|
|
|
| 349 |
try:
|
| 350 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 351 |
response.raise_for_status()
|
|
|
|
| 359 |
)
|
| 360 |
logger.info("Submission successful.")
|
| 361 |
except requests.exceptions.HTTPError as e:
|
| 362 |
+
error_detail = f"Server responded with {e.response.status_code}."
|
| 363 |
try:
|
| 364 |
error_json = e.response.json()
|
| 365 |
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 366 |
+
except requests.exceptions.JSONDecodeError:
|
| 367 |
+
error_detail += f" Raw Response: {e.response.text[:500]}"
|
| 368 |
final_status = f"Submission Failed: {error_detail}"
|
| 369 |
logger.error(final_status)
|
| 370 |
except requests.exceptions.Timeout:
|
|
|
|
| 377 |
final_status = f"An unexpected error occurred during submission: {e}"
|
| 378 |
logger.error(final_status, exc_info=True)
|
| 379 |
|
| 380 |
+
results_df = pd.DataFrame(results_log if results_log else [])
|
| 381 |
return final_status, results_df
|
| 382 |
|
| 383 |
|
|
|
|
| 394 |
Make sure you have the following **Secrets** correctly set in your Hugging Face Space settings:
|
| 395 |
- `OPENAI_API_KEY` (Your OpenAI API key)
|
| 396 |
- `SERPER_API_KEY` (Your Serper API key)
|
| 397 |
+
Ensure your `requirements.txt` specifies `gradio>=4.19.2` or newer.
|
| 398 |
"""
|
| 399 |
)
|
| 400 |
|
|
|
|
|
|
|
| 401 |
login_button = gr.LoginButton()
|
|
|
|
| 402 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 403 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=10, interactive=False) # Increased lines
|
| 404 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True, max_rows=20) # Show more rows
|
| 405 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 406 |
run_button.click(
|
| 407 |
fn=run_and_submit_all,
|
| 408 |
+
inputs=[login_button],
|
| 409 |
outputs=[status_output, results_table]
|
| 410 |
)
|
| 411 |
|
|
|
|
| 416 |
|
| 417 |
if space_host_startup:
|
| 418 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
|
|
|
|
|
|
|
| 419 |
print(f" Runtime URL might be: https://{space_host_startup}")
|
| 420 |
else:
|
| 421 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
|
|
|
| 430 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 431 |
|
| 432 |
print("Launching Gradio Interface for Chuck Agent Evaluation...")
|
| 433 |
+
demo.launch(debug=True, share=False)
|