Final_Assignment_Template / enhanced_integration.py
murphynetworks's picture
feat: Add improved code handling and prevent timeouts for infinite loops
90d7802
Raw History Blame Contribute Delete
11.5 kB
#!/usr/bin/env python3
"""
Integration script that connects our EnhancedAgent to the app.py submission system.
This version includes improved file handling, better logging, and enhanced error recovery.
"""
import os
import json
import logging
import requests
import tempfile
from datetime import datetime
from pathlib import Path
import gradio as gr
from enhanced_agent import EnhancedAgent
from tools.attachment_handler import download_file_by_task_id, cleanup_temp_file
from dotenv import load_dotenv
# Set up colorful logging
class ColoredFormatter(logging.Formatter):
"""Custom formatter with ANSI colors for log levels"""
COLORS = {
'DEBUG': '\033[94m', # Blue
'INFO': '\033[92m', # Green
'WARNING': '\033[93m', # Yellow
'ERROR': '\033[91m', # Red
'CRITICAL': '\033[91m\033[1m', # Bold Red
}
RESET = '\033[0m'
def format(self, record):
log_message = super().format(record)
if record.levelname in self.COLORS:
return f"{self.COLORS[record.levelname]}{log_message}{self.RESET}"
return log_message
# Set up logging
log_filename = f"agent_run_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(log_filename) # Log to file (without colors)
]
)
# Add colored console handler
console_handler = logging.StreamHandler()
console_handler.setFormatter(ColoredFormatter('%(asctime)s - %(levelname)s - %(message)s'))
logging.getLogger().addHandler(console_handler)
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"
FILES_URL = "https://agents-course-unit4-scoring.hf.space/files"
# Username and code link for submission
USERNAME = os.getenv("USERNAME", "YOUR_USERNAME_HERE")
CODE_LINK = os.getenv("CODE_LINK", "YOUR_GITHUB_REPO_LINK")
# Get model from environment or default to Claude
MODEL = os.getenv("OPENROUTER_MODEL", "anthropic/claude-3-5-sonnet")
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 enhanced agent on each question and collect answers."""
# Initialize the enhanced agent
agent = EnhancedAgent(model=MODEL)
answers = []
# 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"
}
for i, question in enumerate(questions):
task_id = question["task_id"]
question_text = question["question"]
# 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(f"{separator}")
logger.info(f"QUESTION TEXT:\n{question_text}")
logger.info(f"{separator}")
# Run the agent on the question
try:
logger.info("Starting agent execution...")
# Call the enhanced agent with the task_id for file attachment handling
answer = agent(question_text, task_id=task_id)
# Log the answer
print(f"\n{COLORS['BOLD']}{COLORS['WHITE']}=== FINAL ANSWER ==={COLORS['RESET']}")
print(f"{COLORS['BOLD']}{COLORS['GREEN']}{answer}{COLORS['RESET']}")
print(f"{COLORS['BOLD']}{COLORS['WHITE']}================={COLORS['RESET']}\n")
logger.info(f"{separator}\nANSWER:\n{answer}\n{separator}")
# Store the answer
answers.append({
"task_id": task_id,
"submitted_answer": answer
})
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 {"error": 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 isinstance(submission_response, dict) and "error" in submission_response:
logger.error(f"Submission error: {submission_response['error']}")
return {"error": 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("# Enhanced Agent Evaluation Interface")
gr.Markdown("This interface uses the EnhancedAgent with specialized tools for different question types.")
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():
model_input = gr.Dropdown(
label="Model",
choices=[
"anthropic/claude-3-5-sonnet",
"anthropic/claude-3-opus-20240229",
"openai/gpt-4o",
"google/gemini-pro",
"meta-llama/llama-3-70b-instruct"
],
value=MODEL
)
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, model):
global USERNAME, CODE_LINK, MODEL
USERNAME = username
CODE_LINK = code_link
MODEL = model
logger.info(f"Updated username to: {username}")
logger.info(f"Updated code link to: {code_link}")
logger.info(f"Updated model to: {model}")
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, model_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)