VincentG1234 commited on
Commit
8cdcc51
·
verified ·
1 Parent(s): 099d700

Delete paulistaunb_app.py

Browse files
Files changed (1) hide show
  1. paulistaunb_app.py +0 -259
paulistaunb_app.py DELETED
@@ -1,259 +0,0 @@
1
- import os
2
- import gradio as gr
3
- import requests
4
- import inspect
5
- import pandas as pd
6
-
7
- from smolagents import ToolCallingAgent, HfApiModel, DuckDuckGoSearchTool, PythonInterpreterTool
8
- from smolagents import OpenAIServerModel
9
-
10
-
11
- from agentsTools.toolVisitWebpage import visit_webpage
12
- from agentsTools.tool_fetch_task_file import fetch_task_file
13
- from agentsTools.tool_read_excel_as_json import read_excel_as_json
14
-
15
- # (Keep Constants as is)
16
- # --- Constants ---
17
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
18
-
19
- hf_token = os.getenv("HUGGINGFACEHUB_API_TOKEN")
20
-
21
- def get_gemini_model():
22
- return OpenAIServerModel(
23
- model_id="OPENAI_API_KEY",
24
- api_base="https://generativelanguage.googleapis.com/v1beta/",
25
- api_key=os.getenv("GEMINI_API_KEY_1", "your-gemini-api-key-here")
26
- )
27
-
28
- model = get_gemini_model()
29
-
30
- # --- Basic Agent Definition ---
31
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
32
- class BasicAgent:
33
- def __init__(self):
34
- print("BasicAgent initialized.")
35
- def __call__(self, question: str, taskid: str) -> str:
36
- print(f"Agent received question (first 50 chars): {question[:50]}...")
37
-
38
-
39
- agent = ToolCallingAgent(
40
- tools=[
41
- DuckDuckGoSearchTool(),
42
- PythonInterpreterTool(),
43
- visit_webpage,
44
- fetch_task_file,
45
- read_excel_as_json,
46
- # update_File,
47
-
48
- ],
49
- #model=HfApiModel(api_key=hf_token),
50
- model=model,
51
- max_steps=10
52
- )
53
-
54
- task = f"""
55
-
56
- You are a general AI assistant.
57
- I will ask you a question and you can use 8 steps to answer it.
58
- You can use the tools I provided to you to answer the question.
59
- Every time you use a tool, the number of steps will decrease by one.
60
- If you have a list of possible pages to visit, prefer the wikipedia ones.
61
- If a page does not allow visit, skip it.
62
- Report your thoughts, and finish your answer with the following template:
63
- FINAL ANSWER: [YOUR FINAL ANSWER].
64
-
65
- YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
66
-
67
- 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.
68
- 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.
69
- 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.
70
-
71
- The taskid is {taskid} in case you need to get extra files, use taskid and not name of the file
72
- and the question is {question}
73
-
74
-
75
- """
76
-
77
- # Let the agent drive the task execution (ReAct loop)
78
- # fixed_answer = "This is a default answer."
79
- fixed_answer = agent.run(task)
80
-
81
-
82
- print(f"Agent returning fixed answer: {fixed_answer}")
83
- return fixed_answer
84
-
85
- def run_and_submit_all( profile: gr.OAuthProfile | None):
86
- """
87
- Fetches all questions, runs the BasicAgent on them, submits all answers,
88
- and displays the results.
89
- """
90
- # --- Determine HF Space Runtime URL and Repo URL ---
91
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
92
-
93
- if profile:
94
- username= f"{profile.username}"
95
- print(f"User logged in: {username}")
96
- else:
97
- print("User not logged in.")
98
- return "Please Login to Hugging Face with the button.", None
99
-
100
- api_url = DEFAULT_API_URL
101
- questions_url = f"{api_url}/questions"
102
- submit_url = f"{api_url}/submit"
103
-
104
- # 1. Instantiate Agent ( modify this part to create your agent)
105
- try:
106
- agent = BasicAgent()
107
- except Exception as e:
108
- print(f"Error instantiating agent: {e}")
109
- return f"Error initializing agent: {e}", None
110
- # 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)
111
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
112
- print(agent_code)
113
-
114
- # 2. Fetch Questions
115
- print(f"Fetching questions from: {questions_url}")
116
- try:
117
- response = requests.get(questions_url, timeout=15)
118
- response.raise_for_status()
119
- questions_data = response.json()
120
- if not questions_data:
121
- print("Fetched questions list is empty.")
122
- return "Fetched questions list is empty or invalid format.", None
123
- print(f"Fetched {len(questions_data)} questions.")
124
- except requests.exceptions.RequestException as e:
125
- print(f"Error fetching questions: {e}")
126
- return f"Error fetching questions: {e}", None
127
- except requests.exceptions.JSONDecodeError as e:
128
- print(f"Error decoding JSON response from questions endpoint: {e}")
129
- print(f"Response text: {response.text[:500]}")
130
- return f"Error decoding server response for questions: {e}", None
131
- except Exception as e:
132
- print(f"An unexpected error occurred fetching questions: {e}")
133
- return f"An unexpected error occurred fetching questions: {e}", None
134
-
135
- # 3. Run your Agent
136
- results_log = []
137
- answers_payload = []
138
- print(f"Running agent on {len(questions_data)} questions...")
139
- for item in questions_data:
140
- task_id = item.get("task_id")
141
- question_text = item.get("question")
142
- if not task_id or question_text is None:
143
- print(f"Skipping item with missing task_id or question: {item}")
144
- continue
145
- try:
146
- submitted_answer = agent(question_text,task_id)
147
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
148
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
149
- except Exception as e:
150
- print(f"Error running agent on task {task_id}: {e}")
151
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
152
-
153
- if not answers_payload:
154
- print("Agent did not produce any answers to submit.")
155
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
156
-
157
- # 4. Prepare Submission
158
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
159
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
160
- print(status_update)
161
-
162
- # 5. Submit
163
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
164
- try:
165
- response = requests.post(submit_url, json=submission_data, timeout=60)
166
- response.raise_for_status()
167
- result_data = response.json()
168
- final_status = (
169
- f"Submission Successful!\n"
170
- f"User: {result_data.get('username')}\n"
171
- f"Overall Score: {result_data.get('score', 'N/A')}% "
172
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
173
- f"Message: {result_data.get('message', 'No message received.')}"
174
- )
175
- print("Submission successful.")
176
- results_df = pd.DataFrame(results_log)
177
- return final_status, results_df
178
- except requests.exceptions.HTTPError as e:
179
- error_detail = f"Server responded with status {e.response.status_code}."
180
- try:
181
- error_json = e.response.json()
182
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
183
- except requests.exceptions.JSONDecodeError:
184
- error_detail += f" Response: {e.response.text[:500]}"
185
- status_message = f"Submission Failed: {error_detail}"
186
- print(status_message)
187
- results_df = pd.DataFrame(results_log)
188
- return status_message, results_df
189
- except requests.exceptions.Timeout:
190
- status_message = "Submission Failed: The request timed out."
191
- print(status_message)
192
- results_df = pd.DataFrame(results_log)
193
- return status_message, results_df
194
- except requests.exceptions.RequestException as e:
195
- status_message = f"Submission Failed: Network error - {e}"
196
- print(status_message)
197
- results_df = pd.DataFrame(results_log)
198
- return status_message, results_df
199
- except Exception as e:
200
- status_message = f"An unexpected error occurred during submission: {e}"
201
- print(status_message)
202
- results_df = pd.DataFrame(results_log)
203
- return status_message, results_df
204
-
205
-
206
- # --- Build Gradio Interface using Blocks ---
207
- with gr.Blocks() as demo:
208
- gr.Markdown("# Basic Agent Evaluation Runner")
209
- gr.Markdown(
210
- """
211
- **Instructions:**
212
-
213
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
214
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
215
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
216
-
217
- ---
218
- **Disclaimers:**
219
- 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).
220
- 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.
221
- """
222
- )
223
-
224
- gr.LoginButton()
225
-
226
- run_button = gr.Button("Run Evaluation & Submit All Answers")
227
-
228
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
229
- # Removed max_rows=10 from DataFrame constructor
230
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
231
-
232
- run_button.click(
233
- fn=run_and_submit_all,
234
- outputs=[status_output, results_table]
235
- )
236
-
237
- if __name__ == "__main__":
238
- print("\n" + "-"*30 + " App Starting " + "-"*30)
239
- # Check for SPACE_HOST and SPACE_ID at startup for information
240
- space_host_startup = os.getenv("SPACE_HOST")
241
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
242
-
243
- if space_host_startup:
244
- print(f"✅ SPACE_HOST found: {space_host_startup}")
245
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
246
- else:
247
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
248
-
249
- if space_id_startup: # Print repo URLs if SPACE_ID is found
250
- print(f"✅ SPACE_ID found: {space_id_startup}")
251
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
252
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
253
- else:
254
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
255
-
256
- print("-"*(60 + len(" App Starting ")) + "\n")
257
-
258
- print("Launching Gradio Interface for Basic Agent Evaluation...")
259
- demo.launch(debug=True, share=False)