davron04 commited on
Commit
e3f14a8
·
1 Parent(s): 3cc7cf4

first agent version

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