supratipb commited on
Commit
1f8ce50
·
verified ·
1 Parent(s): 14535b3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +211 -211
app.py CHANGED
@@ -1,212 +1,212 @@
1
- import os
2
- import gradio as gr
3
- import requests
4
- import inspect
5
- import pandas as pd
6
-
7
- from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
8
- from smolagents import OpenAIServerModel, DuckDuckGoSearchTool, CodeAgent, WikipediaSearchTool, InferenceClientModel
9
- import os
10
-
11
- api_key = os.getenv("HF_TOKEN")
12
-
13
-
14
-
15
- # (Keep Constants as is)
16
- # --- Constants ---
17
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
18
-
19
- # --- Basic Agent Definition ---
20
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
21
- class BasicAgent:
22
- def __init__(self):
23
- openAI_model = OpenAIServerModel(model_id="gpt-4.1-mini", api_key="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")
24
- self.agent = CodeAgent(
25
- model = openAI_model,
26
- tools = [DuckDuckGoSearchTool(), WikipediaSearchTool()],
27
- add_base_tools = True,
28
- )
29
- print("BasicAgent initialized.")
30
- def __call__(self, question: str) -> str:
31
- print(f"Agent received question (first 50 chars): {question[:50]}...")
32
- # fixed_answer = "This is a default answer."
33
- fixed_answer = self.agent.run(question)
34
- print(f"Agent returning fixed answer: {fixed_answer}")
35
- return fixed_answer
36
-
37
-
38
- def run_and_submit_all( profile: gr.OAuthProfile | None):
39
- """
40
- Fetches all questions, runs the BasicAgent on them, submits all answers,
41
- and displays the results.
42
- """
43
- # --- Determine HF Space Runtime URL and Repo URL ---
44
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
45
-
46
- if profile:
47
- username= f"{profile.username}"
48
- print(f"User logged in: {username}")
49
- else:
50
- print("User not logged in.")
51
- return "Please Login to Hugging Face with the button.", None
52
-
53
- api_url = DEFAULT_API_URL
54
- questions_url = f"{api_url}/questions"
55
- submit_url = f"{api_url}/submit"
56
-
57
- # 1. Instantiate Agent ( modify this part to create your agent)
58
- try:
59
- agent = BasicAgent()
60
- except Exception as e:
61
- print(f"Error instantiating agent: {e}")
62
- return f"Error initializing agent: {e}", None
63
- # 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)
64
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
65
- print(agent_code)
66
-
67
- # 2. Fetch Questions
68
- print(f"Fetching questions from: {questions_url}")
69
- try:
70
- response = requests.get(questions_url, timeout=15)
71
- response.raise_for_status()
72
- questions_data = response.json()
73
- if not questions_data:
74
- print("Fetched questions list is empty.")
75
- return "Fetched questions list is empty or invalid format.", None
76
- print(f"Fetched {len(questions_data)} questions.")
77
- except requests.exceptions.RequestException as e:
78
- print(f"Error fetching questions: {e}")
79
- return f"Error fetching questions: {e}", None
80
- except requests.exceptions.JSONDecodeError as e:
81
- print(f"Error decoding JSON response from questions endpoint: {e}")
82
- print(f"Response text: {response.text[:500]}")
83
- return f"Error decoding server response for questions: {e}", None
84
- except Exception as e:
85
- print(f"An unexpected error occurred fetching questions: {e}")
86
- return f"An unexpected error occurred fetching questions: {e}", None
87
-
88
- # 3. Run your Agent
89
- results_log = []
90
- answers_payload = []
91
- print(f"Running agent on {len(questions_data)} questions...")
92
- for item in questions_data:
93
- task_id = item.get("task_id")
94
- question_text = item.get("question")
95
- if not task_id or question_text is None:
96
- print(f"Skipping item with missing task_id or question: {item}")
97
- continue
98
- try:
99
- submitted_answer = agent(question_text)
100
- if not isinstance(submitted_answer, str):
101
- submitted_answer = str(submitted_answer)
102
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
103
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
104
- except Exception as e:
105
- print(f"Error running agent on task {task_id}: {e}")
106
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
107
-
108
- if not answers_payload:
109
- print("Agent did not produce any answers to submit.")
110
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
111
-
112
- # 4. Prepare Submission
113
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
114
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
115
- print(status_update)
116
-
117
- # 5. Submit
118
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
119
- try:
120
- response = requests.post(submit_url, json=submission_data, timeout=60)
121
- response.raise_for_status()
122
- result_data = response.json()
123
- final_status = (
124
- f"Submission Successful!\n"
125
- f"User: {result_data.get('username')}\n"
126
- f"Overall Score: {result_data.get('score', 'N/A')}% "
127
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
128
- f"Message: {result_data.get('message', 'No message received.')}"
129
- )
130
- print("Submission successful.")
131
- results_df = pd.DataFrame(results_log)
132
- return final_status, results_df
133
- except requests.exceptions.HTTPError as e:
134
- error_detail = f"Server responded with status {e.response.status_code}."
135
- try:
136
- error_json = e.response.json()
137
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
138
- except requests.exceptions.JSONDecodeError:
139
- error_detail += f" Response: {e.response.text[:500]}"
140
- status_message = f"Submission Failed: {error_detail}"
141
- print(status_message)
142
- results_df = pd.DataFrame(results_log)
143
- return status_message, results_df
144
- except requests.exceptions.Timeout:
145
- status_message = "Submission Failed: The request timed out."
146
- print(status_message)
147
- results_df = pd.DataFrame(results_log)
148
- return status_message, results_df
149
- except requests.exceptions.RequestException as e:
150
- status_message = f"Submission Failed: Network error - {e}"
151
- print(status_message)
152
- results_df = pd.DataFrame(results_log)
153
- return status_message, results_df
154
- except Exception as e:
155
- status_message = f"An unexpected error occurred during submission: {e}"
156
- print(status_message)
157
- results_df = pd.DataFrame(results_log)
158
- return status_message, results_df
159
-
160
-
161
- # --- Build Gradio Interface using Blocks ---
162
- with gr.Blocks() as demo:
163
- gr.Markdown("# Basic Agent Evaluation Runner")
164
- gr.Markdown(
165
- """
166
- **Instructions:**
167
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
168
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
169
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
170
- ---
171
- **Disclaimers:**
172
- Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
173
- This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
174
- """
175
- )
176
-
177
- gr.LoginButton()
178
-
179
- run_button = gr.Button("Run Evaluation & Submit All Answers")
180
-
181
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
182
- # Removed max_rows=10 from DataFrame constructor
183
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
184
-
185
- run_button.click(
186
- fn=run_and_submit_all,
187
- outputs=[status_output, results_table]
188
- )
189
-
190
- if __name__ == "__main__":
191
- print("\n" + "-"*30 + " App Starting " + "-"*30)
192
- # Check for SPACE_HOST and SPACE_ID at startup for information
193
- space_host_startup = os.getenv("SPACE_HOST")
194
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
195
-
196
- if space_host_startup:
197
- print(f"✅ SPACE_HOST found: {space_host_startup}")
198
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
199
- else:
200
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
201
-
202
- if space_id_startup: # Print repo URLs if SPACE_ID is found
203
- print(f"✅ SPACE_ID found: {space_id_startup}")
204
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
205
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
206
- else:
207
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
208
-
209
- print("-"*(60 + len(" App Starting ")) + "\n")
210
-
211
- print("Launching Gradio Interface for Basic Agent Evaluation...")
212
  demo.launch(debug=True, share=False)
 
