ghanemfaouri commited on
Commit
db85f61
·
verified ·
1 Parent(s): c45a8b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -100
app.py CHANGED
@@ -1,11 +1,9 @@
1
  import os
2
  import gradio as gr
3
  import requests
4
- import inspect
5
  import pandas as pd
6
- from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
7
 
8
- # (Keep Constants and BasicAgent class as is)
9
  # --- Constants ---
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
 
@@ -13,37 +11,43 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
  class BasicAgent:
14
  def __init__(self):
15
  print("BasicAgent initialized.")
16
- self.agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=HfApiModel())
17
-
18
- SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and
19
- finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER].
20
- YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated
21
- list of numbers and/or strings.
22
- If you are asked for a number, don't use comma to write your number neither use units such as $ or
23
- percent sign unless specified otherwise.
24
- If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the
25
- digits in plain text unless specified otherwise.
26
- If you are asked for a comma separated list, apply the above rules depending of whether the element
27
- to be put in the list is a number or a string.
28
- """
29
- self.agent.prompt_templates["system_prompt"] = self.agent.prompt_templates["system_prompt"] + SYSTEM_PROMPT
30
-
 
 
 
 
 
 
 
 
 
 
 
31
  def __call__(self, question: str) -> str:
32
  print(f"Agent received question (first 50 chars): {question[:50]}...")
33
  final_answer = self.agent.run(question)
34
  print(f"Agent returning final answer: {final_answer}")
35
  return final_answer
36
 
37
- def run_and_submit_all( profile: gr.OAuthProfile | None):
38
- """
39
- Fetches all questions, runs the BasicAgent on them, submits all answers,
40
- and displays the results.
41
- """
42
- # --- Determine HF Space Runtime URL and Repo URL ---
43
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
44
 
45
  if profile:
46
- username= f"{profile.username}"
47
  print(f"User logged in: {username}")
48
  else:
49
  print("User not logged in.")
@@ -53,41 +57,30 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
53
  questions_url = f"{api_url}/questions"
54
  submit_url = f"{api_url}/submit"
55
 
56
- # 1. Instantiate Agent ( modify this part to create your agent)
57
  try:
58
  agent = BasicAgent()
59
  except Exception as e:
60
  print(f"Error instantiating agent: {e}")
61
  return f"Error initializing agent: {e}", None
62
- # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
63
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
64
  print(agent_code)
65
 
66
- # 2. Fetch Questions
67
  print(f"Fetching questions from: {questions_url}")
68
  try:
69
  response = requests.get(questions_url, timeout=15)
70
  response.raise_for_status()
71
  questions_data = response.json()
72
  if not questions_data:
73
- print("Fetched questions list is empty.")
74
- return "Fetched questions list is empty or invalid format.", None
75
  print(f"Fetched {len(questions_data)} questions.")
76
- except requests.exceptions.RequestException as e:
77
  print(f"Error fetching questions: {e}")
78
  return f"Error fetching questions: {e}", None
79
- except requests.exceptions.JSONDecodeError as e:
80
- print(f"Error decoding JSON response from questions endpoint: {e}")
81
- print(f"Response text: {response.text[:500]}")
82
- return f"Error decoding server response for questions: {e}", None
83
- except Exception as e:
84
- print(f"An unexpected error occurred fetching questions: {e}")
85
- return f"An unexpected error occurred fetching questions: {e}", None
86
 
87
- # 3. Run your Agent
88
  results_log = []
89
  answers_payload = []
90
- print(f"Running agent on {len(questions_data)} questions...")
91
  for item in questions_data:
92
  task_id = item.get("task_id")
93
  question_text = item.get("question")
@@ -99,19 +92,14 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
99
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
100
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
101
  except Exception as e:
102
- print(f"Error running agent on task {task_id}: {e}")
103
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
104
 
105
  if not answers_payload:
106
  print("Agent did not produce any answers to submit.")
107
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
108
 
109
- # 4. Prepare Submission
110
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
111
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
112
- print(status_update)
113
-
114
- # 5. Submit
115
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
116
  try:
117
  response = requests.post(submit_url, json=submission_data, timeout=60)
@@ -124,52 +112,24 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
124
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
125
  f"Message: {result_data.get('message', 'No message received.')}"
126
  )
127
- print("Submission successful.")
128
  results_df = pd.DataFrame(results_log)
129
  return final_status, results_df
130
- except requests.exceptions.HTTPError as e:
131
- error_detail = f"Server responded with status {e.response.status_code}."
132
- try:
133
- error_json = e.response.json()
134
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
135
- except requests.exceptions.JSONDecodeError:
136
- error_detail += f" Response: {e.response.text[:500]}"
137
- status_message = f"Submission Failed: {error_detail}"
138
- print(status_message)
139
- results_df = pd.DataFrame(results_log)
140
- return status_message, results_df
141
- except requests.exceptions.Timeout:
142
- status_message = "Submission Failed: The request timed out."
143
- print(status_message)
144
- results_df = pd.DataFrame(results_log)
145
- return status_message, results_df
146
- except requests.exceptions.RequestException as e:
147
- status_message = f"Submission Failed: Network error - {e}"
148
- print(status_message)
149
- results_df = pd.DataFrame(results_log)
150
- return status_message, results_df
151
  except Exception as e:
152
- status_message = f"An unexpected error occurred during submission: {e}"
153
- print(status_message)
154
  results_df = pd.DataFrame(results_log)
155
- return status_message, results_df
156
 
157
-
158
- # --- Build Gradio Interface using Blocks ---
159
  with gr.Blocks() as demo:
160
  gr.Markdown("# Basic Agent Evaluation Runner")
161
  gr.Markdown(
162
- "Please clone this space, then modify the code to define your agent's logic within the BasicAgent class. "
163
- "Log in to your Hugging Face account using the button below. This uses your HF username for submission. "
164
  "Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score."
165
  )
166
 
167
  gr.LoginButton()
168
-
169
  run_button = gr.Button("Run Evaluation & Submit All Answers")
170
-
171
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
172
- # Removed max_rows=10 from DataFrame constructor
173
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
174
 
175
  run_button.click(
@@ -178,25 +138,5 @@ with gr.Blocks() as demo:
178
  )
179
 
180
  if __name__ == "__main__":
181
- print("\n" + "-"*30 + " App Starting " + "-"*30)
182
- # Check for SPACE_HOST and SPACE_ID at startup for information
183
- space_host_startup = os.getenv("SPACE_HOST")
184
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
185
-
186
- if space_host_startup:
187
- print(f"✅ SPACE_HOST found: {space_host_startup}")
188
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
189
- else:
190
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
191
-
192
- if space_id_startup: # Print repo URLs if SPACE_ID is found
193
- print(f"✅ SPACE_ID found: {space_id_startup}")
194
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
195
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
196
- else:
197
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
198
-
199
- print("-"*(60 + len(" App Starting ")) + "\n")
200
-
201
  print("Launching Gradio Interface for Basic Agent Evaluation...")
202
  demo.launch(debug=True, share=False)
 
1
  import os
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
5
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel
6
 
 
7
  # --- Constants ---
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
 
11
  class BasicAgent:
12
  def __init__(self):
13
  print("BasicAgent initialized.")
14
+ self.agent = CodeAgent(
15
+ tools=[DuckDuckGoSearchTool()],
16
+ model=InferenceClientModel(model_id="mistralai/Mixtral-8x7B-Instruct-v0.1")
17
+ )
18
+
19
+ SYSTEM_PROMPT = """
20
+ You are a general AI assistant. I will ask you a question. Think step by step before answering.
21
+ Clearly explain your reasoning, and then finish your answer with:
22
+ FINAL ANSWER: [YOUR FINAL ANSWER].
23
+
24
+ Your final answer should be:
25
+ - A number without commas or symbols (e.g. "3000")
26
+ - OR a single string (e.g. "New York City") without abbreviations or articles
27
+ - OR a comma-separated list of such items
28
+
29
+ Examples:
30
+ Q: What is 12 multiplied by 25?
31
+ A: First, 12 * 25 = 300. FINAL ANSWER: 300
32
+
33
+ Q: Name the capital cities of France and Germany.
34
+ A: The capital of France is Paris. The capital of Germany is Berlin. FINAL ANSWER: Paris,Berlin
35
+
36
+ Think step by step.
37
+ """
38
+ self.agent.prompt_templates["system_prompt"] += SYSTEM_PROMPT
39
+
40
  def __call__(self, question: str) -> str:
41
  print(f"Agent received question (first 50 chars): {question[:50]}...")
42
  final_answer = self.agent.run(question)
43
  print(f"Agent returning final answer: {final_answer}")
44
  return final_answer
45
 
46
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
47
+ space_id = os.getenv("SPACE_ID")
 
 
 
 
 
48
 
49
  if profile:
50
+ username = f"{profile.username}"
51
  print(f"User logged in: {username}")
52
  else:
53
  print("User not logged in.")
 
57
  questions_url = f"{api_url}/questions"
58
  submit_url = f"{api_url}/submit"
59
 
 
60
  try:
61
  agent = BasicAgent()
62
  except Exception as e:
63
  print(f"Error instantiating agent: {e}")
64
  return f"Error initializing agent: {e}", None
65
+
66
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
67
  print(agent_code)
68
 
 
69
  print(f"Fetching questions from: {questions_url}")
70
  try:
71
  response = requests.get(questions_url, timeout=15)
72
  response.raise_for_status()
73
  questions_data = response.json()
74
  if not questions_data:
75
+ print("Fetched questions list is empty.")
76
+ return "Fetched questions list is empty or invalid format.", None
77
  print(f"Fetched {len(questions_data)} questions.")
78
+ except Exception as e:
79
  print(f"Error fetching questions: {e}")
80
  return f"Error fetching questions: {e}", None
 
 
 
 
 
 
 
81
 
 
82
  results_log = []
83
  answers_payload = []
 
84
  for item in questions_data:
85
  task_id = item.get("task_id")
86
  question_text = item.get("question")
 
92
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
93
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
94
  except Exception as e:
95
+ print(f"Error running agent on task {task_id}: {e}")
96
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
97
 
98
  if not answers_payload:
99
  print("Agent did not produce any answers to submit.")
100
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
101
 
 
102
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
 
 
 
 
103
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
104
  try:
105
  response = requests.post(submit_url, json=submission_data, timeout=60)
 
112
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
113
  f"Message: {result_data.get('message', 'No message received.')}"
114
  )
 
115
  results_df = pd.DataFrame(results_log)
116
  return final_status, results_df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  except Exception as e:
118
+ print(f"Submission failed: {e}")
 
119
  results_df = pd.DataFrame(results_log)
120
+ return f"Submission failed: {e}", results_df
121
 
122
+ # --- Build Gradio Interface ---
 
123
  with gr.Blocks() as demo:
124
  gr.Markdown("# Basic Agent Evaluation Runner")
125
  gr.Markdown(
126
+ "Log in to your Hugging Face account using the button below. "
 
127
  "Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score."
128
  )
129
 
130
  gr.LoginButton()
 
131
  run_button = gr.Button("Run Evaluation & Submit All Answers")
 
132
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
133
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
134
 
135
  run_button.click(
 
138
  )
139
 
140
  if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  print("Launching Gradio Interface for Basic Agent Evaluation...")
142
  demo.launch(debug=True, share=False)