File size: 6,372 Bytes
8e01d85 | 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 | #!/usr/bin/env python3
import os
import json
import requests
import argparse
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Constants
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
# Import the agent
from agent import SmolAgent
def fetch_questions(api_url=DEFAULT_API_URL):
"""Fetch all questions from the API."""
questions_url = f"{api_url}/questions"
print(f"Fetching questions from: {questions_url}")
try:
response = requests.get(questions_url, timeout=15)
response.raise_for_status()
questions_data = response.json()
if not questions_data:
print("Fetched questions list is empty.")
return None
print(f"Fetched {len(questions_data)} questions.")
return questions_data
except requests.exceptions.RequestException as e:
print(f"Error fetching questions: {e}")
return None
except requests.exceptions.JSONDecodeError as e:
print(f"Error decoding JSON response from questions endpoint: {e}")
print(f"Response text: {response.text[:500]}")
return None
except Exception as e:
print(f"An unexpected error occurred fetching questions: {e}")
return None
def fetch_random_question(api_url=DEFAULT_API_URL):
"""Fetch a single random question from the API."""
random_question_url = f"{api_url}/random-question"
print(f"Fetching random question from: {random_question_url}")
try:
response = requests.get(random_question_url, timeout=15)
response.raise_for_status()
question_data = response.json()
return question_data
except requests.exceptions.RequestException as e:
print(f"Error fetching random question: {e}")
return None
except requests.exceptions.JSONDecodeError as e:
print(f"Error decoding JSON response from random question endpoint: {e}")
print(f"Response text: {response.text[:500]}")
return None
except Exception as e:
print(f"An unexpected error occurred fetching random question: {e}")
return None
def fetch_file(task_id, api_url=DEFAULT_API_URL):
"""Fetch a file for a task if one exists."""
file_url = f"{api_url}/files/{task_id}"
print(f"Fetching file for task {task_id} from: {file_url}")
try:
response = requests.get(file_url, timeout=15)
if response.status_code == 404:
print(f"No file found for task {task_id}")
return None
response.raise_for_status()
return response.content
except requests.exceptions.RequestException as e:
print(f"Error fetching file: {e}")
return None
except Exception as e:
print(f"An unexpected error occurred fetching file: {e}")
return None
def test_agent_on_question(agent, question, save_file=False):
"""Test the agent on a single question and display the result."""
task_id = question.get("task_id")
question_text = question.get("question")
level = question.get("Level", "Unknown")
file_name = question.get("file_name", "")
print(f"\n{'='*80}")
print(f"Task ID: {task_id}")
print(f"Level: {level}")
print(f"Question: {question_text}")
# Check if there's a file associated with this question
file_content = None
file_path = None
if file_name:
print(f"File Name: {file_name}")
file_content = fetch_file(task_id)
if file_content and save_file:
os.makedirs("downloaded_files", exist_ok=True)
file_path = os.path.join("downloaded_files", file_name)
with open(file_path, "wb") as f:
f.write(file_content)
print(f"File saved to: {file_path}")
try:
print("\nRunning agent...")
# Pass additional context to the agent if there's a file
context = {}
if file_content and file_path:
context = {
"file_name": file_name,
"file_path": file_path
}
answer = agent(question_text, context=context)
print(f"\nAgent's answer: {answer}")
return {"task_id": task_id, "submitted_answer": answer}
except Exception as e:
print(f"\nError running agent: {e}")
return None
def main():
parser = argparse.ArgumentParser(description="CLI for the Agent Evaluation")
parser.add_argument("--all", action="store_true", help="Run against all questions")
parser.add_argument("--random", action="store_true", help="Run against a random question")
parser.add_argument("--save-files", action="store_true", help="Save downloaded files")
parser.add_argument("--api-url", default=DEFAULT_API_URL, help="API URL")
parser.add_argument("--openrouter-key", help="OpenRouter API key (or set OPENROUTER_API_KEY env var)")
parser.add_argument("--model", default="anthropic/claude-3-5-sonnet", help="Model to use for the agent")
args = parser.parse_args()
# Get API key either from command line or environment variable
openrouter_api_key = args.openrouter_key or os.getenv("OPENROUTER_API_KEY")
if not openrouter_api_key:
print("OpenRouter API key is required. Set it via --openrouter-key or OPENROUTER_API_KEY env var.")
return
# Initialize the agent
try:
agent = SmolAgent(openrouter_api_key, model=args.model)
print("Agent initialized successfully.")
except Exception as e:
print(f"Error initializing agent: {e}")
return
# Run agent on questions
results = []
if args.all:
questions = fetch_questions(args.api_url)
if questions:
for question in questions:
result = test_agent_on_question(agent, question, args.save_files)
if result:
results.append(result)
# Save results to a file
with open("results.json", "w") as f:
json.dump(results, f, indent=2)
print(f"\nSaved {len(results)} results to results.json")
elif args.random:
question = fetch_random_question(args.api_url)
if question:
test_agent_on_question(agent, question, args.save_files)
else:
parser.print_help()
if __name__ == "__main__":
main() |