artyomboyko commited on
Commit
0652464
·
verified ·
1 Parent(s): 81917a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -17
app.py CHANGED
@@ -4,18 +4,26 @@ 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
 
@@ -24,8 +32,8 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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}"
@@ -38,13 +46,13 @@ 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
 
@@ -69,7 +77,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
69
  print(f"An unexpected error occurred fetching questions: {e}")
70
  return f"An unexpected error occurred fetching questions: {e}", None
71
 
72
- # 3. Run your Agent
73
  results_log = []
74
  answers_payload = []
75
  print(f"Running agent on {len(questions_data)} questions...")
@@ -91,12 +99,12 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
91
  print("Agent did not produce any answers to submit.")
92
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
93
 
94
- # 4. Prepare Submission
95
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
96
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
97
  print(status_update)
98
 
99
- # 5. Submit
100
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
101
  try:
102
  response = requests.post(submit_url, json=submission_data, timeout=60)
@@ -140,7 +148,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
140
  return status_message, results_df
141
 
142
 
143
- # --- Build Gradio Interface using Blocks ---
144
  with gr.Blocks() as demo:
145
  gr.Markdown("# Basic Agent Evaluation Runner")
146
  gr.Markdown(
@@ -163,7 +171,7 @@ 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 +181,9 @@ 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 +191,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")
 
4
  import inspect
5
  import pandas as pd
6
 
7
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
8
+
9
+
10
+ # (Сохраните константы как есть)
11
+ # --- Константы ---
12
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
 
14
+ # --- Основное определение агента ---
15
+ # ----- ЗДЕСЬ ВЫ МОЖЕТЕ СОЗДАТЬ ТО, ЧТО ХОТИТЕ ------
16
  class BasicAgent:
17
  def __init__(self):
18
  print("BasicAgent initialized.")
19
+
20
+ self.agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=HfApiModel())
21
+
22
+ print("Agent initialized successfully.")
23
+
24
  def __call__(self, question: str) -> str:
25
  print(f"Agent received question (first 50 chars): {question[:50]}...")
26
+ fixed_answer = self.agent.run(question)
27
  print(f"Agent returning fixed answer: {fixed_answer}")
28
  return fixed_answer
29
 
 
32
  Fetches all questions, runs the BasicAgent on them, submits all answers,
33
  and displays the results.
34
  """
35
+ # --- Определите HF Space Runtime URL и Repo URL ---
36
+ space_id = os.getenv("SPACE_ID") # Получите SPACE_ID для отправки ссылки на код
37
 
38
  if profile:
39
  username= f"{profile.username}"
 
46
  questions_url = f"{api_url}/questions"
47
  submit_url = f"{api_url}/submit"
48
 
49
+ # 1. Инстантируйте агента (измените эту часть, чтобы создать своего агента)
50
  try:
51
  agent = BasicAgent()
52
  except Exception as e:
53
  print(f"Error instantiating agent: {e}")
54
  return f"Error initializing agent: {e}", None
55
+ # В случае приложения, работающего как пространство Hugging Face, эта ссылка указывает на вашу кодовую базу (полезно для других, поэтому, пожалуйста, держите ее в открытом доступе).
56
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
57
  print(agent_code)
58
 
 
77
  print(f"An unexpected error occurred fetching questions: {e}")
78
  return f"An unexpected error occurred fetching questions: {e}", None
79
 
80
+ # 3. Запуск агента
81
  results_log = []
82
  answers_payload = []
83
  print(f"Running agent on {len(questions_data)} questions...")
 
99
  print("Agent did not produce any answers to submit.")
100
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
101
 
102
+ # 4. Подготовка к отправке
103
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
104
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
105
  print(status_update)
106
 
107
+ # 5. Отправка
108
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
109
  try:
110
  response = requests.post(submit_url, json=submission_data, timeout=60)
 
148
  return status_message, results_df
149
 
150
 
151
+ # --- Создание интерфейса Gradio с использованием Blocks ---
152
  with gr.Blocks() as demo:
153
  gr.Markdown("# Basic Agent Evaluation Runner")
154
  gr.Markdown(
 
171
  run_button = gr.Button("Run Evaluation & Submit All Answers")
172
 
173
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
174
+ # Удалено max_rows=10 из конструктора DataFrame
175
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
176
 
177
  run_button.click(
 
181
 
182
  if __name__ == "__main__":
183
  print("\n" + "-"*30 + " App Starting " + "-"*30)
184
+ # Проверьте наличие SPACE_HOST и SPACE_ID при запуске для получения информации
185
  space_host_startup = os.getenv("SPACE_HOST")
186
+ space_id_startup = os.getenv("SPACE_ID") # Получение SPACE_ID при запуске
187
 
188
  if space_host_startup:
189
  print(f"✅ SPACE_HOST found: {space_host_startup}")
 
191
  else:
192
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
193
 
194
+ if space_id_startup: # Вывод URL репозитория, если найден SPACE_ID
195
  print(f"✅ SPACE_ID found: {space_id_startup}")
196
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
197
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")