Imnotchis commited on
Commit
e8883a1
·
verified ·
1 Parent(s): a683cea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -30
app.py CHANGED
@@ -5,7 +5,13 @@ from pathlib import Path
5
  import gradio as gr
6
  import pandas as pd
7
  import requests
8
- from smolagents import CodeAgent, OpenAIServerModel, DuckDuckGoSearchTool, VisitWebpageTool
 
 
 
 
 
 
9
 
10
  # --- Constants ---
11
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
@@ -15,7 +21,6 @@ DOWNLOADS_DIR.mkdir(parents=True, exist_ok=True)
15
  def make_request_with_retry(url, method="get", max_retries=5, backoff_factor=3, **kwargs):
16
  """
17
  Tự động gọi lại API nếu gặp lỗi 429 (Too Many Requests) hoặc lỗi mạng ngẫu nhiên.
18
- Thời gian chờ sẽ tăng theo cấp số nhân: 3s -> 6s -> 12s -> 24s...
19
  """
20
  for attempt in range(max_retries):
21
  try:
@@ -24,7 +29,6 @@ def make_request_with_retry(url, method="get", max_retries=5, backoff_factor=3,
24
  elif method.lower() == "post":
25
  response = requests.post(url, **kwargs)
26
 
27
- # Xử lý riêng khi bị máy chủ giới hạn tần suất (429)
28
  if response.status_code == 429:
29
  wait_time = backoff_factor * (2 ** attempt)
30
  print(f"⚠️ Máy chủ đang quá tải (Lỗi 429). Đang nghỉ {wait_time}s rồi thử lại (Lần {attempt + 1}/{max_retries})...")
@@ -46,29 +50,21 @@ def make_request_with_retry(url, method="get", max_retries=5, backoff_factor=3,
46
  class BasicAgent:
47
  def __init__(self):
48
  print("BasicAgent initialized.")
49
- # --- ĐOẠN CODE TEST TOKEN ---
50
- token = os.environ.get("HF_TOKEN")
51
- print(f"👉 Kiểm tra HF_TOKEN: {'✅ ĐÃ NHẬN (Độ dài: ' + str(len(token)) + ')' if token else '❌ THẤT BẠI - Đang bị rỗng (None)!'}")
52
- # ----------------------------
53
- # Setup tools
 
54
  search_tool = DuckDuckGoSearchTool()
55
  visit_tool = VisitWebpageTool()
56
 
57
- # Setup LLM sử dụng API miễn phí của Hugging Face thông qua cổng OpenAI-compatible
58
- # LƯU Ý: Đảm bảo Space của bạn có secret tên là HF_TOKEN
59
- self.model = OpenAIServerModel(
60
  model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
61
- api_base="https://api-inference.huggingface.co/v1/",
62
- api_key=os.environ.get("HF_TOKEN")
63
  )
64
 
65
- # --- GỢI Ý THÊM (Tùy chọn): Nếu mạng HF bị chậm, bạn có thể bỏ comment đoạn dưới để dùng Groq Free ---
66
- # self.model = OpenAIServerModel(
67
- # model_id="qwen-2.5-coder-32b",
68
- # api_base="https://api.groq.com/openai/v1",
69
- # api_key=os.environ.get("GROQ_API_KEY")
70
- # )
71
-
72
  # Setup CodeAgent
73
  self.agent = CodeAgent(
74
  tools=[search_tool, visit_tool],
@@ -79,7 +75,6 @@ class BasicAgent:
79
  def __call__(self, question: str, file_path: str | None = None) -> str:
80
  print(f"Agent received question (first 50 chars): {question[:50]}...")
81
 
82
- # Bổ sung chỉ dẫn về file vào prompt để agent biết dùng Python tools xử lý file
83
  prompt = question
84
  if file_path and os.path.exists(file_path):
85
  prompt += f"\n\n[LƯU Ý QUAN TRỌNG: Câu hỏi này có đính kèm một file dữ liệu. File đã được tải về máy tại đường dẫn: '{file_path}'. Hãy sử dụng code Python và các thư viện như pandas, openpyxl, PIL,... để đọc và phân tích file này nhằm tìm ra câu trả lời chính xác.]"
@@ -93,10 +88,6 @@ class BasicAgent:
93
  return f"Error: {e}"
94
 
95
  def run_and_submit_all(profile: gr.OAuthProfile | None):
96
- """
97
- Fetches all questions, downloads attachments if present, runs the BasicAgent,
98
- submits all answers, and displays the results.
99
- """
100
  space_id = os.getenv("SPACE_ID", "Imnotchis/Final_Assignment_Template")
101
  if profile:
102
  username = f"{profile.username}"
@@ -145,7 +136,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
145
  print(f"Skipping item with missing task_id or question: {item}")
146
  continue
147
 
148
- # Xử lý tải file đính kèm với hàm retry chống lỗi 429
149
  local_file_path = None
150
  if file_name and str(file_name).strip() and str(file_name) != "None":
151
  file_url = f"{api_url}/files/{task_id}"
@@ -182,7 +172,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
182
  "Submitted Answer": f"AGENT ERROR: {e}"
183
  })
184
 
185
- # Nghỉ 2 giây sau mỗi câu hỏi để tránh bị máy chủ chặn IP (Rate limit)
186
  time.sleep(2)
187
 
188
  if not answers_payload:
@@ -245,9 +235,6 @@ with gr.Blocks() as demo:
245
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc...
246
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
247
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
248
- ---
249
- **Disclaimers:**
250
- 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).
251
  """
252
  )
253
  gr.LoginButton()
 
5
  import gradio as gr
6
  import pandas as pd
7
  import requests
8
+
9
+ # --- Import thông minh chống lỗi phiên bản smolagents ---
10
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, VisitWebpageTool
11
+ try:
12
+ from smolagents import HfApiModel # Cho smolagents bản mới (1.4.0+)
13
+ except ImportError:
14
+ from smolagents import ApiModel as HfApiModel # Tự động lùi về ApiModel cho bản cũ
15
 
16
  # --- Constants ---
17
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
21
  def make_request_with_retry(url, method="get", max_retries=5, backoff_factor=3, **kwargs):
22
  """
