murphynetworks's picture
Initial setup with smolagents implementation
8e01d85
Raw History Blame Contribute Delete
6.37 kB
#!/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()