dlaima commited on
Commit
5907175
·
verified ·
1 Parent(s): fae6cac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -53
app.py CHANGED
@@ -2,111 +2,170 @@ import os
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
 
5
  from smolagents import CodeAgent, DuckDuckGoSearchTool
6
  from smolagents.models import OpenAIServerModel
7
 
8
- # Constants
 
 
 
 
 
 
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
- # === Define the Smol Agent ===
12
  class MyAgent:
13
  def __init__(self):
14
- self.model = OpenAIServerModel(model_id="gpt-4") # or "gpt-3.5-turbo"
 
 
 
 
15
  self.agent = CodeAgent(
16
  tools=[DuckDuckGoSearchTool()],
17
- model=self.model,
18
- system_message="""You are a general AI assistant. I will ask you a question.
19
- Report your thoughts, and finish your answer with the following template:
20
- FINAL ANSWER: [YOUR FINAL ANSWER].
21
- YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list
22
- 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."""
23
  )
24
 
25
  def __call__(self, question: str) -> str:
 
26
  return self.agent.run(question)
27
 
28
- # === Submission Logic ===
29
  def run_and_submit_all(profile: gr.OAuthProfile | None):
 
 
 
30
  space_id = os.getenv("SPACE_ID")
 
31
  if profile:
32
  username = profile.username
33
  print(f"User logged in: {username}")
34
  else:
 
35
  return "Please Login to Hugging Face with the button.", None
36
 
37
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
38
- questions_url = f"{DEFAULT_API_URL}/questions"
39
- submit_url = f"{DEFAULT_API_URL}/submit"
40
 
41
  try:
42
  agent = MyAgent()
43
  except Exception as e:
 
44
  return f"Error initializing agent: {e}", None
45
 
46
- # Fetch Questions
 
 
 
47
  try:
48
- res = requests.get(questions_url, timeout=15)
49
- res.raise_for_status()
50
- questions_data = res.json()
 
 
 
 
51
  except Exception as e:
52
- return f"Failed to fetch questions: {e}", None
 
53
 
54
  results_log = []
55
  answers_payload = []
56
-
57
  for item in questions_data:
58
  task_id = item.get("task_id")
59
- question = item.get("question")
60
- if not task_id or question is None:
 
61
  continue
62
  try:
63
- answer = agent(question)
64
- results_log.append({"Task ID": task_id, "Question": question, "Submitted Answer": answer})
65
- answers_payload.append({"task_id": task_id, "submitted_answer": answer})
66
  except Exception as e:
67
- results_log.append({"Task ID": task_id, "Question": question, "Submitted Answer": f"ERROR: {e}"})
 
68
 
69
  if not answers_payload:
70
- return "No answers generated.", pd.DataFrame(results_log)
71
-
72
- submission_data = {
73
- "username": username,
74
- "agent_code": agent_code,
75
- "answers": answers_payload
76
- }
77
 
 
 
78
  try:
79
- res = requests.post(submit_url, json=submission_data, timeout=60)
80
- res.raise_for_status()
81
- result_data = res.json()
82
- summary = (
83
  f"Submission Successful!\n"
84
  f"User: {result_data.get('username')}\n"
85
- f"Score: {result_data.get('score', '?')}% "
86
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')})\n"
87
- f"Message: {result_data.get('message', '')}"
88
  )
89
- return summary, pd.DataFrame(results_log)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  except Exception as e:
91
- return f"Submission failed: {e}", pd.DataFrame(results_log)
 
 
92
 
93
- # === Gradio UI ===
94
  with gr.Blocks() as demo:
95
- gr.Markdown("# Agent Evaluation Runner (SmolAgents)")
96
- gr.Markdown("""
97
- **Instructions:**
98
- 1. Clone this space and customize your agent.
99
- 2. Log in with Hugging Face.
100
- 3. Click 'Run Evaluation' to answer and submit.
101
- """)
 
 
 
 
102
 
103
  gr.LoginButton()
104
  run_button = gr.Button("Run Evaluation & Submit All Answers")
105
- status_output = gr.Textbox(label="Status", lines=4, interactive=False)
106
- results_table = gr.DataFrame(label="Results", wrap=True)
 
107
 
108
  run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
109
 
110
  if __name__ == "__main__":
