File size: 14,746 Bytes
c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 bd83de1 0907ef1 bd83de1 0907ef1 c288490 0907ef1 c288490 0907ef1 5d282cd 0907ef1 5d282cd 0907ef1 5d282cd 0907ef1 5d282cd 0907ef1 5d282cd bd83de1 5d282cd bd83de1 5d282cd bd83de1 5d282cd 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 0907ef1 c288490 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 | #!/usr/bin/env python3
"""
Integration script that connects our DirectAgent to the app.py submission system.
"""
import os
import json
import logging
import requests
import tempfile
from datetime import datetime
from pathlib import Path
import gradio as gr
from direct_agent_fixed import DirectAgent
from dotenv import load_dotenv
# Set up logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(), # Log to console
logging.FileHandler(f"agent_run_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log") # Log to file
]
)
logger = logging.getLogger(__name__)
# Load environment variables
load_dotenv()
# URLs for the evaluation API
QUESTIONS_URL = "https://agents-course-unit4-scoring.hf.space/questions"
SUBMIT_URL = "https://agents-course-unit4-scoring.hf.space/submit"
# Username and code link for submission
USERNAME = os.getenv("USERNAME", "YOUR_USERNAME_HERE")
CODE_LINK = os.getenv("CODE_LINK", "YOUR_CODE_LINK_HERE")
def download_file(url, task_id):
"""Download a file from a URL and save it to a temporary location."""
try:
response = requests.get(url)
response.raise_for_status()
# Create a temporary file with the right extension
file_extension = Path(url).suffix.lower()
# If no extension or weird extension, try to guess from content-type
if not file_extension:
content_type = response.headers.get('content-type', '')
if 'excel' in content_type or 'spreadsheet' in content_type:
file_extension = '.xlsx'
elif 'csv' in content_type:
file_extension = '.csv'
# Create temporary file with correct extension
with tempfile.NamedTemporaryFile(delete=False, suffix=file_extension) as temp_file:
temp_file.write(response.content)
temp_file_path = temp_file.name
# Get the original filename from the URL
filename = Path(url).name
return {
"file_path": temp_file_path,
"file_name": filename,
"task_id": task_id
}
except Exception as e:
return {"error": f"Error downloading file: {str(e)}"}
def fetch_questions():
"""Fetch questions from the evaluation API."""
try:
response = requests.get(QUESTIONS_URL)
response.raise_for_status()
questions = response.json()
# Check if the response is a list (as expected) or something else
if not isinstance(questions, list):
return {"error": f"Unexpected API response format: {questions}"}
return questions
except Exception as e:
return {"error": f"Error fetching questions: {str(e)}"}
def run_agent_on_questions(questions):
"""Run the agent on each question and collect answers."""
agent = DirectAgent()
answers = []
for i, question in enumerate(questions):
task_id = question["task_id"]
question_text = question["question"]
# ANSI color codes for terminal output
COLORS = {
"RED": "\033[91m",
"GREEN": "\033[92m",
"YELLOW": "\033[93m",
"BLUE": "\033[94m",
"MAGENTA": "\033[95m",
"CYAN": "\033[96m",
"WHITE": "\033[97m",
"BOLD": "\033[1m",
"RESET": "\033[0m"
}
# Create a separator line for better logging visibility
separator = "=" * 80
# Colorful question display in console
print(f"\n{COLORS['BOLD']}{COLORS['MAGENTA']}{separator}{COLORS['RESET']}")
print(f"{COLORS['BOLD']}{COLORS['MAGENTA']}QUESTION {i+1}/{len(questions)} (Task ID: {task_id}){COLORS['RESET']}")
print(f"{COLORS['BOLD']}{COLORS['MAGENTA']}{separator}{COLORS['RESET']}")
print(f"{COLORS['BOLD']}{COLORS['GREEN']}QUESTION TEXT:{COLORS['RESET']}\n{question_text}")
print(f"{COLORS['BOLD']}{COLORS['MAGENTA']}{separator}{COLORS['RESET']}")
# Also log to file
logger.info(f"\n{separator}")
logger.info(f"QUESTION {i+1}/{len(questions)} (Task ID: {task_id})")
logger.info(separator)
logger.info(f"QUESTION TEXT:\n{question_text}")
logger.info(separator)
# Check if there's a file URL
file_context = None
if "file_url" in question and question["file_url"]:
file_url = question["file_url"]
logger.info(f"File attachment detected: {file_url}")
file_info = download_file(file_url, task_id)
if "error" not in file_info:
file_context = file_info
logger.info(f"Downloaded file: {file_info['file_name']} to {file_info['file_path']}")
else:
logger.error(f"Error downloading file: {file_info.get('error')}")
# Create a wrapper for the agent to capture logs
class LoggingAgent:
def __init__(self, agent):
self.agent = agent
def __call__(self, question, context=None):
# Create a custom handler to capture the agent's output
class AgentOutputHandler:
def __init__(self):
self.buffer = []
def write(self, message):
if message.strip(): # Only log non-empty lines
# Log directly to file and preserve in buffer
self.buffer.append(message.strip())
# Use different log levels based on content
if message.startswith("==="):
logger.info(message.strip())
elif "ERROR" in message:
logger.error(message.strip())
else:
logger.debug(message.strip())
def flush(self):
pass
# Set up a custom handler to capture standard output
import sys
import io
from contextlib import redirect_stdout
output_handler = AgentOutputHandler()
# Create a StringIO object to capture all output
string_output = io.StringIO()
# Use contextlib to redirect stdout to both our handlers
with redirect_stdout(output_handler):
# Call the actual agent
result = self.agent(question, context)
# ANSI color codes for terminal output
COLORS = {
"RED": "\033[91m",
"GREEN": "\033[92m",
"YELLOW": "\033[93m",
"BLUE": "\033[94m",
"MAGENTA": "\033[95m",
"CYAN": "\033[96m",
"WHITE": "\033[97m",
"BOLD": "\033[1m",
"RESET": "\033[0m"
}
# Create an all-caps delimiter for the final answer
delimiter = "=" * 80
print(f"\n{COLORS['BOLD']}{COLORS['GREEN']}{delimiter}")
print(f"{COLORS['BOLD']}{COLORS['GREEN']}FINAL MINIMAL ANSWER:{COLORS['RESET']}")
print(f"{COLORS['BOLD']}{result}{COLORS['RESET']}")
print(f"{COLORS['BOLD']}{COLORS['GREEN']}{delimiter}{COLORS['RESET']}\n")
# Also log to file
logger.info(delimiter)
logger.info("FINAL MINIMAL ANSWER:")
logger.info(result)
logger.info(delimiter)
return result
# Create the logging agent
logging_agent = LoggingAgent(agent)
# Run the agent on the question
try:
logger.info("Starting agent execution...")
answer = logging_agent(question_text, context=file_context)
# Log the answer
answer_preview = answer[:200] + "..." if len(answer) > 200 else answer
logger.info(f"{separator}\nANSWER:\n{answer_preview}\n{separator}")
# Store the answer
answers.append({
"task_id": task_id,
"submitted_answer": answer
})
# Clean up any temporary files
if file_context and "file_path" in file_context:
try:
os.unlink(file_context["file_path"])
logger.debug(f"Deleted temporary file: {file_context['file_path']}")
except Exception as e:
logger.warning(f"Error deleting temporary file: {str(e)}")
except Exception as e:
logger.error(f"Error running agent on question {task_id}: {str(e)}")
# Still add the error message as the answer
answers.append({
"task_id": task_id,
"submitted_answer": f"Error generating answer: {str(e)}"
})
return answers
def submit_answers(answers):
"""Submit answers to the evaluation API."""
try:
submission = {
"username": USERNAME,
"agent_code": CODE_LINK,
"answers": answers
}
logger.info(f"Submitting answers for {len(answers)} questions...")
logger.info(f"Username: {USERNAME}")
logger.info(f"Code link: {CODE_LINK}")
response = requests.post(SUBMIT_URL, json=submission)
response.raise_for_status()
result = response.json()
logger.info(f"Submission successful!")
logger.info(f"Response: {json.dumps(result, indent=2)}")
return result
except Exception as e:
error_msg = f"Error submitting answers: {str(e)}"
logger.error(error_msg)
return {"error": error_msg}
def run_full_evaluation():
"""Run the full evaluation process: fetch questions, run agent, submit answers."""
logger.info("=" * 80)
logger.info("STARTING FULL EVALUATION")
logger.info("=" * 80)
# 1. Fetch questions
logger.info("Fetching questions from API...")
questions = fetch_questions()
if isinstance(questions, dict) and "error" in questions:
logger.error(f"Error fetching questions: {questions['error']}")
return questions["error"]
logger.info(f"Received {len(questions)} questions from API")
# 2. Run agent on questions
logger.info("\nRunning agent on all questions...")
answers = run_agent_on_questions(questions)
logger.info(f"Agent processing complete for all {len(answers)} questions")
# 3. Submit answers
logger.info("\nSubmitting answers to evaluation API...")
submission_response = submit_answers(answers)
if "error" in submission_response:
logger.error(f"Submission error: {submission_response['error']}")
return submission_response["error"]
# 4. Return result
logger.info("=" * 80)
logger.info("EVALUATION COMPLETE")
logger.info("=" * 80)
return submission_response
def create_interface():
"""Create a Gradio interface for running the evaluation."""
with gr.Blocks() as interface:
gr.Markdown("# Agent Evaluation Interface")
with gr.Row():
username_input = gr.Textbox(label="Username", value=USERNAME)
code_link_input = gr.Textbox(label="Code Link", value=CODE_LINK)
with gr.Row():
run_button = gr.Button("Run Evaluation")
status = gr.Textbox(label="Status")
with gr.Row():
results = gr.JSON(label="Results")
with gr.Row():
log_output = gr.Textbox(label="Log Output", lines=20)
def update_env_and_run(username, code_link):
global USERNAME, CODE_LINK
USERNAME = username
CODE_LINK = code_link
logger.info(f"Updated username to: {username}")
logger.info(f"Updated code link to: {code_link}")
return "Running evaluation...", None, "Starting evaluation... Check console for detailed logs."
def run_evaluation():
result = run_full_evaluation()
# Get the log file content for display
log_content = ""
try:
log_files = sorted([f for f in os.listdir('.') if f.startswith('agent_run_') and f.endswith('.log')])
if log_files:
with open(log_files[-1], 'r') as f:
log_content = f.read()
# Truncate if too long
if len(log_content) > 10000:
log_content = log_content[-10000:]
log_content = "... (log truncated) ...\n\n" + log_content
except Exception as e:
log_content = f"Error reading log file: {str(e)}"
return "Evaluation complete", result, log_content
run_button.click(
fn=update_env_and_run,
inputs=[username_input, code_link_input],
outputs=[status, results, log_output]
).then(
fn=run_evaluation,
inputs=None,
outputs=[status, results, log_output]
)
return interface
if __name__ == "__main__":
# Check if we should run with UI or headless
import sys
if len(sys.argv) > 1 and sys.argv[1] == "--headless":
# Run in headless mode (just run the evaluation)
logger.info("Running in headless mode")
result = run_full_evaluation()
logger.info("\nFinal result:")
logger.info(json.dumps(result, indent=2))
# Also print to console for convenience
print("\nFinal result:")
print(json.dumps(result, indent=2))
# Print log file location
log_files = sorted([f for f in os.listdir('.') if f.startswith('agent_run_') and f.endswith('.log')])
if log_files:
print(f"\nDetailed logs saved to: {log_files[-1]}")
else:
# Run with the UI
logger.info("Starting with UI mode")
interface = create_interface()
interface.launch(share=False) |