Spaces:
Runtime error
Runtime error
newfiles_add
Browse files- README.md +15 -0
- agent.py +229 -0
- app.py +196 -0
- requirements.txt +2 -0
- system_prompt.yaml +6 -0
README.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Template Final Assignment
|
| 3 |
+
emoji: 🕵🏻♂️
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: indigo
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 5.25.2
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
hf_oauth: true
|
| 11 |
+
# optional, default duration is 8 hours/480 minutes. Max duration is 30 days/43200 minutes.
|
| 12 |
+
hf_oauth_expiration_minutes: 480
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
agent.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pandas as pd
|
| 3 |
+
from smolagents import (
|
| 4 |
+
CodeAgent,
|
| 5 |
+
LiteLLMModel,
|
| 6 |
+
DuckDuckGoSearchTool,
|
| 7 |
+
FinalAnswerTool,
|
| 8 |
+
VisitWebpageTool,
|
| 9 |
+
WikipediaSearchTool,
|
| 10 |
+
WebSearchTool,
|
| 11 |
+
tool,
|
| 12 |
+
OpenAIServerModel
|
| 13 |
+
)
|
| 14 |
+
from langchain_community.document_loaders import ArxivLoader
|
| 15 |
+
|
| 16 |
+
import requests
|
| 17 |
+
import yaml
|
| 18 |
+
from dotenv import load_dotenv
|
| 19 |
+
load_dotenv()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def fetch_questions():
|
| 23 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 24 |
+
try:
|
| 25 |
+
response = requests.get(f"{DEFAULT_API_URL}/questions")
|
| 26 |
+
response.raise_for_status()
|
| 27 |
+
questions_data = response.json()
|
| 28 |
+
if not questions_data:
|
| 29 |
+
print("Fetched questions list is empty.")
|
| 30 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 31 |
+
print(f"Fetched {len(questions_data)} questions.")
|
| 32 |
+
return questions_data
|
| 33 |
+
except Exception as e:
|
| 34 |
+
print(f"Error fetching questions: {e}")
|
| 35 |
+
raise e
|
| 36 |
+
|
| 37 |
+
def fetch_file(task_id: str, file_name: str):
|
| 38 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 39 |
+
try:
|
| 40 |
+
response = requests.get(f"{DEFAULT_API_URL}/files/{task_id}")
|
| 41 |
+
response.raise_for_status()
|
| 42 |
+
with open(f"/content/Final_Assignment_Template/data/question_files/{file_name}", "wb") as f:
|
| 43 |
+
f.write(response.content)
|
| 44 |
+
file_content = response.content
|
| 45 |
+
return file_content
|
| 46 |
+
except Exception as e:
|
| 47 |
+
print(f"Error fetching file: {e}")
|
| 48 |
+
raise e
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def submit_answers(answers):
|
| 52 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 53 |
+
request_payload = {
|
| 54 |
+
"username": "GoReed",
|
| 55 |
+
"agent_code": "test",
|
| 56 |
+
"answers": answers
|
| 57 |
+
}
|
| 58 |
+
try:
|
| 59 |
+
response = requests.post(
|
| 60 |
+
f"{DEFAULT_API_URL}/submit",
|
| 61 |
+
json=json.dumps(request_payload),
|
| 62 |
+
headers={"Content-Type": "application/json"}
|
| 63 |
+
)
|
| 64 |
+
response.raise_for_status()
|
| 65 |
+
json_response = response.json()
|
| 66 |
+
print(f"Response: {json_response}")
|
| 67 |
+
return json_response
|
| 68 |
+
except Exception as e:
|
| 69 |
+
print(f"Error submitting answers: {e}")
|
| 70 |
+
|
| 71 |
+
@tool
|
| 72 |
+
def arxiv_search(query: str) -> str:
|
| 73 |
+
"""Search Arxiv for a query and return maximum 3 result.
|
| 74 |
+
Args:
|
| 75 |
+
query: The search query."""
|
| 76 |
+
search_docs = ArxivLoader(query=query, load_max_docs=3).load()
|
| 77 |
+
formatted_search_docs = "\n\n---\n\n".join(
|
| 78 |
+
[
|
| 79 |
+
f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
|
| 80 |
+
for doc in search_docs
|
| 81 |
+
]
|
| 82 |
+
)
|
| 83 |
+
return {"arxiv_results": formatted_search_docs}
|
| 84 |
+
|
| 85 |
+
@tool
|
| 86 |
+
def read_python_file(file_name: str) -> str:
|
| 87 |
+
"""Read a python file and return the content.
|
| 88 |
+
Args:
|
| 89 |
+
file_name: The name of the file to read.
|
| 90 |
+
Returns:
|
| 91 |
+
The content of the file.
|
| 92 |
+
"""
|
| 93 |
+
base_path = "/content/Final_Assignment_Template/data/question_files"
|
| 94 |
+
with open(os.path.join(base_path, file_name), "r") as f:
|
| 95 |
+
return f.read()
|
| 96 |
+
|
| 97 |
+
@tool
|
| 98 |
+
def read_excel_file(file_name: str) -> str:
|
| 99 |
+
"""Read an excel file with xlsx extension and return the content.
|
| 100 |
+
Args:
|
| 101 |
+
file_name: The name of the file to handle.
|
| 102 |
+
Returns:
|
| 103 |
+
The content of the file.
|
| 104 |
+
"""
|
| 105 |
+
base_path = "/content/Final_Assignment_Template/data/question_files"
|
| 106 |
+
df = pd.read_excel(os.path.join(base_path, file_name))
|
| 107 |
+
return df.to_string()
|
| 108 |
+
|
| 109 |
+
@tool
|
| 110 |
+
def extract_text_from_image(image_path: str) -> str:
|
| 111 |
+
"""
|
| 112 |
+
Extract text from an image using pytesseract (if available).
|
| 113 |
+
|
| 114 |
+
Args:
|
| 115 |
+
image_path: Path to the image file
|
| 116 |
+
|
| 117 |
+
Returns:
|
| 118 |
+
Extracted text or error message
|
| 119 |
+
"""
|
| 120 |
+
try:
|
| 121 |
+
# Try to import pytesseract
|
| 122 |
+
import pytesseract
|
| 123 |
+
from PIL import Image
|
| 124 |
+
|
| 125 |
+
# Open the image
|
| 126 |
+
image = Image.open(image_path)
|
| 127 |
+
|
| 128 |
+
# Extract text
|
| 129 |
+
text = pytesseract.image_to_string(image)
|
| 130 |
+
print(f"Extracted text from image:\n\n{text}")
|
| 131 |
+
return f"Extracted text from image:\n\n{text}"
|
| 132 |
+
except ImportError:
|
| 133 |
+
return "Error: pytesseract is not installed. Please install it with 'pip install pytesseract' and ensure Tesseract OCR is installed on your system."
|
| 134 |
+
except Exception as e:
|
| 135 |
+
return f"Error extracting text from image: {str(e)}"
|
| 136 |
+
|
| 137 |
+
MODEL_ID = "ollama_chat/qwen2.5-coder:7b"
|
| 138 |
+
API_KEY = "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"
|
| 139 |
+
print(API_KEY, "HEELLLOOoooooo", os.getenv("OPENAI_API_KEY_AG"))
|
| 140 |
+
# model = LiteLLMModel(
|
| 141 |
+
# model_id=MODEL_ID,
|
| 142 |
+
# api_base="http://127.0.0.1:11434",
|
| 143 |
+
# num_ctx=8192,
|
| 144 |
+
# )
|
| 145 |
+
model = OpenAIServerModel(model_id="gpt-4.1-nano", api_key=API_KEY)
|
| 146 |
+
MODEL_ID = "openai/gpt-4.1-nano"
|
| 147 |
+
|
| 148 |
+
with open("/content/Final_Assignment_Template/system_prompt.yaml", 'r') as stream:
|
| 149 |
+
prompt_templates = yaml.safe_load(stream)
|
| 150 |
+
|
| 151 |
+
agent = CodeAgent(
|
| 152 |
+
model=model,
|
| 153 |
+
tools=[
|
| 154 |
+
WebSearchTool(),
|
| 155 |
+
VisitWebpageTool(),
|
| 156 |
+
WikipediaSearchTool(),
|
| 157 |
+
arxiv_search,
|
| 158 |
+
FinalAnswerTool(),
|
| 159 |
+
extract_text_from_image,
|
| 160 |
+
#read_python_file,
|
| 161 |
+
#read_excel_file
|
| 162 |
+
],
|
| 163 |
+
planning_interval=3,
|
| 164 |
+
max_steps=10,
|
| 165 |
+
verbosity_level=-1,
|
| 166 |
+
additional_authorized_imports=[
|
| 167 |
+
"pandas",
|
| 168 |
+
"numpy",
|
| 169 |
+
"requests",
|
| 170 |
+
"os",
|
| 171 |
+
"math",
|
| 172 |
+
"sympy",
|
| 173 |
+
"scipy",
|
| 174 |
+
"markdownify",
|
| 175 |
+
"unicodedata",
|
| 176 |
+
"stat",
|
| 177 |
+
"datetime",
|
| 178 |
+
"random",
|
| 179 |
+
"itertools",
|
| 180 |
+
"statistics",
|
| 181 |
+
"queue",
|
| 182 |
+
"time",
|
| 183 |
+
"collections",
|
| 184 |
+
"re",
|
| 185 |
+
],
|
| 186 |
+
add_base_tools=True,
|
| 187 |
+
#prompt_templates=prompt_templates,
|
| 188 |
+
)
|
| 189 |
+
questions = fetch_questions()
|
| 190 |
+
answers = []
|
| 191 |
+
counter = 0
|
| 192 |
+
for index, question in enumerate(questions):
|
| 193 |
+
# print(f"Question {index + 1}: Question Key: {question.keys()}")
|
| 194 |
+
# print(
|
| 195 |
+
# f"Task ID: {question['task_id']}\n"
|
| 196 |
+
# f"Question: {question['question']}\n"
|
| 197 |
+
# f"Level: {question['Level']}\n"
|
| 198 |
+
# f"File_name: {question['file_name']}"
|
| 199 |
+
# )
|
| 200 |
+
# if not question['file_name']:
|
| 201 |
+
# continue
|
| 202 |
+
if question['file_name']:
|
| 203 |
+
file_content = fetch_file(question['task_id'], question['file_name'])
|
| 204 |
+
file_path = os.path.join("/content/Final_Assignment_Template/data/question_files", question['file_name'])
|
| 205 |
+
#print(f"File content: {file_content}")
|
| 206 |
+
answer = agent.run(
|
| 207 |
+
f"""You are a general AI assistant.You can use the provided tools and websearch for finding answers. I will ask you a question and provide you with a file_name. Report your thoughts, and finish your answer. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
|
| 208 |
+
question:{question['question']}
|
| 209 |
+
file_path:{file_path}""",
|
| 210 |
+
)
|
| 211 |
+
else:
|
| 212 |
+
answer = agent.run(
|
| 213 |
+
f"""You are a general AI assistant.You can use the provided tools and websearch for finding answers. I will ask you a question. Report your thoughts, and finish your answer. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
|
| 214 |
+
Question:{question['question']}""",
|
| 215 |
+
)
|
| 216 |
+
print(f"Task ID: {question['task_id']} \nQuestion: {question['question']} \nAnswer: {answer}")
|
| 217 |
+
print()
|
| 218 |
+
answers.append(
|
| 219 |
+
{
|
| 220 |
+
"task_id": question['task_id'],
|
| 221 |
+
"submitted_answer": answer
|
| 222 |
+
}
|
| 223 |
+
)
|
| 224 |
+
import json
|
| 225 |
+
with open(f"/content/Final_Assignment_Template/data/answers_with_prompt_{MODEL_ID.split('/')[-1]}_with_file_content_handling.json", "w") as f:
|
| 226 |
+
json.dump(answers, f, indent=2)
|
| 227 |
+
print("Submitting answers...")
|
| 228 |
+
submit_answers(answers)
|
| 229 |
+
print("Answers submitted successfully")
|
app.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import requests
|
| 4 |
+
import inspect
|
| 5 |
+
import pandas as pd
|
| 6 |
+
|
| 7 |
+
# (Keep Constants as is)
|
| 8 |
+
# --- Constants ---
|
| 9 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
+
|
| 11 |
+
# --- Basic Agent Definition ---
|
| 12 |
+
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 13 |
+
class BasicAgent:
|
| 14 |
+
def __init__(self):
|
| 15 |
+
print("BasicAgent initialized.")
|
| 16 |
+
def __call__(self, question: str) -> str:
|
| 17 |
+
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 18 |
+
fixed_answer = "This is a default answer."
|
| 19 |
+
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 20 |
+
return fixed_answer
|
| 21 |
+
|
| 22 |
+
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 23 |
+
"""
|
| 24 |
+
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 25 |
+
and displays the results.
|
| 26 |
+
"""
|
| 27 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 28 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 29 |
+
|
| 30 |
+
if profile:
|
| 31 |
+
username= f"{profile.username}"
|
| 32 |
+
print(f"User logged in: {username}")
|
| 33 |
+
else:
|
| 34 |
+
print("User not logged in.")
|
| 35 |
+
return "Please Login to Hugging Face with the button.", None
|
| 36 |
+
|
| 37 |
+
api_url = DEFAULT_API_URL
|
| 38 |
+
questions_url = f"{api_url}/questions"
|
| 39 |
+
submit_url = f"{api_url}/submit"
|
| 40 |
+
|
| 41 |
+
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 42 |
+
try:
|
| 43 |
+
agent = BasicAgent()
|
| 44 |
+
except Exception as e:
|
| 45 |
+
print(f"Error instantiating agent: {e}")
|
| 46 |
+
return f"Error initializing agent: {e}", None
|
| 47 |
+
# In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
|
| 48 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 49 |
+
print(agent_code)
|
| 50 |
+
|
| 51 |
+
# 2. Fetch Questions
|
| 52 |
+
print(f"Fetching questions from: {questions_url}")
|
| 53 |
+
try:
|
| 54 |
+
response = requests.get(questions_url, timeout=15)
|
| 55 |
+
response.raise_for_status()
|
| 56 |
+
questions_data = response.json()
|
| 57 |
+
if not questions_data:
|
| 58 |
+
print("Fetched questions list is empty.")
|
| 59 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 60 |
+
print(f"Fetched {len(questions_data)} questions.")
|
| 61 |
+
except requests.exceptions.RequestException as e:
|
| 62 |
+
print(f"Error fetching questions: {e}")
|
| 63 |
+
return f"Error fetching questions: {e}", None
|
| 64 |
+
except requests.exceptions.JSONDecodeError as e:
|
| 65 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 66 |
+
print(f"Response text: {response.text[:500]}")
|
| 67 |
+
return f"Error decoding server response for questions: {e}", None
|
| 68 |
+
except Exception as e:
|
| 69 |
+
print(f"An unexpected error occurred fetching questions: {e}")
|
| 70 |
+
return f"An unexpected error occurred fetching questions: {e}", None
|
| 71 |
+
|
| 72 |
+
# 3. Run your Agent
|
| 73 |
+
results_log = []
|
| 74 |
+
answers_payload = []
|
| 75 |
+
print(f"Running agent on {len(questions_data)} questions...")
|
| 76 |
+
for item in questions_data:
|
| 77 |
+
task_id = item.get("task_id")
|
| 78 |
+
question_text = item.get("question")
|
| 79 |
+
if not task_id or question_text is None:
|
| 80 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
| 81 |
+
continue
|
| 82 |
+
try:
|
| 83 |
+
submitted_answer = agent(question_text)
|
| 84 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 85 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 86 |
+
except Exception as e:
|
| 87 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 88 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 89 |
+
|
| 90 |
+
if not answers_payload:
|
| 91 |
+
print("Agent did not produce any answers to submit.")
|
| 92 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 93 |
+
|
| 94 |
+
# 4. Prepare Submission
|
| 95 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 96 |
+
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 97 |
+
print(status_update)
|
| 98 |
+
|
| 99 |
+
# 5. Submit
|
| 100 |
+
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 101 |
+
try:
|
| 102 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 103 |
+
response.raise_for_status()
|
| 104 |
+
result_data = response.json()
|
| 105 |
+
final_status = (
|
| 106 |
+
f"Submission Successful!\n"
|
| 107 |
+
f"User: {result_data.get('username')}\n"
|
| 108 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 109 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 110 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
| 111 |
+
)
|
| 112 |
+
print("Submission successful.")
|
| 113 |
+
results_df = pd.DataFrame(results_log)
|
| 114 |
+
return final_status, results_df
|
| 115 |
+
except requests.exceptions.HTTPError as e:
|
| 116 |
+
error_detail = f"Server responded with status {e.response.status_code}."
|
| 117 |
+
try:
|
| 118 |
+
error_json = e.response.json()
|
| 119 |
+
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 120 |
+
except requests.exceptions.JSONDecodeError:
|
| 121 |
+
error_detail += f" Response: {e.response.text[:500]}"
|
| 122 |
+
status_message = f"Submission Failed: {error_detail}"
|
| 123 |
+
print(status_message)
|
| 124 |
+
results_df = pd.DataFrame(results_log)
|
| 125 |
+
return status_message, results_df
|
| 126 |
+
except requests.exceptions.Timeout:
|
| 127 |
+
status_message = "Submission Failed: The request timed out."
|
| 128 |
+
print(status_message)
|
| 129 |
+
results_df = pd.DataFrame(results_log)
|
| 130 |
+
return status_message, results_df
|
| 131 |
+
except requests.exceptions.RequestException as e:
|
| 132 |
+
status_message = f"Submission Failed: Network error - {e}"
|
| 133 |
+
print(status_message)
|
| 134 |
+
results_df = pd.DataFrame(results_log)
|
| 135 |
+
return status_message, results_df
|
| 136 |
+
except Exception as e:
|
| 137 |
+
status_message = f"An unexpected error occurred during submission: {e}"
|
| 138 |
+
print(status_message)
|
| 139 |
+
results_df = pd.DataFrame(results_log)
|
| 140 |
+
return status_message, results_df
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
# --- Build Gradio Interface using Blocks ---
|
| 144 |
+
with gr.Blocks() as demo:
|
| 145 |
+
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 146 |
+
gr.Markdown(
|
| 147 |
+
"""
|
| 148 |
+
**Instructions:**
|
| 149 |
+
|
| 150 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 151 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 152 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 153 |
+
|
| 154 |
+
---
|
| 155 |
+
**Disclaimers:**
|
| 156 |
+
Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
|
| 157 |
+
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
|
| 158 |
+
"""
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
gr.LoginButton()
|
| 162 |
+
|
| 163 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 164 |
+
|
| 165 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 166 |
+
# Removed max_rows=10 from DataFrame constructor
|
| 167 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 168 |
+
|
| 169 |
+
run_button.click(
|
| 170 |
+
fn=run_and_submit_all,
|
| 171 |
+
outputs=[status_output, results_table]
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
if __name__ == "__main__":
|
| 175 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 176 |
+
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 177 |
+
space_host_startup = os.getenv("SPACE_HOST")
|
| 178 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 179 |
+
|
| 180 |
+
if space_host_startup:
|
| 181 |
+
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 182 |
+
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 183 |
+
else:
|
| 184 |
+
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 185 |
+
|
| 186 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 187 |
+
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 188 |
+
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 189 |
+
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 190 |
+
else:
|
| 191 |
+
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 192 |
+
|
| 193 |
+
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 194 |
+
|
| 195 |
+
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 196 |
+
demo.launch(debug=True, share=False)
|
requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
requests
|
system_prompt.yaml
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"system_prompt": |-
|
| 2 |
+
You are a helpful assistant tasked with answering questions using a set of tools.
|
| 3 |
+
Now, I will ask you a question. Report your thoughts, and finish your answer with the following template:
|
| 4 |
+
FINAL ANSWER: [YOUR FINAL ANSWER].
|
| 5 |
+
YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
|
| 6 |
+
Your answer should only start with "FINAL ANSWER: ", then follows with the answer.
|