111
- print("Launching...")
112
- demo.launch(debug=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
5
+
6
  from smolagents import CodeAgent, DuckDuckGoSearchTool
7
  from smolagents.models import OpenAIServerModel
8
 
9
+ # System prompt as per your instructions
10
+ SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question.
11
+ Report your thoughts, and finish your answer with the following template:
12
+ FINAL ANSWER: [YOUR FINAL ANSWER].
13
+ YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list
14
+ 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."""
15
+
16
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
17
 
 
18
  class MyAgent:
19
  def __init__(self):
20
+ # Initialize model with system prompt
21
+ self.model = OpenAIServerModel(
22
+ model_id="gpt-4",
23
+ system_message=SYSTEM_PROMPT
24
+ )
25
  self.agent = CodeAgent(
26
  tools=[DuckDuckGoSearchTool()],
27
+ model=self.model
 
 
 
 
 
28
  )
29
 
30
  def __call__(self, question: str) -> str:
31
+ # Run agent on the question
32
  return self.agent.run(question)
33
 
 
34
  def run_and_submit_all(profile: gr.OAuthProfile | None):
35
+ """
36
+ Fetches questions, runs the agent, submits answers, returns status and results table.
37
+ """
38
  space_id = os.getenv("SPACE_ID")
39
+
40
  if profile:
41
  username = profile.username
42
  print(f"User logged in: {username}")
43
  else:
44
+ print("User not logged in.")
45
  return "Please Login to Hugging Face with the button.", None
46
 
47
+ api_url = DEFAULT_API_URL
48
+ questions_url = f"{api_url}/questions"
49
+ submit_url = f"{api_url}/submit"
50
 
51
  try:
52
  agent = MyAgent()
53
  except Exception as e:
54
+ print(f"Error initializing agent: {e}")
55
  return f"Error initializing agent: {e}", None
56
 
57
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
58
+ print(f"Agent code URL: {agent_code}")
59
+
60
+ print(f"Fetching questions from: {questions_url}")
61
  try:
62
+ response = requests.get(questions_url, timeout=15)
63
+ response.raise_for_status()
64
+ questions_data = response.json()
65
+ if not questions_data:
66
+ print("Fetched questions list is empty.")
67
+ return "Fetched questions list is empty or invalid format.", None
68
+ print(f"Fetched {len(questions_data)} questions.")
69
  except Exception as e:
70
+ print(f"Error fetching questions: {e}")
71
+ return f"Error fetching questions: {e}", None
72
 
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 invalid item: {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
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
95
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
96
  try:
97
+ response = requests.post(submit_url, json=submission_data, timeout=60)
98
+ response.raise_for_status()
99
+ result_data = response.json()
100
+ final_status = (
101
  f"Submission Successful!\n"
102
  f"User: {result_data.get('username')}\n"
103
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
104
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
105
+ f"Message: {result_data.get('message', 'No message received.')}"
106
  )
107
+ print("Submission successful.")
108
+ results_df = pd.DataFrame(results_log)
109
+ return final_status, results_df
110
+ except requests.exceptions.HTTPError as e:
111
+ error_detail = f"Server responded with status {e.response.status_code}."
112
+ try:
113
+ error_json = e.response.json()
114
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
115
+ except Exception:
116
+ error_detail += f" Response: {e.response.text[:500]}"
117
+ status_message = f"Submission Failed: {error_detail}"
118
+ print(status_message)
119
+ return status_message, pd.DataFrame(results_log)
120
+ except requests.exceptions.Timeout:
121
+ status_message = "Submission Failed: The request timed out."
122
+ print(status_message)
123
+ return status_message, pd.DataFrame(results_log)
124
  except Exception as e:
125
+ status_message = f"An unexpected error occurred during submission: {e}"
126
+ print(status_message)
127
+ return status_message, pd.DataFrame(results_log)
128
 
 
129
  with gr.Blocks() as demo:
130
+ gr.Markdown("# Basic Agent Evaluation Runner")
131
+ gr.Markdown(
132
+ """
133
+ **Instructions:**
134
+ 1. Clone this space, modify code to define your agent's logic, tools, and packages.
135
+ 2. Log in to your Hugging Face account using the button below.
136
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see your score.
137
+
138
+ **Note:** Submitting can take some time.
139
+ """
140
+ )
141
 
142
  gr.LoginButton()
143
  run_button = gr.Button("Run Evaluation & Submit All Answers")
144
+
145
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
146
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
147
 
148
  run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
149
 
150
  if __name__ == "__main__":
151
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
152
+ space_host = os.getenv("SPACE_HOST")
153
+ space_id = os.getenv("SPACE_ID")
154
+
155
+ if space_host:
156
+ print(f"✅ SPACE_HOST found: {space_host}")
157
+ print(f" Runtime URL should be: https://{space_host}.hf.space")
158
+ else:
159
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
160
+
161
+ if space_id:
162
+ print(f"✅ SPACE_ID found: {space_id}")
163
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id}")
164
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id}/tree/main")
165
+ else:
166
+ print("ℹ️ SPACE_ID environment variable not found (running locally?).")
167
+
168
+ print("-"*(60 + len(" App Starting ")) + "\n")
169
+
170
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
171
+ demo.launch(debug=True, share=False)