Qscar KIM commited on
Commit
a4cb48c
ยท
1 Parent(s): bdc0645

update codes

Browse files
Files changed (1) hide show
  1. app.py +37 -9
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
- # ์ผ์ผ ์ฟผํ„ฐ๊ฐ€ 1,500ํšŒ๋กœ ๊ฐ€์žฅ ๋„‰๋„‰ํ•œ 2.0-flash ๋ฐฐ์ •
20
- # requests_per_minute ์ธ์ž๋ฅผ ํ†ตํ•ด ํ”„๋ ˆ์ž„์›Œํฌ๊ฐ€ ์•Œ์•„์„œ ์•ˆ์ „ ๊ฐ€๋“œ๋ ˆ์ผ์„ ์žก๋„๋ก ์„ค์ •
21
- self.model = LiteLLMModel(
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
- # 45์  ๋ฒ ์ด์Šค๋ผ์ธ์˜ ๋‹ค๋‹จ๊ณ„ ๊ณ„ํš ์ˆ˜๋ฆฝ ๋ฐ ๋‚ด์žฅ ์ธํ„ฐํ”„๋ฆฌํ„ฐ ํŒŒ๋ผ๋ฏธํ„ฐ ์™„์ „ ๊ณ ์ •
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
- space_id = os.getenv("SPACE_ID")
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)