zineb-chgari commited on
Commit
c4f4fa4
Β·
verified Β·
1 Parent(s): b2ab5d7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1 -245
app.py CHANGED
@@ -32,248 +32,4 @@ for model_id in models_to_test:
32
  client.text_generation("Hello!", model=model_id, max_new_tokens=10)
33
  print(f"βœ… Accessible: {model_id}\n")
34
  except Exception as e:
35
- print(f"❌ Not accessible: {model_id} -> {e}\n")
36
-
37
- custom_prompt = """
38
- You are an intelligent AI agent participating in the GALA (Generative Agent Learning Assignment).
39
- Your goal is to answer each question accurately, concisely, and factually.
40
-
41
- Instructions:
42
- 1. Analyze the user's question carefully.
43
- 2. If you can answer it directly from your own knowledge, do so in one or two sentences.
44
- 3. If the question requires recent, factual, or numeric data (e.g. "current CEO", "latest version", "in 2025", etc.), use the DuckDuckGoSearchTool to find the answer.
45
- 4. When using a tool, be precise in your query and summarize the result clearly.
46
- 5. Always provide clean, readable text without markdown or citations unless explicitly requested.
47
- 6. If a question is ambiguous, briefly explain your assumption before answering.
48
- 7. Never refuse to answer unless the question is unrelated to the task or violates safety rules.
49
-
50
- Format:
51
- - Respond directly with the final answer only.
52
- - Do not include reasoning steps or technical metadata.
53
-
54
- Example behaviors:
55
- User: Who is the CEO of OpenAI?
56
- β†’ Use search tool β†’ "The CEO of OpenAI is Sam Altman."
57
-
58
- User: What is the capital of Japan?
59
- β†’ Direct answer β†’ "The capital of Japan is Tokyo."
60
-
61
- Remember: you are being evaluated for correctness and clarity.
62
- """
63
-
64
- @Tool
65
- def calculatorTool(query:str) -> str:
66
- try:
67
- result=eval(query)
68
- return str(result)
69
- except Exception as e:
70
- return f"error while calculating {e}"
71
- CalculatorTool=Tool(
72
- name="calculator",
73
- description="it calculates basic arithmetics",
74
- func=calculatorTool
75
- )
76
- class BasicAgent:
77
- def __init__(self):
78
- try:
79
- api_key=os.getenv("chatbotagenthf")
80
- model =InferenceClientModel(model_id="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free",token=api_key)
81
-
82
- self.agent = ToolCallingAgent(
83
- tools=[DuckDuckGoSearchTool()],
84
- model=model
85
- )
86
-
87
- print("βœ… Agent initialized successfully.")
88
-
89
- except Exception as e:
90
- print(f"❌ Error initializing agent: {e}")
91
- traceback.print_exc()
92
- raise e
93
-
94
- def __call__(self, question: str) -> str:
95
- try:
96
- print(f"\n➑️ Agent received question: {question[:80]}")
97
- agent_answer = self.agent.run(question)
98
- print(f"βœ… Agent returning answer: {agent_answer}")
99
- return agent_answer
100
- except Exception as e:
101
- print(f"❌ Agent encountered an error: {e}")
102
- traceback.print_exc()
103
- return f"Error generating answer: {e}"
104
-
105
-
106
- def run_and_submit_all( profile: gr.OAuthProfile | None):
107
- """
108
- Fetches all questions, runs the BasicAgent on them, submits all answers,
109
- and displays the results.
110
- """
111
- # --- Determine HF Space Runtime URL and Repo URL ---
112
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
113
-
114
- if profile:
115
- username= f"{profile.username}"
116
- print(f"User logged in: {username}")
117
- else:
118
- print("User not logged in.")
119
- return "Please Login to Hugging Face with the button.", None
120
-
121
- api_url = DEFAULT_API_URL
122
- questions_url = f"{api_url}/questions"
123
- submit_url = f"{api_url}/submit"
124
-
125
- # 1. Instantiate Agent ( modify this part to create your agent)
126
- try:
127
- agent = BasicAgent()
128
- except Exception as e:
129
- print(f"Error instantiating agent: {e}")
130
- return f"Error initializing agent: {e}", None
131
- # 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)
132
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
133
- print(agent_code)
134
-
135
- # 2. Fetch Questions
136
- print(f"Fetching questions from: {questions_url}")
137
- try:
138
- response = requests.get(questions_url, timeout=15)
139
- response.raise_for_status()
140
- questions_data = response.json()
141
- if not questions_data:
142
- print("Fetched questions list is empty.")
143
- return "Fetched questions list is empty or invalid format.", None
144
- print(f"Fetched {len(questions_data)} questions.")
145
- except requests.exceptions.RequestException as e:
146
- print(f"Error fetching questions: {e}")
147
- return f"Error fetching questions: {e}", None
148
- except requests.exceptions.JSONDecodeError as e:
149
- print(f"Error decoding JSON response from questions endpoint: {e}")
150
- print(f"Response text: {response.text[:500]}")
151
- return f"Error decoding server response for questions: {e}", None
152
- except Exception as e:
153
- print(f"An unexpected error occurred fetching questions: {e}")
154
- return f"An unexpected error occurred fetching questions: {e}", None
155
-
156
- # 3. Run your Agent
157
- results_log = []
158
- answers_payload = []
159
- print(f"Running agent on {len(questions_data)} questions...")
160
- for item in questions_data:
161
- task_id = item.get("task_id")
162
- question_text = item.get("question")
163
- if not task_id or question_text is None:
164
- print(f"Skipping item with missing task_id or question: {item}")
165
- continue
166
- try:
167
- submitted_answer = agent(question_text)
168
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
169
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
170
- except Exception as e:
171
- print(f"Error running agent on task {task_id}: {e}")
172
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
173
-
174
- if not answers_payload:
175
- print("Agent did not produce any answers to submit.")
176
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
177
-
178
- # 4. Prepare Submission
179
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
180
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
181
- print(status_update)
182
-
183
- # 5. Submit
184
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
185
- try:
186
- response = requests.post(submit_url, json=submission_data, timeout=60)
187
- response.raise_for_status()
188
- result_data = response.json()
189
- final_status = (
190
- f"Submission Successful!\n"
191
- f"User: {result_data.get('username')}\n"
192
- f"Overall Score: {result_data.get('score', 'N/A')}% "
193
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
194
- f"Message: {result_data.get('message', 'No message received.')}"
195
- )
196
- print("Submission successful.")
197
- results_df = pd.DataFrame(results_log)
198
- return final_status, results_df
199
- except requests.exceptions.HTTPError as e:
200
- error_detail = f"Server responded with status {e.response.status_code}."
201
- try:
202
- error_json = e.response.json()
203
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
204
- except requests.exceptions.JSONDecodeError:
205
- error_detail += f" Response: {e.response.text[:500]}"
206
- status_message = f"Submission Failed: {error_detail}"
207
- print(status_message)
208
- results_df = pd.DataFrame(results_log)
209
- return status_message, results_df
210
- except requests.exceptions.Timeout:
211
- status_message = "Submission Failed: The request timed out."
212
- print(status_message)
213
- results_df = pd.DataFrame(results_log)
214
- return status_message, results_df
215
- except requests.exceptions.RequestException as e:
216
- status_message = f"Submission Failed: Network error - {e}"
217
- print(status_message)
218
- results_df = pd.DataFrame(results_log)
219
- return status_message, results_df
220
- except Exception as e:
221
- status_message = f"An unexpected error occurred during submission: {e}"
222
- print(status_message)
223
- results_df = pd.DataFrame(results_log)
224
- return status_message, results_df
225
-
226
-
227
- # --- Build Gradio Interface using Blocks ---
228
- with gr.Blocks() as demo:
229
- gr.Markdown("# Basic Agent Evaluation Runner")
230
- gr.Markdown(
231
- """
232
- **Instructions:**
233
-
234
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
235
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
236
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
237
-
238
- ---
239
- **Disclaimers:**
240
- 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).
241
- 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.
242
- """
243
- )
244
-
245
- gr.LoginButton()
246
-
247
- run_button = gr.Button("Run Evaluation & Submit All Answers")
248
-
249
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
250
- # Removed max_rows=10 from DataFrame constructor
251
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
252
-
253
- run_button.click(
254
- fn=run_and_submit_all,
255
- outputs=[status_output, results_table]
256
- )
257
-
258
- if __name__ == "__main__":
259
- print("\n" + "-"*30 + " App Starting " + "-"*30)
260
- # Check for SPACE_HOST and SPACE_ID at startup for information
261
- space_host_startup = os.getenv("SPACE_HOST")
262
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
263
-
264
- if space_host_startup:
265
- print(f"βœ… SPACE_HOST found: {space_host_startup}")
266
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
267
- else:
268
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
269
-
270
- if space_id_startup: # Print repo URLs if SPACE_ID is found
271
- print(f"βœ… SPACE_ID found: {space_id_startup}")
272
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
273
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
274
- else:
275
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
276
-
277
- print("-"*(60 + len(" App Starting ")) + "\n")
278
- print("Launching Gradio Interface for Basic Agent Evaluation...")
279
- demo.launch(debug=True, share=False)
 
32
  client.text_generation("Hello!", model=model_id, max_new_tokens=10)
33
  print(f"βœ… Accessible: {model_id}\n")
34
  except Exception as e:
35
+ print(f"❌ Not accessible: {model_id} -> {e}\n")