vladd19 commited on
Commit
2ddd689
·
verified ·
1 Parent(s): 6603541

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -57
app.py CHANGED
@@ -3,76 +3,67 @@ import gradio as gr
3
  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
  # --- Basic Agent Definition ---
14
  class BasicAgent:
15
  def __init__(self):
16
- # 1. Указываем ID модели.
17
- # Вы можете использовать "Qwen/Qwen3.6-27B" (или другую доступную модель Qwen 3.6),
18
- # либо проверенную в курсе кодинг-модель "Qwen/Qwen2.5-Coder-32B-Instruct".
19
  model_id = "Qwen/Qwen2.5-Coder-32B-Instruct"
20
-
21
- # Получаем токен из секретов Space, которые вы настроили ранее
22
  hf_token = os.getenv("HF_TOKEN")
 
23
  if not hf_token:
24
- print("⚠️ ВНИМАНИЕ: Секрет HF_TOKEN не найден в настройках Space!")
25
 
26
- # 2. Инициализируем модель
27
  self.model = HfApiModel(
28
  model_id=model_id,
29
  token=hf_token
30
  )
31
-
32
- # 3. Подключаем инструмент поиска в интернете
33
  self.search_tool = DuckDuckGoSearchTool()
34
 
35
- # 4. Создаем CodeAgent, который умеет запускать Python-код для вычислений
36
  self.agent = CodeAgent(
37
  tools=[self.search_tool],
38
  model=self.model,
39
- add_base_tools=True # Подключает базовые инструменты smolagents
40
  )
41
  print(f"BasicAgent успешно инициализирован с моделью: {model_id}")
42
 
43
  def __call__(self, question: str) -> str:
44
  print(f"Agent received question (first 50 chars): {question[:50]}...")
45
 
46
- # Системное указание агенту возвращать только результат (для Exact Match)
47
  prompt = (
48
  f"{question}\n\n"
49
- "ВАЖНО: Твой ответ будет проверяться автоматически на точное соответствие (Exact Match). "
50
- "Выведи ТОЛЬКО финальный ответ (число, дату, слово или краткую фразу) "
51
- "без каких-либо вводных слов, пояснений и оформления вроде 'The answer is:' или 'FINAL ANSWER'."
 
52
  )
53
 
54
  try:
55
- # Запускаем агента для выполнения задачи
56
  result = self.agent.run(prompt)
57
- # Приводим к строке и удаляем лишние пробелы по краям
58
- fixed_answer = str(result).strip()
59
- print(f"Agent returning answer: {fixed_answer}")
60
- return fixed_answer
61
  except Exception as e:
62
- error_msg = f"ERROR: {str(e)}"
63
- print(f"Ошибка при работе агента: {error_msg}")
64
- return error_msg
65
 
66
- def run_and_submit_all( profile: gr.OAuthProfile | None):
67
  """
68
  Fetches all questions, runs the BasicAgent on them, submits all answers,
69
  and displays the results.
70
  """
71
- # --- Determine HF Space Runtime URL and Repo URL ---
72
  space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
73
 
74
  if profile:
75
- username= f"{profile.username}"
76
  print(f"User logged in: {username}")
77
  else:
78
  print("User not logged in.")
@@ -82,13 +73,13 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
82
  questions_url = f"{api_url}/questions"
83
  submit_url = f"{api_url}/submit"
84
 
85
- # 1. Instantiate Agent ( modify this part to create your agent)
86
  try:
87
  agent = BasicAgent()
88
  except Exception as e:
89
  print(f"Error instantiating agent: {e}")
90
  return f"Error initializing agent: {e}", None
91
- # 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)
92
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
93
  print(agent_code)
94
 