23
  Tự động gọi lại API nếu gặp lỗi 429 (Too Many Requests) hoặc lỗi mạng ngẫu nhiên.
 
24
  """
25
  for attempt in range(max_retries):
26
  try:
 
29
  elif method.lower() == "post":
30
  response = requests.post(url, **kwargs)
31
 
 
32
  if response.status_code == 429:
33
  wait_time = backoff_factor * (2 ** attempt)
34
  print(f"⚠️ Máy chủ đang quá tải (Lỗi 429). Đang nghỉ {wait_time}s rồi thử lại (Lần {attempt + 1}/{max_retries})...")
 
50
  class BasicAgent:
51
  def __init__(self):
52
  print("BasicAgent initialized.")
53
+
54
+ # Kiểm tra nhanh HF_TOKEN để tránh lỗi Missing credentials
55
+ hf_token = os.environ.get("HF_TOKEN")
56
+ if not hf_token:
57
+ print("⚠️ CẢNH BÁO: Chưa tìm thấy HF_TOKEN trong biến môi trường!")
58
+
59
  search_tool = DuckDuckGoSearchTool()
60
  visit_tool = VisitWebpageTool()
61
 
62
+ # Khởi tạo mô hình trực tiếp qua Hugging Face Inference API bằng HfApiModel
63
+ self.model = HfApiModel(
 
64
  model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
65
+ token=hf_token
 
66
  )
67
 
 
 
 
 
 
 
 
68
  # Setup CodeAgent
69
  self.agent = CodeAgent(
70
  tools=[search_tool, visit_tool],
 
75
  def __call__(self, question: str, file_path: str | None = None) -> str:
76
  print(f"Agent received question (first 50 chars): {question[:50]}...")
77
 
 
78
  prompt = question
79
  if file_path and os.path.exists(file_path):
80
  prompt += f"\n\n[LƯU Ý QUAN TRỌNG: Câu hỏi này có đính kèm một file dữ liệu. File đã được tải về máy tại đường dẫn: '{file_path}'. Hãy sử dụng code Python và các thư viện như pandas, openpyxl, PIL,... để đọc và phân tích file này nhằm tìm ra câu trả lời chính xác.]"
 
88
  return f"Error: {e}"
89
 
90
  def run_and_submit_all(profile: gr.OAuthProfile | None):
 
 
 
 
91
  space_id = os.getenv("SPACE_ID", "Imnotchis/Final_Assignment_Template")
92
  if profile:
93
  username = f"{profile.username}"
 
136
  print(f"Skipping item with missing task_id or question: {item}")
137
  continue
138
 
 
139
  local_file_path = None
140
  if file_name and str(file_name).strip() and str(file_name) != "None":
141
  file_url = f"{api_url}/files/{task_id}"
 
172
  "Submitted Answer": f"AGENT ERROR: {e}"
173
  })
174
 
175
+ # Nghỉ 2 giây sau mỗi câu hỏi để chống lỗi Rate Limit 429
176
  time.sleep(2)
177
 
178
  if not answers_payload:
 
235
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc...
236
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
237
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
 
 
 
238
  """
239
  )
240
  gr.LoginButton()