s1144662 commited on
Commit
1288551
·
verified ·
1 Parent(s): 9df76c7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -14
app.py CHANGED
@@ -26,7 +26,9 @@ def perform_search(query: str) -> str:
26
 
27
  print(f"🕵️ Searching: {query[:50]}...")
28
  try:
29
- time.sleep(random.uniform(2.0, 4.0)) # 增加延遲
 
 
30
  with DDGS() as ddgs:
31
  results = list(ddgs.text(query, max_results=2, backend="lite"))
32
 
@@ -43,7 +45,7 @@ class GroqClient:
43
  def __init__(self):
44
  self.api_key = os.getenv("GROQ_API_KEY")
45
 
46
- def query(self, messages, model, max_retries=5): # 增加重試次數到 5 次
47
  """發送請求給 Groq,包含超強自動重試機制"""
48
  if not self.api_key:
49
  return "Error: No API Key"
@@ -54,7 +56,6 @@ class GroqClient:
54
  }
55
 
56
  # 針對這門課的特殊要求:強制簡潔
57
- # 這是拿分的關鍵,避免模型講廢話
58
  system_instruction = {
59
  "role": "system",
60
  "content": "You are taking a test. Provide ONLY the exact answer. No sentences, no punctuation, no explanations. Example: if the answer is 5, output '5'. If the answer is Paris, output 'Paris'."
@@ -67,7 +68,7 @@ class GroqClient:
67
  "model": model,
68
  "messages": final_messages,
69
  "temperature": 0.1,
70
- "max_tokens": 100 # 限制回答長度
71
  }
72
 
73
  for attempt in range(max_retries):
@@ -77,14 +78,13 @@ class GroqClient:
77
  # 如果成功
78
  if response.status_code == 200:
79
  content = response.json()['choices'][0]['message']['content'].strip()
80
- # 移除最後的句號 (常見錯誤)
81
  if content.endswith('.'):
82
  content = content[:-1]
83
  return content
84
 
85
  # 如果遇到 429 (太快了),休息很久再試
86
  if response.status_code == 429:
87
- wait_time = (attempt + 1) * 20 # 20s, 40s, 60s, 80s, 100s
88
  print(f"⚠️ Rate limit (429). Waiting {wait_time}s... (Attempt {attempt+1}/{max_retries})")
89
  time.sleep(wait_time)
90
  continue
@@ -160,21 +160,25 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
160
  # 核心:解題
161
  ans = solve_question(q, client)
162
 
163
- print(f"✅ Answer: {ans}") # 在 Log 顯示答案確認
164
 
165
  answers.append({"task_id": tid, "submitted_answer": ans})
166
  logs.append({"Task": tid, "Answer": str(ans)[:100]})
167
 
168
- # !!! 強制休息 10 秒 !!!
169
- # 這是為了確保下一題不會立刻觸發 429
170
- print("💤 Sleeping 10s to respect rate limits...")
171
- time.sleep(10)
 
 
 
 
172
 
173
  try:
174
  print("Submitting...")
175
  res = requests.post(f"{DEFAULT_API_URL}/submit", json={
176
  "username": profile.username,
177
- "agent_code": "https://huggingface.co/spaces/test/test",
178
  "answers": answers
179
  }, timeout=60)
180
 
@@ -185,8 +189,9 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
185
  except Exception as e:
186
  return f"Submit error: {str(e)}", pd.DataFrame(logs)
187
 
188
- with gr.Blocks(title="Final Agent (Anti-429 v2)") as demo:
189
- gr.Markdown("# 🚀 Final Agent (Strict Format + Slow Mode)")
 
190
  with gr.Row():
191
  gr.LoginButton()
192
  btn = gr.Button("Run Evaluation", variant="primary")
 
26
 
27
  print(f"🕵️ Searching: {query[:50]}...")
28
  try:
29
+ # 【微調】這裡也保留一點隨機性,模擬真人操作
30
+ time.sleep(random.uniform(3.0, 5.0))
31
+
32
  with DDGS() as ddgs:
33
  results = list(ddgs.text(query, max_results=2, backend="lite"))
34
 
 
45
  def __init__(self):
46
  self.api_key = os.getenv("GROQ_API_KEY")
47
 
48
+ def query(self, messages, model, max_retries=5): # 維持 5 次重試
49
  """發送請求給 Groq,包含超強自動重試機制"""
50
  if not self.api_key:
51
  return "Error: No API Key"
 
56
  }
57
 
58
  # 針對這門課的特殊要求:強制簡潔
 
59
  system_instruction = {
60
  "role": "system",
61
  "content": "You are taking a test. Provide ONLY the exact answer. No sentences, no punctuation, no explanations. Example: if the answer is 5, output '5'. If the answer is Paris, output 'Paris'."
 
68
  "model": model,
69
  "messages": final_messages,
70
  "temperature": 0.1,
71
+ "max_tokens": 100
72
  }
73
 
74
  for attempt in range(max_retries):
 
78
  # 如果成功
79
  if response.status_code == 200:
80
  content = response.json()['choices'][0]['message']['content'].strip()
 
81
  if content.endswith('.'):
82
  content = content[:-1]
83
  return content
84
 
85
  # 如果遇到 429 (太快了),休息很久再試
86
  if response.status_code == 429:
87
+ wait_time = (attempt + 1) * 20 # 20s, 40s, 60s...
88
  print(f"⚠️ Rate limit (429). Waiting {wait_time}s... (Attempt {attempt+1}/{max_retries})")
89
  time.sleep(wait_time)
90
  continue
 
160
  # 核心:解題
161
  ans = solve_question(q, client)
162
 
163
+ print(f"✅ Answer: {ans}")
164
 
165
  answers.append({"task_id": tid, "submitted_answer": ans})
166
  logs.append({"Task": tid, "Answer": str(ans)[:100]})
167
 
168
+ # ======================================================
169
+ # 【修改重點】:智慧型隨機休息,避免 429 Rate Limit
170
+ # 從原本固定的 10 秒,改成 25 ~ 45 秒隨機
171
+ # ======================================================
172
+ sleep_time = random.uniform(25, 45)
173
+ print(f"💤 Sleeping {sleep_time:.2f}s to avoid rate limits (429)...")
174
+ time.sleep(sleep_time)
175
+ # ======================================================
176
 
177
  try:
178
  print("Submitting...")
179
  res = requests.post(f"{DEFAULT_API_URL}/submit", json={
180
  "username": profile.username,
181
+ "agent_code": "https://huggingface.co/spaces/test/test", # 這裡可以換成你的 Space 連結
182
  "answers": answers
183
  }, timeout=60)
184
 
 
189
  except Exception as e:
190
  return f"Submit error: {str(e)}", pd.DataFrame(logs)
191
 
192
+ with gr.Blocks(title="Final Agent (Safe Mode)") as demo:
193
+ gr.Markdown("# 🚀 Final Agent (Anti-429 Safe Mode)")
194
+ gr.Markdown("此版本已增加隨機延遲 (25s~45s) 以避免搜尋引擎封鎖。執行時間會較長,請耐心等待。")
195
  with gr.Row():
196
  gr.LoginButton()
197
  btn = gr.Button("Run Evaluation", variant="primary")