Qscar KIM commited on
Commit
7c2f842
ยท
1 Parent(s): 82a263a

update codes

Browse files
Files changed (1) hide show
  1. app.py +18 -37
app.py CHANGED
@@ -10,45 +10,32 @@ from smolagents import CodeAgent, LiteLLMModel, DuckDuckGoSearchTool, VisitWebpa
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,7 +45,7 @@ class BasicAgent:
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:
@@ -73,8 +60,8 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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,17 +73,15 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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,12 +102,10 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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...")
124
  for item in questions_data:
125
- time.sleep(5.0)
126
  task_id = item.get("task_id")
127
  question_text = item.get("question")
128
  if not task_id or question_text is None:
@@ -140,12 +123,10 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
140
  print("Agent did not produce any answers to submit.")
141
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
142
 
143
- # 4. Prepare Submission
144
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
145
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
146
  print(status_update)
147
 
148
- # 5. Submit
149
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
150
  try:
151
  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
  # --- 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. ๊ธฐ์กด์— ์ •์ƒ ๊ตฌ๋™์ด ํ™•์ธ๋œ ๊ฒ€์ฆ๋œ ๋ชจ๋ธ ์‹๋ณ„์ž๋กœ ์›์ƒ ๋ณต๊ตฌ
20
+ base_model = LiteLLMModel(
21
  model_id="gemini/gemini-2.5-flash",
22
+ api_key=gemini_key
 
23
  )
24
+
25
+ # 2. ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์ถฉ๋Œ์„ ๋ง‰๊ธฐ ์œ„ํ•ด ๋ชจ๋ธ ํ˜ธ์ถœ ์ž์ฒด๋ฅผ ์ธํ„ฐ์…‰ํŠธํ•˜์—ฌ 10์ดˆ ํŽ˜์ด์‹ฑ(Pacing) ๊ฐ•์ œ ์ฃผ์ž…
26
+ original_call = base_model.__call__
27
+ def paced_call(*args, **kwargs):
28
+ print("โณ [RPM Guard] Free tier burst protection sleep (10s)...")
29
+ time.sleep(10.0)
30
+ return original_call(*args, **kwargs)
31
+
32
+ base_model.__call__ = paced_call
33
+ self.model = base_model
34
 
35
  self.search_tool = DuckDuckGoSearchTool()
36
  self.visit_tool = VisitWebpageTool()
37
 
38
+ # 45์  ๋ฒ ์ด์Šค๋ผ์ธ ์•„ํ‚คํ…์ฒ˜ ๊ทœ๊ฒฉ ๊ณ ์ •
39
  self.alfred = CodeAgent(
40
  tools=[self.search_tool, self.visit_tool],
41
  model=self.model,
 
45
 
46
  def __call__(self, question: str) -> str:
47
  try:
48
+ # ๋ฌธ์ œ์™€ ๋ฌธ์ œ ์‚ฌ์ด์˜ ์™„์ „ํ•œ ์„ธ์…˜ ์ดˆ๊ธฐํ™”๋ฅผ ์œ„ํ•ด 5์ดˆ ์ถ”๊ฐ€ ๋Œ€๊ธฐ
49
  time.sleep(5.0)
50
  result = self.alfred.run(question)
51
  if result is None:
 
60
  Fetches all questions, runs the BasicAgent on them, submits all answers,
61
  and displays the results.
62
  """
63
+ space_id = os.getenv("SPACE_ID")
64
+
65
  if profile:
66
  username= f"{profile.username}"
67
  print(f"User logged in: {username}")
 
73
  questions_url = f"{api_url}/questions"
74
  submit_url = f"{api_url}/submit"
75
 
 
76
  try:
77
  agent = BasicAgent()
78
  except Exception as e:
79
  print(f"Error instantiating agent: {e}")
80
  return f"Error initializing agent: {e}", None
81
+
82
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
83
  print(agent_code)
84
 
 
85
  print(f"Fetching questions from: {questions_url}")
86
  try:
87
  response = requests.get(questions_url, timeout=15)
 
102
  print(f"An unexpected error occurred fetching questions: {e}")
103
  return f"An unexpected error occurred fetching questions: {e}", None
104
 
 
105
  results_log = []
106
  answers_payload = []
107
  print(f"Running agent on {len(questions_data)} questions...")
108
  for item in questions_data:
 
109
  task_id = item.get("task_id")
110
  question_text = item.get("question")
111
  if not task_id or question_text is None:
 
123
  print("Agent did not produce any answers to submit.")
124
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
125
 
 
126
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
127
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
128
  print(status_update)
129
 
 
130
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
131
  try:
132
  response = requests.post(submit_url, json=submission_data, timeout=60)