File size: 4,689 Bytes
c288490 90d7802 c288490 90d7802 c288490 90d7802 c288490 90d7802 c288490 90d7802 c288490 90d7802 c288490 90d7802 c288490 90d7802 c288490 90d7802 c288490 90d7802 c288490 90d7802 c288490 90d7802 c288490 90d7802 c288490 90d7802 c288490 90d7802 | 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 | #!/usr/bin/env python3
"""
Test script for running the enhanced agent on a single API question.
"""
import os
import json
import logging
import requests
from dotenv import load_dotenv
from enhanced_agent import EnhancedAgent
from tools.attachment_handler import cleanup_temp_file
# Load environment variables
load_dotenv()
# Configure basic logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# 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"
}
# API URL for questions
QUESTIONS_URL = "https://agents-course-unit4-scoring.hf.space/questions"
def fetch_first_question():
"""Fetch the first question from the evaluation API."""
try:
logger.info(f"Fetching questions from {QUESTIONS_URL}")
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) or len(questions) == 0:
logger.error(f"Unexpected API response format or empty list: {questions}")
return None
# Return the first question
logger.info(f"Successfully fetched the first question (Task ID: {questions[0]['task_id']})")
return questions[0]
except Exception as e:
logger.error(f"Error fetching questions: {str(e)}")
return None
def run_agent_on_question(question):
"""Run the enhanced agent on a single question."""
if not question:
logger.error("No question to process")
return
task_id = question["task_id"]
question_text = question["question"]
# Display question info
print(f"\n{COLORS['BOLD']}{COLORS['MAGENTA']}====================================={COLORS['RESET']}")
print(f"{COLORS['BOLD']}{COLORS['MAGENTA']}QUESTION (Task ID: {task_id}){COLORS['RESET']}")
print(f"{COLORS['BOLD']}{COLORS['MAGENTA']}====================================={COLORS['RESET']}")
print(f"{COLORS['BOLD']}{COLORS['GREEN']}QUESTION TEXT:{COLORS['RESET']}\n{question_text}")
print(f"{COLORS['BOLD']}{COLORS['MAGENTA']}====================================={COLORS['RESET']}")
# Initialize the agent
try:
model = os.getenv("OPENROUTER_MODEL", "anthropic/claude-3-5-sonnet")
logger.info(f"Initializing agent with model: {model}")
agent = EnhancedAgent(model=model)
logger.info("Agent initialized successfully")
# Process the question
logger.info("Starting agent execution...")
answer = agent(question_text, task_id=task_id)
# Display 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")
return {
"task_id": task_id,
"question": question_text,
"answer": answer
}
except Exception as e:
error_msg = f"Error processing question: {str(e)}"
logger.error(error_msg)
print(f"\n{COLORS['RED']}{error_msg}{COLORS['RESET']}")
return None
def main():
"""Main function to run the test."""
print(f"{COLORS['BOLD']}{COLORS['BLUE']}Testing Enhanced Agent on a Single API Question{COLORS['RESET']}")
# Fetch the first question
question = fetch_first_question()
if not question:
return 1
# Run the agent on the question
result = run_agent_on_question(question)
if not result:
return 1
print(f"{COLORS['BOLD']}{COLORS['BLUE']}Test completed successfully!{COLORS['RESET']}")
return 0
if __name__ == "__main__":
try:
exit_code = main()
except KeyboardInterrupt:
print(f"\n{COLORS['YELLOW']}Test interrupted by user.{COLORS['RESET']}")
exit_code = 130
except Exception as e:
print(f"\n{COLORS['RED']}Unexpected error: {str(e)}{COLORS['RESET']}")
logger.exception("Unexpected error")
exit_code = 1
# Ensure we clean up any temporary files
try:
import glob
temp_files = glob.glob("/tmp/attachment_*")
for file in temp_files:
cleanup_temp_file(file)
except:
pass
exit(exit_code) |