Spaces:
Sleeping
Sleeping
Qscar KIM commited on
Commit ยท
a4cb48c
1
Parent(s): bdc0645
update codes
Browse files
app.py
CHANGED
|
@@ -10,24 +10,45 @@ from smolagents import CodeAgent, LiteLLMModel, DuckDuckGoSearchTool, VisitWebpa
|
|
| 10 |
# --- Constants ---
|
| 11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
# --- Basic Agent Definition ---
|
| 14 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 15 |
class BasicAgent:
|
| 16 |
def __init__(self):
|
| 17 |
gemini_key = os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY")
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
model_id="gemini/gemini-2.0-flash",
|
| 23 |
api_key=gemini_key,
|
| 24 |
-
requests_per_minute=6
|
| 25 |
)
|
| 26 |
|
| 27 |
self.search_tool = DuckDuckGoSearchTool()
|
| 28 |
self.visit_tool = VisitWebpageTool()
|
| 29 |
|
| 30 |
-
#
|
| 31 |
self.alfred = CodeAgent(
|
| 32 |
tools=[self.search_tool, self.visit_tool],
|
| 33 |
model=self.model,
|
|
@@ -37,6 +58,8 @@ class BasicAgent:
|
|
| 37 |
|
| 38 |
def __call__(self, question: str) -> str:
|
| 39 |
try:
|
|
|
|
|
|
|
| 40 |
result = self.alfred.run(question)
|
| 41 |
if result is None:
|
| 42 |
return "unknown"
|
|
@@ -50,8 +73,8 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 50 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 51 |
and displays the results.
|
| 52 |
"""
|
| 53 |
-
|
| 54 |
-
|
| 55 |
if profile:
|
| 56 |
username= f"{profile.username}"
|
| 57 |
print(f"User logged in: {username}")
|
|
@@ -63,15 +86,17 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 63 |
questions_url = f"{api_url}/questions"
|
| 64 |
submit_url = f"{api_url}/submit"
|
| 65 |
|
|
|
|
| 66 |
try:
|
| 67 |
agent = BasicAgent()
|
| 68 |
except Exception as e:
|
| 69 |
print(f"Error instantiating agent: {e}")
|
| 70 |
return f"Error initializing agent: {e}", None
|
| 71 |
-
|
| 72 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 73 |
print(agent_code)
|
| 74 |
|
|
|
|
| 75 |
print(f"Fetching questions from: {questions_url}")
|
| 76 |
try:
|
| 77 |
response = requests.get(questions_url, timeout=15)
|
|
@@ -92,6 +117,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 92 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 93 |
return f"An unexpected error occurred fetching questions: {e}", None
|
| 94 |
|
|
|
|
| 95 |
results_log = []
|
| 96 |
answers_payload = []
|
| 97 |
print(f"Running agent on {len(questions_data)} questions...")
|
|
@@ -113,10 +139,12 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 113 |
print("Agent did not produce any answers to submit.")
|
| 114 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 115 |
|
|
|
|
| 116 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 117 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 118 |
print(status_update)
|
| 119 |
|
|
|
|
| 120 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 121 |
try:
|
| 122 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
|
|
|
| 10 |
# --- Constants ---
|
| 11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 12 |
|
| 13 |
+
# --- RPM Guard: ํ๋ฆฌ ํฐ์ด ๋ฒ์คํธ ๋ฐฉ์ดํ ์ปค์คํ
๋ชจ๋ธ ์ด๋ํฐ ---
|
| 14 |
+
class PacedGeminiModel(LiteLLMModel):
|
| 15 |
+
def __init__(self, *args, **kwargs):
|
| 16 |
+
super().__init__(*args, **kwargs)
|
| 17 |
+
self.last_call_time = 0.0
|
| 18 |
+
self.min_interval = 10 # 15 RPM ์ ํ์ ์์ ํ๊ฒ ํํผํ๊ธฐ ์ํ ์ต์ ์ด ๋จ์ ๊ฐ๊ฒฉ ๊ณ ์
|
| 19 |
+
|
| 20 |
+
def __call__(self, *args, **kwargs):
|
| 21 |
+
# ๋ง์ง๋ง API ํธ์ถ ์์ ์ผ๋ก๋ถํฐ ๊ฒฝ๊ณผํ ์๊ฐ์ ๊ณ์ฐํ์ฌ ์ ๋ฐ ํ์ด์ฑ ๋ฝ(Lock) ๊ฐ๋
|
| 22 |
+
now = time.time()
|
| 23 |
+
elapsed = now - self.last_call_time
|
| 24 |
+
if elapsed < self.min_interval:
|
| 25 |
+
sleep_needed = self.min_interval - elapsed
|
| 26 |
+
time.sleep(sleep_needed)
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
response = super().__call__(*args, **kwargs)
|
| 30 |
+
return response
|
| 31 |
+
finally:
|
| 32 |
+
# ์คํจํ๋ ์ฑ๊ณตํ๋ ํ์์คํฌํ๋ฅผ ๊ฐฑ์ ํ์ฌ ์ฐ์ ๋ฆฌํธ๋ผ์ด๋ก ์ธํ ๋ฒ์คํธ ํญ์ฆ ์ฐจ๋จ
|
| 33 |
+
self.last_call_time = time.time()
|
| 34 |
+
|
| 35 |
# --- Basic Agent Definition ---
|
| 36 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 37 |
class BasicAgent:
|
| 38 |
def __init__(self):
|
| 39 |
gemini_key = os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY")
|
| 40 |
|
| 41 |
+
# ๊ธฐ๋ณธ LiteLLMModel ๋์ ์ ๋ฐ ๊ฐ์๊ธฐ๊ฐ ๋ด์ฅ๋ PacedGeminiModel๋ก ๋ฐ์ธ๋ฉ
|
| 42 |
+
self.model = PacedGeminiModel(
|
| 43 |
+
model_id="gemini/gemini-2.5-flash",
|
|
|
|
| 44 |
api_key=gemini_key,
|
| 45 |
+
requests_per_minute=6
|
| 46 |
)
|
| 47 |
|
| 48 |
self.search_tool = DuckDuckGoSearchTool()
|
| 49 |
self.visit_tool = VisitWebpageTool()
|
| 50 |
|
| 51 |
+
# ๊ณํ ์ฃผ๊ธฐ ๊ฐ๋ ๋ฐ ํด ๊ฐ๋ฐฉ ๋ฐ์ธ๋ฉ
|
| 52 |
self.alfred = CodeAgent(
|
| 53 |
tools=[self.search_tool, self.visit_tool],
|
| 54 |
model=self.model,
|
|
|
|
| 58 |
|
| 59 |
def __call__(self, question: str) -> str:
|
| 60 |
try:
|
| 61 |
+
# ์ฐ์๋ ๋ฌธ์ ํ์ด ์ฌ์ด์๋ ํ๋ฆฌ ํฐ์ด ๊ฒ์ดํธ์จ์ด๊ฐ ํด์ํ ์ ์๋๋ก 5์ด ์ ์ฒ๋ฆฌ ๋๊ธฐ
|
| 62 |
+
time.sleep(5.0)
|
| 63 |
result = self.alfred.run(question)
|
| 64 |
if result is None:
|
| 65 |
return "unknown"
|
|
|
|
| 73 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 74 |
and displays the results.
|
| 75 |
"""
|
| 76 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 77 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 78 |
if profile:
|
| 79 |
username= f"{profile.username}"
|
| 80 |
print(f"User logged in: {username}")
|
|
|
|
| 86 |
questions_url = f"{api_url}/questions"
|
| 87 |
submit_url = f"{api_url}/submit"
|
| 88 |
|
| 89 |
+
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 90 |
try:
|
| 91 |
agent = BasicAgent()
|
| 92 |
except Exception as e:
|
| 93 |
print(f"Error instantiating agent: {e}")
|
| 94 |
return f"Error initializing agent: {e}", None
|
| 95 |
+
# 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)
|
| 96 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 97 |
print(agent_code)
|
| 98 |
|
| 99 |
+
# 2. Fetch Questions
|
| 100 |
print(f"Fetching questions from: {questions_url}")
|
| 101 |
try:
|
| 102 |
response = requests.get(questions_url, timeout=15)
|
|
|
|
| 117 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 118 |
return f"An unexpected error occurred fetching questions: {e}", None
|
| 119 |
|
| 120 |
+
# 3. Run your Agent
|
| 121 |
results_log = []
|
| 122 |
answers_payload = []
|
| 123 |
print(f"Running agent on {len(questions_data)} questions...")
|
|
|
|
| 139 |
print("Agent did not produce any answers to submit.")
|
| 140 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 141 |
|
| 142 |
+
# 4. Prepare Submission
|
| 143 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 144 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 145 |
print(status_update)
|
| 146 |
|
| 147 |
+
# 5. Submit
|
| 148 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 149 |
try:
|
| 150 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|