@@ -193,10 +184,6 @@ with gr.Blocks() as demo:
193
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
194
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
195
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
196
- ---
197
- **Disclaimers:**
198
- 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).
199
- 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.
200
  """
201
  )
202
 
@@ -205,7 +192,6 @@ with gr.Blocks() as demo:
205
  run_button = gr.Button("Run Evaluation & Submit All Answers")
206
 
207
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
208
- # Removed max_rows=10 from DataFrame constructor
209
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
210
 
211
  run_button.click(
@@ -213,26 +199,14 @@ with gr.Blocks() as demo:
213
  outputs=[status_output, results_table]
214
  )
215
 
216
- if __name__ == "__main__":
217
- print("\n" + "-"*30 + " App Starting " + "-"*30)
218
- # Check for SPACE_HOST and SPACE_ID at startup for information
219
- space_host_startup = os.getenv("SPACE_HOST")
220
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
221
-
222
- if space_host_startup:
223
- print(f"✅ SPACE_HOST found: {space_host_startup}")
224
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
225
- else:
226
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
227
-
228
- if space_id_startup: # Print repo URLs if SPACE_ID is found
229
- print(f"✅ SPACE_ID found: {space_id_startup}")
230
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
231
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
232
- else:
233
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
234
 
235
- print("-"*(60 + len(" App Starting ")) + "\n")
 
 
 
236
 
237
- print("Launching Gradio Interface for Basic Agent Evaluation...")
238
- demo.launch(debug=True, share=False)
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ from smolagents import CodeAgent, HfApiModel, DuckDuckGoSearchTool
7
 
 
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
 
 
11
  # --- Basic Agent Definition ---
12
  class BasicAgent:
13
  def __init__(self):
14
+ # Используем Qwen 2.5 Coder 32B как надежную и проверенную модель для агентов
 
 
15
  model_id = "Qwen/Qwen2.5-Coder-32B-Instruct"
 
 
16
  hf_token = os.getenv("HF_TOKEN")
17
+
18
  if not hf_token:
19
+ print("⚠️ WARNING: Секрет HF_TOKEN не обнаружен!")
20
 
 
21
  self.model = HfApiModel(
22
  model_id=model_id,
23
  token=hf_token
24
  )
25
+ # Добавляем поиск DuckDuckGo
 
26
  self.search_tool = DuckDuckGoSearchTool()
27
 
28
+ # Создаем CodeAgent
29
  self.agent = CodeAgent(
30
  tools=[self.search_tool],
31
  model=self.model,
32
+ add_base_tools=True
33
  )
34
  print(f"BasicAgent успешно инициализирован с моделью: {model_id}")
35
 
36
  def __call__(self, question: str) -> str:
37
  print(f"Agent received question (first 50 chars): {question[:50]}...")
38
 
39
+ # Промпт для соблюдения Exact Match формата
40
  prompt = (
41
  f"{question}\n\n"
42
+ "ВАЖНОЕ ТРЕБОВАНИЕ: Твой ответ должен содержать только итоговое значение "
43
+ "(число, дату, слово или краткую фразу) без каких-либо вводных слов, пояснений "
44
+ "или разметки типа 'The final answer is:' или 'FINAL ANSWER'. "
45
+ "Выведи только чистый результат."
46
  )
47
 
48
  try:
 
49
  result = self.agent.run(prompt)
50
+ final_answer = str(result).strip()
51
+ print(f"Agent returning answer: {final_answer}")
52
+ return final_answer
 
53
  except Exception as e:
54
+ print(f"Error during agent execution: {e}")
55
+ return f"ERROR: {e}"
56
+
57
 
58
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
59
  """
60
  Fetches all questions, runs the BasicAgent on them, submits all answers,
61
  and displays the results.
62
  """
 
63
  space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
64
 
65
  if profile:
66
+ username = f"{profile.username}"
67
  print(f"User logged in: {username}")
68
  else:
69
  print("User not logged in.")
 
73
  questions_url = f"{api_url}/questions"
74
  submit_url = f"{api_url}/submit"
75
 
76
+ # 1. Instantiate Agent
77
  try:
78
  agent = BasicAgent()
79
  except Exception as e:
80
  print(f"Error instantiating agent: {e}")
81
  return f"Error initializing agent: {e}", None
82
+
83
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
84
  print(agent_code)
85
 
 
184
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
185
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
186
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
 
 
 
 
187
  """
188
  )
189
 
 
192
  run_button = gr.Button("Run Evaluation & Submit All Answers")
193
 
194
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
195
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
196
 
197
  run_button.click(
 
199
  outputs=[status_output, results_table]
200
  )
201
 
202
+ # --- Инициализация без блока 'if __name__ == "__main__":' ---
203
+ space_host_startup = os.getenv("SPACE_HOST")
204
+ space_id_startup = os.getenv("SPACE_ID")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
 
206
+ if space_host_startup:
207
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
208
+ if space_id_startup:
209
+ print(f"✅ SPACE_ID found: {space_id_startup}")
210
 
211
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
212
+ demo.launch(debug=True, share=False)