Files changed (1) hide show
  1. app.py +46 -26
app.py CHANGED
@@ -4,31 +4,57 @@ import requests
4
  import inspect
5
  import pandas as pd
6
 
7
- # (Keep Constants as is)
 
 
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
- # --- Basic Agent Definition ---
12
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
  class BasicAgent:
14
  def __init__(self):
15
- print("BasicAgent initialized.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  def __call__(self, question: str) -> str:
17
  print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
 
 
 
 
 
21
 
22
- def run_and_submit_all( profile: gr.OAuthProfile | None):
23
  """
24
- Fetches all questions, runs the BasicAgent on them, submits all answers,
25
  and displays the results.
26
  """
27
  # --- Determine HF Space Runtime URL and Repo URL ---
28
  space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
29
 
30
  if profile:
31
- username= f"{profile.username}"
32
  print(f"User logged in: {username}")
33
  else:
34
  print("User not logged in.")
@@ -38,13 +64,14 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
38
  questions_url = f"{api_url}/questions"
39
  submit_url = f"{api_url}/submit"
40
 
41
- # 1. Instantiate Agent ( modify this part to create your agent)
42
  try:
43
  agent = BasicAgent()
44
  except Exception as e:
45
  print(f"Error instantiating agent: {e}")
46
  return f"Error initializing agent: {e}", None
47
- # 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)
 
48
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
49
  print(agent_code)
50
 
@@ -142,19 +169,14 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
142
 
143
  # --- Build Gradio Interface using Blocks ---
144
  with gr.Blocks() as demo:
145
- gr.Markdown("# Basic Agent Evaluation Runner")
146
  gr.Markdown(
147
  """
148
  **Instructions:**
149
 
150
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
151
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
152
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
153
-
154
- ---
155
- **Disclaimers:**
156
- 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).
157
- 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.
158
  """
159
  )
160
 
@@ -163,7 +185,6 @@ with gr.Blocks() as demo:
163
  run_button = gr.Button("Run Evaluation & Submit All Answers")
164
 
165
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
166
- # Removed max_rows=10 from DataFrame constructor
167
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
168
 
169
  run_button.click(
@@ -173,9 +194,8 @@ with gr.Blocks() as demo:
173
 
174
  if __name__ == "__main__":
175
  print("\n" + "-"*30 + " App Starting " + "-"*30)
176
- # Check for SPACE_HOST and SPACE_ID at startup for information
177
  space_host_startup = os.getenv("SPACE_HOST")
178
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
179
 
180
  if space_host_startup:
181
  print(f"✅ SPACE_HOST found: {space_host_startup}")
@@ -183,7 +203,7 @@ if __name__ == "__main__":
183
  else:
184
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
185
 
186
- if space_id_startup: # Print repo URLs if SPACE_ID is found
187
  print(f"✅ SPACE_ID found: {space_id_startup}")
188
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
189
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
@@ -192,5 +212,5 @@ if __name__ == "__main__":
192
 
193
  print("-"*(60 + len(" App Starting ")) + "\n")
194
 
195
- print("Launching Gradio Interface for Basic Agent Evaluation...")
196
  demo.launch(debug=True, share=False)
 
4
  import inspect
5
  import pandas as pd
6
 
7
+ # --- Importações do smolagents ---
8
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, LiteLLMModel
9
+
10
  # --- Constants ---
11
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
 
13
+ # --- Real Agent Definition usando smolagents ---
 
14
  class BasicAgent:
15
  def __init__(self):
16
+ print("Initializing Real Agent with smolagents and Gemini...")
17
+
18
+ # 1. Configura o modelo Gemini através do LiteLLM usando a chave de API correta
19
+ # O smolagents usa o padrão "gemini/gemini-pro" ou modelos mais recentes como "gemini/gemini-1.5-flash" via LiteLLM
20
+ self.model = LiteLLMModel(
21
+ model_id="gemini/gemini-1.5-flash",
22
+ api_key=os.getenv("GEMINI_API_KEY")
23
+ )
24
+
25
+ # 2. Instancia as ferramentas necessárias (Neste caso, Busca Web via DuckDuckGo)
26
+ self.search_tool = DuckDuckGoSearchTool()
27
+
28
+ # 3. Cria o CodeAgent (ou você pode usar ToolCallingAgent se preferir JSON)
29
+ # Passamos a ferramenta de busca na lista de tools
30
+ self.agent = CodeAgent(
31
+ tools=[self.search_tool],
32
+ model=self.model,
33
+ add_base_tools=True # Adiciona ferramentas base do smolagents úteis para manipulação de dados
34
+ )
35
+ print("Real Agent initialized successfully.")
36
+
37
  def __call__(self, question: str) -> str:
38
  print(f"Agent received question (first 50 chars): {question[:50]}...")
39
+ try:
40
+ # Executa o agente passando a pergunta enviada pela plataforma de avaliação
41
+ response = self.agent.run(question)
42
+ print(f"Agent raw response: {response}")
43
+ return str(response)
44
+ except Exception as e:
45
+ print(f"Error during agent execution: {e}")
46
+ return f"Error processing request: {str(e)}"
47
 
48
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
49
  """
50
+ Fetches all questions, runs the Real Agent on them, submits all answers,
51
  and displays the results.
52
  """
53
  # --- Determine HF Space Runtime URL and Repo URL ---
54
  space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
55
 
56
  if profile:
57
+ username = f"{profile.username}"
58
  print(f"User logged in: {username}")
59
  else:
60
  print("User not logged in.")
 
64
  questions_url = f"{api_url}/questions"
65
  submit_url = f"{api_url}/submit"
66
 
67
+ # 1. Instantiate Agent (Instanciando o novo agente configurado)
68
  try:
69
  agent = BasicAgent()
70
  except Exception as e:
71
  print(f"Error instantiating agent: {e}")
72
  return f"Error initializing agent: {e}", None
73
+
74
+ # In the case of an app running as a hugging Face space, this link points toward your codebase
75
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
76
  print(agent_code)
77
 
 
169
 
170
  # --- Build Gradio Interface using Blocks ---
171
  with gr.Blocks() as demo:
172
+ gr.Markdown("# Gemini smolagents Evaluation Runner")
173
  gr.Markdown(
174
  """
175
  **Instructions:**
176
 
177
+ 1. This Space has been configured to use `smolagents` with Google Gemini.
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
 
 
185
  run_button = gr.Button("Run Evaluation & Submit All Answers")
186
 
187
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
188
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
189
 
190
  run_button.click(
 
194
 
195
  if __name__ == "__main__":
196
  print("\n" + "-"*30 + " App Starting " + "-"*30)
 
197
  space_host_startup = os.getenv("SPACE_HOST")
198
+ space_id_startup = os.getenv("SPACE_ID")
199
 
200
  if space_host_startup:
201
  print(f"✅ SPACE_HOST found: {space_host_startup}")
 
203
  else:
204
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
205
 
206
+ if space_id_startup:
207
  print(f"✅ SPACE_ID found: {space_id_startup}")
208
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
209
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
 
212
 
213
  print("-"*(60 + len(" App Starting ")) + "\n")
214
 
215
+ print("Launching Gradio Interface for Agent Evaluation...")
216
  demo.launch(debug=True, share=False)