Spaces:
Configuration error
Configuration error
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,148 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import gradio as gr
|
| 3 |
-
import requests
|
| 4 |
-
import pandas as pd
|
| 5 |
-
from smolagents import CodeAgent, DuckDuckGoSearchTool
|
| 6 |
-
|
| 7 |
-
# Constants
|
| 8 |
-
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 9 |
-
|
| 10 |
-
class HfApiModel:
|
| 11 |
-
def __init__(self, model_name="tiiuae/falcon-7b-instruct", api_key=None):
|
| 12 |
-
self.model_name = model_name
|
| 13 |
-
self.api_key = api_key or os.getenv("HF_TOKEN")
|
| 14 |
-
if not self.api_key:
|
| 15 |
-
raise ValueError("HF_TOKEN environment variable is missing.")
|
| 16 |
-
|
| 17 |
-
def __call__(self, prompt):
|
| 18 |
-
url = f"https://api-inference.huggingface.co/models/{self.model_name}"
|
| 19 |
-
headers = {"Authorization": f"Bearer {self.api_key}"}
|
| 20 |
-
payload = {"inputs": prompt, "options": {"wait_for_model": True}}
|
| 21 |
-
|
| 22 |
-
response = requests.post(url, headers=headers, json=payload, timeout=60)
|
| 23 |
-
response.raise_for_status()
|
| 24 |
-
output = response.json()
|
| 25 |
-
|
| 26 |
-
try:
|
| 27 |
-
return output[0]["generated_text"]
|
| 28 |
-
except Exception:
|
| 29 |
-
return f"ERROR: {output}"
|
| 30 |
-
|
| 31 |
-
def generate(self, prompt, **kwargs):
|
| 32 |
-
# Accept any extra keyword arguments to avoid errors
|
| 33 |
-
return self.__call__(prompt)
|
| 34 |
-
|
| 35 |
-
class BasicAgent:
|
| 36 |
-
def __init__(self):
|
| 37 |
-
print("BasicAgent initialized.")
|
| 38 |
-
self.agent = CodeAgent(
|
| 39 |
-
tools=[DuckDuckGoSearchTool()],
|
| 40 |
-
model=HfApiModel(model_name="tiiuae/falcon-7b-instruct")
|
| 41 |
-
)
|
| 42 |
-
SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and
|
| 43 |
-
finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER].
|
| 44 |
-
YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated
|
| 45 |
-
list of numbers and/or strings.
|
| 46 |
-
If you are asked for a number, don't use comma to write your number neither use units such as $ or
|
| 47 |
-
percent sign unless specified otherwise.
|
| 48 |
-
If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the
|
| 49 |
-
digits in plain text unless specified otherwise.
|
| 50 |
-
If you are asked for a comma separated list, apply the above rules depending of whether the element
|
| 51 |
-
to be put in the list is a number or a string.
|
| 52 |
-
"""
|
| 53 |
-
self.agent.prompt_templates["system_prompt"] += SYSTEM_PROMPT
|
| 54 |
-
|
| 55 |
-
def __call__(self, question: str) -> str:
|
| 56 |
-
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 57 |
-
final_answer = self.agent.run(question)
|
| 58 |
-
print(f"Agent returning final answer: {final_answer}")
|
| 59 |
-
return final_answer
|
| 60 |
-
|
| 61 |
-
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 62 |
-
space_id = os.getenv("SPACE_ID")
|
| 63 |
-
|
| 64 |
-
if profile:
|
| 65 |
-
username = profile.username
|
| 66 |
-
print(f"User logged in: {username}")
|
| 67 |
-
else:
|
| 68 |
-
print("User not logged in.")
|
| 69 |
-
return "Please Login to Hugging Face with the button.", None
|
| 70 |
-
|
| 71 |
-
api_url = DEFAULT_API_URL
|
| 72 |
-
questions_url = f"{api_url}/questions"
|
| 73 |
-
submit_url = f"{api_url}/submit"
|
| 74 |
-
|
| 75 |
-
try:
|
| 76 |
-
agent = BasicAgent()
|
| 77 |
-
except Exception as e:
|
| 78 |
-
print(f"Error instantiating agent: {e}")
|
| 79 |
-
return f"Error initializing agent: {e}", None
|
| 80 |
-
|
| 81 |
-
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "No SPACE_ID found"
|
| 82 |
-
|
| 83 |
-
try:
|
| 84 |
-
response = requests.get(questions_url, timeout=15)
|
| 85 |
-
response.raise_for_status()
|
| 86 |
-
questions_data = response.json()
|
| 87 |
-
if not questions_data:
|
| 88 |
-
return "Fetched questions list is empty or invalid format.", None
|
| 89 |
-
except Exception as e:
|
| 90 |
-
return f"Error fetching questions: {e}", None
|
| 91 |
-
|
| 92 |
-
answers_payload = []
|
| 93 |
-
results_log = []
|
| 94 |
-
|
| 95 |
-
for item in questions_data:
|
| 96 |
-
task_id = item.get("task_id")
|
| 97 |
-
question_text = item.get("question")
|
| 98 |
-
if not task_id or question_text is None:
|
| 99 |
-
print(f"Skipping item with missing task_id or question: {item}")
|
| 100 |
-
continue
|
| 101 |
-
try:
|
| 102 |
-
submitted_answer = agent(question_text)
|
| 103 |
-
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 104 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 105 |
-
except Exception as e:
|
| 106 |
-
print(f"Error running agent on task {task_id}: {e}")
|
| 107 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 108 |
-
|
| 109 |
-
if not answers_payload:
|
| 110 |
-
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 111 |
-
|
| 112 |
-
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 113 |
-
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 114 |
-
|
| 115 |
-
try:
|
| 116 |
-
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 117 |
-
response.raise_for_status()
|
| 118 |
-
result_data = response.json()
|
| 119 |
-
final_status = (
|
| 120 |
-
f"Submission Successful!\n"
|
| 121 |
-
f"User: {result_data.get('username')}\n"
|
| 122 |
-
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 123 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 124 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
| 125 |
-
)
|
| 126 |
-
print("Submission successful.")
|
| 127 |
-
return final_status, pd.DataFrame(results_log)
|
| 128 |
-
except Exception as e:
|
| 129 |
-
print(f"Submission failed: {e}")
|
| 130 |
-
return f"Submission Failed: {e}", pd.DataFrame(results_log)
|
| 131 |
-
|
| 132 |
-
with gr.Blocks() as demo:
|
| 133 |
-
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 134 |
-
gr.Markdown(
|
| 135 |
-
"Clone this space, modify the code to define your agent logic in `BasicAgent`. "
|
| 136 |
-
"Log in with your HF account, then click 'Run Evaluation & Submit All Answers' to submit."
|
| 137 |
-
)
|
| 138 |
-
|
| 139 |
-
gr.LoginButton()
|
| 140 |
-
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 141 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 142 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 143 |
-
|
| 144 |
-
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
| 145 |
-
|
| 146 |
-
if __name__ == "__main__":
|
| 147 |
-
print("\nStarting Basic Agent Evaluation App...")
|
| 148 |
-
demo.launch(debug=True, share=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|