Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,29 +1,11 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
-
import requests
|
| 4 |
import inspect
|
| 5 |
-
import pandas as pd
|
| 6 |
from pathlib import Path
|
| 7 |
-
import
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 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"
|
|
@@ -52,7 +34,6 @@ def make_request_with_retry(url, method="get", max_retries=5, backoff_factor=3,
|
|
| 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)
|
|
@@ -60,7 +41,7 @@ def make_request_with_retry(url, method="get", max_retries=5, backoff_factor=3,
|
|
| 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):
|
|
@@ -69,12 +50,11 @@ class BasicAgent:
|
|
| 69 |
search_tool = DuckDuckGoSearchTool()
|
| 70 |
visit_tool = VisitWebpageTool()
|
| 71 |
|
| 72 |
-
# Setup LLM
|
| 73 |
-
#
|
| 74 |
-
self.model =
|
| 75 |
-
model_id="
|
| 76 |
-
|
| 77 |
-
api_key=os.environ.get("OPENROUTER_API_KEY")
|
| 78 |
)
|
| 79 |
|
| 80 |
# Setup CodeAgent
|
|
@@ -130,7 +110,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 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:
|
|
@@ -154,14 +133,13 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 154 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 155 |
continue
|
| 156 |
|
| 157 |
-
#
|
| 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:
|
|
@@ -191,9 +169,13 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 191 |
"Attachment": file_name if file_name else "None",
|
| 192 |
"Submitted Answer": f"AGENT ERROR: {e}"
|
| 193 |
})
|
| 194 |
-
|
| 195 |
-
#
|
| 196 |
time.sleep(2)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
|
| 198 |
# 4. Prepare Submission
|
| 199 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
|
|
|
| 1 |
import os
|
| 2 |
+
import time
|
|
|
|
| 3 |
import inspect
|
|
|
|
| 4 |
from pathlib import Path
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import requests
|
| 8 |
+
from smolagents import CodeAgent, HfApiModel, DuckDuckGoSearchTool, VisitWebpageTool
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
# --- Constants ---
|
| 11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
|
|
| 34 |
response.raise_for_status()
|
| 35 |
return response
|
| 36 |
except requests.exceptions.RequestException as e:
|
|
|
|
| 37 |
if attempt == max_retries - 1:
|
| 38 |
raise e
|
| 39 |
wait_time = backoff_factor * (2 ** attempt)
|
|
|
|
| 41 |
time.sleep(wait_time)
|
| 42 |
|
| 43 |
raise Exception("Đã vượt quá số lần kết nối lại tối đa tới máy chủ.")
|
| 44 |
+
|
| 45 |
# --- Basic Agent Definition ---
|
| 46 |
class BasicAgent:
|
| 47 |
def __init__(self):
|
|
|
|
| 50 |
search_tool = DuckDuckGoSearchTool()
|
| 51 |
visit_tool = VisitWebpageTool()
|
| 52 |
|
| 53 |
+
# Setup LLM sử dụng API miễn phí của Hugging Face (Không tốn tiền)
|
| 54 |
+
# Lưu ý: Cần thêm secret HF_TOKEN trong cài đặt Space
|
| 55 |
+
self.model = HfApiModel(
|
| 56 |
+
model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
|
| 57 |
+
token=os.environ.get("HF_TOKEN")
|
|
|
|
| 58 |
)
|
| 59 |
|
| 60 |
# Setup CodeAgent
|
|
|
|
| 110 |
# 2. Fetch Questions
|
| 111 |
print(f"Fetching questions from: {questions_url}")
|
| 112 |
try:
|
|
|
|
| 113 |
response = make_request_with_retry(questions_url, timeout=30)
|
| 114 |
questions_data = response.json()
|
| 115 |
if not questions_data:
|
|
|
|
| 133 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 134 |
continue
|
| 135 |
|
| 136 |
+
# Xử lý tải file đính kèm với hàm retry chống lỗi 429
|
| 137 |
local_file_path = None
|
| 138 |
if file_name and str(file_name).strip() and str(file_name) != "None":
|
| 139 |
file_url = f"{api_url}/files/{task_id}"
|
| 140 |
local_file_path = str(DOWNLOADS_DIR / file_name)
|
| 141 |
print(f"Downloading attachment '{file_name}' from {file_url}...")
|
| 142 |
try:
|
|
|
|
| 143 |
file_resp = make_request_with_retry(file_url, timeout=45)
|
| 144 |
if file_resp.status_code == 200:
|
| 145 |
with open(local_file_path, "wb") as f:
|
|
|
|
| 169 |
"Attachment": file_name if file_name else "None",
|
| 170 |
"Submitted Answer": f"AGENT ERROR: {e}"
|
| 171 |
})
|
| 172 |
+
|
| 173 |
+
# Nghỉ 2 giây sau mỗi câu hỏi để tránh bị máy chủ chặn IP (Rate limit)
|
| 174 |
time.sleep(2)
|
| 175 |
+
|
| 176 |
+
if not answers_payload:
|
| 177 |
+
print("Agent did not produce any answers to submit.")
|
| 178 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 179 |
|
| 180 |
# 4. Prepare Submission
|
| 181 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|