Imnotchis commited on
Commit
15066dc
·
verified ·
1 Parent(s): 156e483

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -11
app.py CHANGED
@@ -4,13 +4,63 @@ import requests
4
  import inspect
5
  import pandas as pd
6
  from pathlib import Path
7
- from smolagents import CodeAgent, OpenAIServerModel, DuckDuckGoSearchTool, VisitWebpageTool
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  # --- Constants ---
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
  DOWNLOADS_DIR = Path("./tmp_downloads")
12
  DOWNLOADS_DIR.mkdir(parents=True, exist_ok=True)
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  # --- Basic Agent Definition ---
15
  class BasicAgent:
16
  def __init__(self):
@@ -80,8 +130,8 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
80
  # 2. Fetch Questions
81
  print(f"Fetching questions from: {questions_url}")
82
  try:
83
- response = requests.get(questions_url, timeout=15)
84
- response.raise_for_status()
85
  questions_data = response.json()
86
  if not questions_data:
87
  print("Fetched questions list is empty.")
@@ -104,14 +154,15 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
104
  print(f"Skipping item with missing task_id or question: {item}")
105
  continue
106
 
107
- # XỬ LÝ TẢI FILE ĐÍNH KÈM (Cải tiến giúp ăn trọn điểm các câu hỏi multimodal/Excel)
108
  local_file_path = None
109
  if file_name and str(file_name).strip() and str(file_name) != "None":
110
  file_url = f"{api_url}/files/{task_id}"
111
  local_file_path = str(DOWNLOADS_DIR / file_name)
112
  print(f"Downloading attachment '{file_name}' from {file_url}...")
113
  try:
114
- file_resp = requests.get(file_url, timeout=30)
 
115
  if file_resp.status_code == 200:
116
  with open(local_file_path, "wb") as f:
117
  f.write(file_resp.content)
@@ -140,10 +191,9 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
140
  "Attachment": file_name if file_name else "None",
141
  "Submitted Answer": f"AGENT ERROR: {e}"
142
  })
143
-
144
- if not answers_payload:
145
- print("Agent did not produce any answers to submit.")
146
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
147
 
148
  # 4. Prepare Submission
149
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
@@ -153,8 +203,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
153
  # 5. Submit
154
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
155
  try:
156
- response = requests.post(submit_url, json=submission_data, timeout=60)
157
- response.raise_for_status()
158
  result_data = response.json()
159
  final_status = (
160
  f"Submission Successful!\n"
 
4
  import inspect
5
  import pandas as pd
6
  from pathlib import Path
7
+ import time
8
+ from smolagents import CodeAgent, HfApiModel, DuckDuckGoSearchTool, VisitWebpageTool # Thay OpenAIServerModel bằng HfApiModel
9
+
10
+ # ... trong class BasicAgent:
11
+ def __init__(self):
12
+ print("BasicAgent initialized.")
13
+ search_tool = DuckDuckGoSearchTool()
14
+ visit_tool = VisitWebpageTool()
15
+
16
+ # Sử dụng API miễn phí của Hugging Face
17
+ self.model = HfApiModel(
18
+ model_id="Qwen/Qwen2.5-Coder-32B-Instruct", # Hoặc "meta-llama/Llama-3.3-70B-Instruct"
19
+ token=os.environ.get("HF_TOKEN")
20
+ )
21
+
22
+ self.agent = CodeAgent(
23
+ tools=[search_tool, visit_tool],
24
+ model=self.model,
25
+ add_base_tools=True
26
+ )
27
 
28
  # --- Constants ---
29
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
30
  DOWNLOADS_DIR = Path("./tmp_downloads")
31
  DOWNLOADS_DIR.mkdir(parents=True, exist_ok=True)
32
 
33
+ def make_request_with_retry(url, method="get", max_retries=5, backoff_factor=3, **kwargs):
34
+ """
35
+ 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.
36
+ Thời gian chờ sẽ tăng theo cấp số nhân: 3s -> 6s -> 12s -> 24s...
37
+ """
38
+ for attempt in range(max_retries):
39
+ try:
40
+ if method.lower() == "get":
41
+ response = requests.get(url, **kwargs)
42
+ elif method.lower() == "post":
43
+ response = requests.post(url, **kwargs)
44
+
45
+ # Xử lý riêng khi bị máy chủ giới hạn tần suất (429)
46
+ if response.status_code == 429:
47
+ wait_time = backoff_factor * (2 ** attempt)
48
+ 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})...")
49
+ time.sleep(wait_time)
50
+ continue
51
+
52
+ response.raise_for_status()
53
+ return response
54
+ except requests.exceptions.RequestException as e:
55
+ # Nếu là lần thử cuối cùng thì mới báo lỗi ra ngoài
56
+ if attempt == max_retries - 1:
57
+ raise e
58
+ wait_time = backoff_factor * (2 ** attempt)
59
+ print(f"⚠️ Lỗi kết nối ({e}). Thử lại sau {wait_time}s...")
60
+ time.sleep(wait_time)
61
+
62
+ raise Exception("Đã vượt quá số lần kết nối lại tối đa tới máy chủ.")
63
+
64
  # --- Basic Agent Definition ---
65
  class BasicAgent:
66
  def __init__(self):
 
130
  # 2. Fetch Questions
131
  print(f"Fetching questions from: {questions_url}")
132
  try:
133
+ # Sử dụng hàm retry thay cho requests.get thông thường
134
+ response = make_request_with_retry(questions_url, timeout=30)
135
  questions_data = response.json()
136
  if not questions_data:
137
  print("Fetched questions list is empty.")
 
154
  print(f"Skipping item with missing task_id or question: {item}")
155
  continue
156
 
157
+ # XỬ LÝ TẢI FILE ĐÍNH KÈM (Đã sửa lại dùng make_request_with_retry)
158
  local_file_path = None
159
  if file_name and str(file_name).strip() and str(file_name) != "None":
160
  file_url = f"{api_url}/files/{task_id}"
161
  local_file_path = str(DOWNLOADS_DIR / file_name)
162
  print(f"Downloading attachment '{file_name}' from {file_url}...")
163
  try:
164
+ # DÙNG RETRY Ở ĐÂY ĐỂ TRÁNH LỖI 429 KHI TẢI FILE:
165
+ file_resp = make_request_with_retry(file_url, timeout=45)
166
  if file_resp.status_code == 200:
167
  with open(local_file_path, "wb") as f:
168
  f.write(file_resp.content)
 
191
  "Attachment": file_name if file_name else "None",
192
  "Submitted Answer": f"AGENT ERROR: {e}"
193
  })
194
+
195
+ # BỔ SUNG NHỊP NGHỈ QUAN TRỌNG Ở CUỐI VÒNG LẶP:
196
+ time.sleep(2)
 
197
 
198
  # 4. Prepare Submission
199
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
 
203
  # 5. Submit
204
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
205
  try:
206
+ response = make_request_with_retry(submit_url, method="post", json=submission_data, timeout=90)
 
207
  result_data = response.json()
208
  final_status = (
209
  f"Submission Successful!\n"