Delete app.py
Browse files
app.py
DELETED
|
@@ -1,161 +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 |
-
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 8 |
-
|
| 9 |
-
class HfApiModel:
|
| 10 |
-
def __init__(self, model_name="tiiuae/falcon-7b-instruct", api_key=None):
|
| 11 |
-
self.model_name = model_name
|
| 12 |
-
self.api_key = api_key or os.getenv("HF_TOKEN")
|
| 13 |
-
if not self.api_key:
|
| 14 |
-
raise ValueError("HF_TOKEN environment variable is missing.")
|
| 15 |
-
|
| 16 |
-
def __call__(self, prompt):
|
| 17 |
-
# Convert ChatMessage or list of ChatMessages to plain string
|
| 18 |
-
if hasattr(prompt, "content"):
|
| 19 |
-
prompt = prompt.content
|
| 20 |
-
elif isinstance(prompt, list):
|
| 21 |
-
prompt = " ".join(
|
| 22 |
-
m.content if hasattr(m, "content") else str(m) for m in prompt
|
| 23 |
-
)
|
| 24 |
-
else:
|
| 25 |
-
prompt = str(prompt)
|
| 26 |
-
|
| 27 |
-
url = f"https://api-inference.huggingface.co/models/{self.model_name}"
|
| 28 |
-
headers = {"Authorization": f"Bearer {self.api_key}"}
|
| 29 |
-
payload = {
|
| 30 |
-
"inputs": prompt,
|
| 31 |
-
"options": {"wait_for_model": True}
|
| 32 |
-
}
|
| 33 |
-
|
| 34 |
-
response = requests.post(url, headers=headers, json=payload, timeout=60)
|
| 35 |
-
response.raise_for_status()
|
| 36 |
-
output = response.json()
|
| 37 |
-
|
| 38 |
-
try:
|
| 39 |
-
return output[0]["generated_text"]
|
| 40 |
-
except Exception:
|
| 41 |
-
return f"ERROR: {output}"
|
| 42 |
-
|
| 43 |
-
def generate(self, prompt, **kwargs):
|
| 44 |
-
return self.__call__(prompt)
|
| 45 |
-
|
| 46 |
-
class BasicAgent:
|
| 47 |
-
def __init__(self):
|
| 48 |
-
print("✅ BasicAgent initialized.")
|
| 49 |
-
self.agent = CodeAgent(
|
| 50 |
-
tools=[DuckDuckGoSearchTool()],
|
| 51 |
-
model=HfApiModel(model_name="tiiuae/falcon-7b-instruct")
|
| 52 |
-
)
|
| 53 |
-
|
| 54 |
-
SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and
|
| 55 |
-
finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER].
|
| 56 |
-
YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated
|
| 57 |
-
list of numbers and/or strings.
|
| 58 |
-
If you are asked for a number, don't use comma to write your number neither use units such as $ or
|
| 59 |
-
percent sign unless specified otherwise.
|
| 60 |
-
If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the
|
| 61 |
-
digits in plain text unless specified otherwise.
|
| 62 |
-
If you are asked for a comma separated list, apply the above rules depending of whether the element
|
| 63 |
-
to be put in the list is a number or a string.
|
| 64 |
-
"""
|
| 65 |
-
self.agent.prompt_templates["system_prompt"] += SYSTEM_PROMPT
|
| 66 |
-
|
| 67 |
-
def __call__(self, question: str) -> str:
|
| 68 |
-
print(f"📥 Agent received question: {question[:60]}...")
|
| 69 |
-
final_answer = self.agent.run(question)
|
| 70 |
-
print(f"📤 Agent returning answer: {final_answer}")
|
| 71 |
-
return final_answer
|
| 72 |
-
|
| 73 |
-
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 74 |
-
space_id = os.getenv("SPACE_ID")
|
| 75 |
-
|
| 76 |
-
if profile:
|
| 77 |
-
username = profile.username
|
| 78 |
-
print(f"🔐 Logged in as: {username}")
|
| 79 |
-
else:
|
| 80 |
-
return "⚠️ Please login with Hugging Face to continue.", None
|
| 81 |
-
|
| 82 |
-
questions_url = f"{DEFAULT_API_URL}/questions"
|
| 83 |
-
submit_url = f"{DEFAULT_API_URL}/submit"
|
| 84 |
-
|
| 85 |
-
try:
|
| 86 |
-
agent = BasicAgent()
|
| 87 |
-
except Exception as e:
|
| 88 |
-
return f"❌ Agent initialization failed: {e}", None
|
| 89 |
-
|
| 90 |
-
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Unknown"
|
| 91 |
-
|
| 92 |
-
try:
|
| 93 |
-
response = requests.get(questions_url, timeout=15)
|
| 94 |
-
response.raise_for_status()
|
| 95 |
-
questions_data = response.json()
|
| 96 |
-
if not questions_data:
|
| 97 |
-
return "❌ No questions received from the server.", None
|
| 98 |
-
except Exception as e:
|
| 99 |
-
return f"❌ Failed to fetch questions: {e}", None
|
| 100 |
-
|
| 101 |
-
answers_payload = []
|
| 102 |
-
results_log = []
|
| 103 |
-
|
| 104 |
-
for item in questions_data:
|
| 105 |
-
task_id = item.get("task_id")
|
| 106 |
-
question_text = item.get("question")
|
| 107 |
-
if not task_id or question_text is None:
|
| 108 |
-
continue
|
| 109 |
-
try:
|
| 110 |
-
submitted_answer = agent(question_text)
|
| 111 |
-
except Exception as e:
|
| 112 |
-
submitted_answer = f"AGENT ERROR: {e}"
|
| 113 |
-
answers_payload.append({
|
| 114 |
-
"task_id": task_id,
|
| 115 |
-
"submitted_answer": submitted_answer
|
| 116 |
-
})
|
| 117 |
-
results_log.append({
|
| 118 |
-
"Task ID": task_id,
|
| 119 |
-
"Question": question_text,
|
| 120 |
-
"Submitted Answer": submitted_answer
|
| 121 |
-
})
|
| 122 |
-
|
| 123 |
-
if not answers_payload:
|
| 124 |
-
return "⚠️ Agent failed to generate any answers.", pd.DataFrame(results_log)
|
| 125 |
-
|
| 126 |
-
submission_data = {
|
| 127 |
-
"username": username.strip(),
|
| 128 |
-
"agent_code": agent_code,
|
| 129 |
-
"answers": answers_payload
|
| 130 |
-
}
|
| 131 |
-
|
| 132 |
-
try:
|
| 133 |
-
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 134 |
-
response.raise_for_status()
|
| 135 |
-
result_data = response.json()
|
| 136 |
-
status = (
|
| 137 |
-
f"✅ Submission Successful!\n"
|
| 138 |
-
f"User: {result_data.get('username')}\n"
|
| 139 |
-
f"Score: {result_data.get('score', '?')}% "
|
| 140 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')})\n"
|
| 141 |
-
f"Message: {result_data.get('message', 'No message.')}"
|
| 142 |
-
)
|
| 143 |
-
return status, pd.DataFrame(results_log)
|
| 144 |
-
except Exception as e:
|
| 145 |
-
return f"❌ Submission failed: {e}", pd.DataFrame(results_log)
|
| 146 |
-
|
| 147 |
-
# Gradio UI
|
| 148 |
-
with gr.Blocks() as demo:
|
| 149 |
-
gr.Markdown("# 🤖 Basic Agent Evaluation Runner")
|
| 150 |
-
gr.Markdown("Clone this space, log in, and run your agent on the questions. Modify `BasicAgent` logic if needed.")
|
| 151 |
-
|
| 152 |
-
gr.LoginButton()
|
| 153 |
-
run_button = gr.Button("▶️ Run Evaluation & Submit All Answers")
|
| 154 |
-
status_output = gr.Textbox(label="📝 Run Status", lines=5, interactive=False)
|
| 155 |
-
results_table = gr.DataFrame(label="📋 Results", wrap=True)
|
| 156 |
-
|
| 157 |
-
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
| 158 |
-
|
| 159 |
-
if __name__ == "__main__":
|
| 160 |
-
print("🚀 Launching Gradio app...")
|
| 161 |
-
demo.launch(debug=True, share=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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