1
+ import os
2
+ import gradio as gr
3
+ import requests
4
+ import inspect
5
+ import pandas as pd
6
+
7
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
8
+ from smolagents import OpenAIServerModel, DuckDuckGoSearchTool, CodeAgent, WikipediaSearchTool, InferenceClientModel
9
+ import os
10
+
11
+ api_key = os.getenv("HF_TOKEN")
12
+
13
+
14
+
15
+ # (Keep Constants as is)
16
+ # --- Constants ---
17
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
18
+
19
+ # --- Basic Agent Definition ---
20
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
21
+ class BasicAgent:
22
+ def __init__(self):
23
+ openAI_model = OpenAIServerModel(model_id="gpt-4.1-mini", api_key="sk-proj--7IsHGYQG_dTB1Q9_wA")
24
+ self.agent = CodeAgent(
25
+ model = openAI_model,
26
+ tools = [DuckDuckGoSearchTool(), WikipediaSearchTool()],
27
+ add_base_tools = True,
28
+ )
29
+ print("BasicAgent initialized.")
30
+ def __call__(self, question: str) -> str:
31
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
32
+ # fixed_answer = "This is a default answer."
33
+ fixed_answer = self.agent.run(question)
34
+ print(f"Agent returning fixed answer: {fixed_answer}")
35
+ return fixed_answer
36
+
37
+
38
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
39
+ """
40
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
41
+ and displays the results.
42
+ """
43
+ # --- Determine HF Space Runtime URL and Repo URL ---
44
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
45
+
46
+ if profile:
47
+ username= f"{profile.username}"
48
+ print(f"User logged in: {username}")
49
+ else:
50
+ print("User not logged in.")
51
+ return "Please Login to Hugging Face with the button.", None
52
+
53
+ api_url = DEFAULT_API_URL
54
+ questions_url = f"{api_url}/questions"
55
+ submit_url = f"{api_url}/submit"
56
+
57
+ # 1. Instantiate Agent ( modify this part to create your agent)
58
+ try:
59
+ agent = BasicAgent()
60
+ except Exception as e:
61
+ print(f"Error instantiating agent: {e}")
62
+ return f"Error initializing agent: {e}", None
63
+ # 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)
64
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
65
+ print(agent_code)
66
+
67
+ # 2. Fetch Questions
68
+ print(f"Fetching questions from: {questions_url}")
69
+ try:
70
+ response = requests.get(questions_url, timeout=15)
71
+ response.raise_for_status()
72
+ questions_data = response.json()
73
+ if not questions_data:
74
+ print("Fetched questions list is empty.")
75
+ return "Fetched questions list is empty or invalid format.", None
76
+ print(f"Fetched {len(questions_data)} questions.")
77
+ except requests.exceptions.RequestException as e:
78
+ print(f"Error fetching questions: {e}")
79
+ return f"Error fetching questions: {e}", None
80
+ except requests.exceptions.JSONDecodeError as e:
81
+ print(f"Error decoding JSON response from questions endpoint: {e}")
82
+ print(f"Response text: {response.text[:500]}")
83
+ return f"Error decoding server response for questions: {e}", None
84
+ except Exception as e:
85
+ print(f"An unexpected error occurred fetching questions: {e}")
86
+ return f"An unexpected error occurred fetching questions: {e}", None
87
+
88
+ # 3. Run your Agent
89
+ results_log = []
90
+ answers_payload = []
91
+ print(f"Running agent on {len(questions_data)} questions...")
92
+ for item in questions_data:
93
+ task_id = item.get("task_id")
94
+ question_text = item.get("question")
95
+ if not task_id or question_text is None:
96
+ print(f"Skipping item with missing task_id or question: {item}")
97
+ continue
98
+ try:
99
+ submitted_answer = agent(question_text)
100
+ if not isinstance(submitted_answer, str):
101
+ submitted_answer = str(submitted_answer)
102
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
103
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
104
+ except Exception as e:
105
+ print(f"Error running agent on task {task_id}: {e}")
106
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
107
+
108
+ if not answers_payload:
109
+ print("Agent did not produce any answers to submit.")
110
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
111
+
112
+ # 4. Prepare Submission
113
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
114
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
115
+ print(status_update)
116
+
117
+ # 5. Submit
118
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
119
+ try:
120
+ response = requests.post(submit_url, json=submission_data, timeout=60)
121
+ response.raise_for_status()
122
+ result_data = response.json()
123
+ final_status = (
124
+ f"Submission Successful!\n"
125
+ f"User: {result_data.get('username')}\n"
126
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
127
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
128
+ f"Message: {result_data.get('message', 'No message received.')}"
129
+ )
130
+ print("Submission successful.")
131
+ results_df = pd.DataFrame(results_log)
132
+ return final_status, results_df
133
+ except requests.exceptions.HTTPError as e:
134
+ error_detail = f"Server responded with status {e.response.status_code}."
135
+ try:
136
+ error_json = e.response.json()
137
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
138
+ except requests.exceptions.JSONDecodeError:
139
+ error_detail += f" Response: {e.response.text[:500]}"
140
+ status_message = f"Submission Failed: {error_detail}"
141
+ print(status_message)
142
+ results_df = pd.DataFrame(results_log)
143
+ return status_message, results_df
144
+ except requests.exceptions.Timeout:
145
+ status_message = "Submission Failed: The request timed out."
146
+ print(status_message)
147
+ results_df = pd.DataFrame(results_log)
148
+ return status_message, results_df
149
+ except requests.exceptions.RequestException as e:
150
+ status_message = f"Submission Failed: Network error - {e}"
151
+ print(status_message)
152
+ results_df = pd.DataFrame(results_log)
153
+ return status_message, results_df
154
+ except Exception as e:
155
+ status_message = f"An unexpected error occurred during submission: {e}"
156
+ print(status_message)
157
+ results_df = pd.DataFrame(results_log)
158
+ return status_message, results_df
159
+
160
+
161
+ # --- Build Gradio Interface using Blocks ---
162
+ with gr.Blocks() as demo:
163
+ gr.Markdown("# Basic Agent Evaluation Runner")
164
+ gr.Markdown(
165
+ """
166
+ **Instructions:**
167
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
168
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
169
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
170
+ ---
171
+ **Disclaimers:**
172
+ Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
173
+ This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
174
+ """
175
+ )
176
+
177
+ gr.LoginButton()
178
+
179
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
180
+
181
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
182
+ # Removed max_rows=10 from DataFrame constructor
183
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
184
+
185
+ run_button.click(
186
+ fn=run_and_submit_all,
187
+ outputs=[status_output, results_table]
188
+ )
189
+
190
+ if __name__ == "__main__":
191
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
192
+ # Check for SPACE_HOST and SPACE_ID at startup for information
193
+ space_host_startup = os.getenv("SPACE_HOST")
194
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
195
+
196
+ if space_host_startup:
197
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
198
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
199
+ else:
200
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
201
+
202
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
203
+ print(f"✅ SPACE_ID found: {space_id_startup}")
204
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
205
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
206
+ else:
207
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
208
+
209
+ print("-"*(60 + len(" App Starting ")) + "\n")
210
+
211
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
212
  demo.launch(debug=True, share=False)