Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,123 +7,94 @@ from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
| 7 |
# --- Constants ---
|
| 8 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 9 |
|
| 10 |
-
# ---
|
| 11 |
class BasicAgent:
|
| 12 |
def __init__(self):
|
| 13 |
print("BasicAgent initialized.")
|
| 14 |
-
self.client = None # Placeholder for Groq or another API client
|
| 15 |
-
self.agent_prompt = (
|
| 16 |
-
"""You are a general AI assistant. I will ask you a question. Report your thoughts, and
|
| 17 |
-
finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]."""
|
| 18 |
-
)
|
| 19 |
-
|
| 20 |
-
# Assuming some model for queries
|
| 21 |
self.llm = AutoModelForCausalLM.from_pretrained("gpt2")
|
| 22 |
self.tokenizer = AutoTokenizer.from_pretrained("gpt2")
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
def query_tools(self, question: str) -> str:
|
| 29 |
-
# Placeholder for using tools
|
| 30 |
-
return f"FINAL ANSWER: {question}"
|
| 31 |
|
| 32 |
def __call__(self, question: str) -> str:
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
| 37 |
|
| 38 |
-
# ---
|
| 39 |
-
def run_and_submit_all(
|
| 40 |
-
space_id = os.getenv("SPACE_ID")
|
| 41 |
-
if
|
| 42 |
-
|
| 43 |
-
print(f"User logged in: {username}")
|
| 44 |
-
else:
|
| 45 |
-
return "Please provide a username.", None
|
| 46 |
|
| 47 |
-
|
| 48 |
-
questions_url = f"{api_url}/questions"
|
| 49 |
-
submit_url = f"{api_url}/submit"
|
| 50 |
-
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
return f"Error initializing agent: {e}", None
|
| 56 |
|
| 57 |
try:
|
| 58 |
response = requests.get(questions_url, timeout=15)
|
| 59 |
response.raise_for_status()
|
| 60 |
questions_data = response.json()
|
| 61 |
-
if not questions_data:
|
| 62 |
-
return "Fetched questions list is empty or invalid format.", None
|
| 63 |
except Exception as e:
|
| 64 |
-
return f"
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
| 68 |
|
| 69 |
for item in questions_data:
|
| 70 |
task_id = item.get("task_id")
|
| 71 |
-
|
| 72 |
-
if not task_id or
|
| 73 |
continue
|
| 74 |
try:
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
except Exception as e:
|
| 79 |
-
|
| 80 |
|
| 81 |
-
if not
|
| 82 |
-
return "
|
| 83 |
|
| 84 |
-
|
| 85 |
"username": username.strip(),
|
| 86 |
"agent_code": agent_code,
|
| 87 |
-
"answers":
|
| 88 |
}
|
| 89 |
|
| 90 |
try:
|
| 91 |
-
response = requests.post(submit_url, json=
|
| 92 |
response.raise_for_status()
|
| 93 |
-
|
| 94 |
-
|
| 95 |
f"Submission Successful!\n"
|
| 96 |
-
f"User: {
|
| 97 |
-
f"
|
| 98 |
-
f"({
|
| 99 |
-
f"Message: {
|
| 100 |
)
|
| 101 |
-
return
|
| 102 |
except Exception as e:
|
| 103 |
-
return f"Submission
|
| 104 |
|
| 105 |
# --- Gradio UI ---
|
| 106 |
with gr.Blocks() as demo:
|
| 107 |
-
gr.Markdown("
|
| 108 |
-
gr.Markdown(
|
| 109 |
-
"""
|
| 110 |
-
**Instructions:**
|
| 111 |
-
1. Clone and customize your agent logic.
|
| 112 |
-
2. Log in with Hugging Face.
|
| 113 |
-
3. Click the button to run evaluation and submit your answers.
|
| 114 |
-
"""
|
| 115 |
-
)
|
| 116 |
-
profile_input = gr.Textbox(label="Enter Username", placeholder="Enter your username", interactive=True)
|
| 117 |
-
run_button = gr.Button("Run Evaluation")
|
| 118 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 119 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
|
|
|
| 126 |
|
| 127 |
if __name__ == "__main__":
|
| 128 |
-
|
| 129 |
-
demo.launch(debug=True, share=False)
|
|
|
|
| 7 |
# --- Constants ---
|
| 8 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 9 |
|
| 10 |
+
# --- Basic Agent Logic ---
|
| 11 |
class BasicAgent:
|
| 12 |
def __init__(self):
|
| 13 |
print("BasicAgent initialized.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
self.llm = AutoModelForCausalLM.from_pretrained("gpt2")
|
| 15 |
self.tokenizer = AutoTokenizer.from_pretrained("gpt2")
|
| 16 |
+
self.agent_prompt = (
|
| 17 |
+
"You are a general AI assistant. I will ask you a question. "
|
| 18 |
+
"Finish your answer with the format: FINAL ANSWER: [YOUR FINAL ANSWER]."
|
| 19 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
def __call__(self, question: str) -> str:
|
| 22 |
+
input_text = f"{self.agent_prompt}\n\nQuestion: {question}"
|
| 23 |
+
inputs = self.tokenizer(input_text, return_tensors="pt")
|
| 24 |
+
outputs = self.llm.generate(**inputs)
|
| 25 |
+
decoded = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 26 |
+
final = decoded.split("FINAL ANSWER:")[-1].strip()
|
| 27 |
+
return f"FINAL ANSWER: {final}" if final else "FINAL ANSWER: UNKNOWN"
|
| 28 |
|
| 29 |
+
# --- Submission Function ---
|
| 30 |
+
def run_and_submit_all(username):
|
| 31 |
+
space_id = os.getenv("SPACE_ID", "your-username/your-space") # fallback
|
| 32 |
+
if not username.strip():
|
| 33 |
+
return "Username is required for submission.", None
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
+
agent = BasicAgent()
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
+
questions_url = f"{DEFAULT_API_URL}/questions"
|
| 38 |
+
submit_url = f"{DEFAULT_API_URL}/submit"
|
| 39 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
|
|
|
| 40 |
|
| 41 |
try:
|
| 42 |
response = requests.get(questions_url, timeout=15)
|
| 43 |
response.raise_for_status()
|
| 44 |
questions_data = response.json()
|
|
|
|
|
|
|
| 45 |
except Exception as e:
|
| 46 |
+
return f"Failed to fetch questions: {e}", None
|
| 47 |
|
| 48 |
+
answers = []
|
| 49 |
+
log = []
|
| 50 |
|
| 51 |
for item in questions_data:
|
| 52 |
task_id = item.get("task_id")
|
| 53 |
+
question = item.get("question")
|
| 54 |
+
if not task_id or not question:
|
| 55 |
continue
|
| 56 |
try:
|
| 57 |
+
answer = agent(question)
|
| 58 |
+
answers.append({"task_id": task_id, "submitted_answer": answer})
|
| 59 |
+
log.append({"Task ID": task_id, "Question": question, "Submitted Answer": answer})
|
| 60 |
except Exception as e:
|
| 61 |
+
log.append({"Task ID": task_id, "Question": question, "Submitted Answer": f"ERROR: {e}"})
|
| 62 |
|
| 63 |
+
if not answers:
|
| 64 |
+
return "No answers submitted.", pd.DataFrame(log)
|
| 65 |
|
| 66 |
+
payload = {
|
| 67 |
"username": username.strip(),
|
| 68 |
"agent_code": agent_code,
|
| 69 |
+
"answers": answers
|
| 70 |
}
|
| 71 |
|
| 72 |
try:
|
| 73 |
+
response = requests.post(submit_url, json=payload, timeout=30)
|
| 74 |
response.raise_for_status()
|
| 75 |
+
result = response.json()
|
| 76 |
+
status = (
|
| 77 |
f"Submission Successful!\n"
|
| 78 |
+
f"User: {result.get('username')}\n"
|
| 79 |
+
f"Score: {result.get('score', 'N/A')}% "
|
| 80 |
+
f"({result.get('correct_count', '?')}/{result.get('total_attempted', '?')} correct)\n"
|
| 81 |
+
f"Message: {result.get('message', '')}"
|
| 82 |
)
|
| 83 |
+
return status, pd.DataFrame(log)
|
| 84 |
except Exception as e:
|
| 85 |
+
return f"Submission failed: {e}", pd.DataFrame(log)
|
| 86 |
|
| 87 |
# --- Gradio UI ---
|
| 88 |
with gr.Blocks() as demo:
|
| 89 |
+
gr.Markdown("## 🚀 Basic Agent Evaluation & Submission")
|
| 90 |
+
gr.Markdown("Enter your Hugging Face username and press **Run and Submit** to evaluate your agent and submit your results.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
+
username_input = gr.Textbox(label="Hugging Face Username", placeholder="e.g. your-hf-username")
|
| 93 |
+
run_button = gr.Button("Run and Submit")
|
| 94 |
+
status_output = gr.Textbox(label="Submission Status", lines=4, interactive=False)
|
| 95 |
+
results_table = gr.DataFrame(label="Submitted Answers")
|
| 96 |
+
|
| 97 |
+
run_button.click(fn=run_and_submit_all, inputs=[username_input], outputs=[status_output, results_table])
|
| 98 |
|
| 99 |
if __name__ == "__main__":
|
| 100 |
+
demo.launch(debug=True)
|
|
|