ghanemfaouri commited on
Commit
e9fba3a
·
verified ·
1 Parent(s): 1d9d9f8

Upload app.py

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