Toumaima commited on
Commit
7f9795b
·
verified ·
1 Parent(s): 2e72f39

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -80
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
- # --- Advanced Agent Logic ---
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
- def query_groq(self, question: str) -> str:
25
- # Placeholder for Groq query handling
26
- return f"FINAL ANSWER: {question}"
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
- # Decide based on the question type, here we use placeholder logic
34
- if "use tools" in question.lower():
35
- return self.query_tools(question)
36
- return self.query_groq(question)
 
 
37
 
38
- # --- Evaluation and Submission Logic ---
39
- def run_and_submit_all(profile):
40
- space_id = os.getenv("SPACE_ID")
41
- if profile:
42
- username = profile
43
- print(f"User logged in: {username}")
44
- else:
45
- return "Please provide a username.", None
46
 
47
- api_url = DEFAULT_API_URL
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
- try:
53
- agent = BasicAgent()
54
- except Exception as e:
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"Error fetching questions: {e}", None
65
 
66
- results_log = []
67
- answers_payload = []
68
 
69
  for item in questions_data:
70
  task_id = item.get("task_id")
71
- question_text = item.get("question")
72
- if not task_id or question_text is None:
73
  continue
74
  try:
75
- submitted_answer = agent(question_text)
76
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
77
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
78
  except Exception as e:
79
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
80
 
81
- if not answers_payload:
82
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
83
 
84
- submission_data = {
85
  "username": username.strip(),
86
  "agent_code": agent_code,
87
- "answers": answers_payload
88
  }
89
 
90
  try:
91
- response = requests.post(submit_url, json=submission_data, timeout=60)
92
  response.raise_for_status()
93
- result_data = response.json()
94
- final_status = (
95
  f"Submission Successful!\n"
96
- f"User: {result_data.get('username')}\n"
97
- f"Overall Score: {result_data.get('score', 'N/A')}% "
98
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
99
- f"Message: {result_data.get('message', 'No message received.')}"
100
  )
101
- return final_status, pd.DataFrame(results_log)
102
  except Exception as e:
103
- return f"Submission Failed: {e}", pd.DataFrame(results_log)
104
 
105
  # --- Gradio UI ---
106
  with gr.Blocks() as demo:
107
- gr.Markdown("# Basic Agent Evaluation Runner")
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
- run_button.click(
122
- fn=run_and_submit_all,
123
- inputs=[profile_input],
124
- outputs=[status_output, results_table]
125
- )
 
126
 
127
  if __name__ == "__main__":
128
- print("Launching Gradio Interface...")
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)