Skip to content

Commit 0e9e157

Browse files
authored
Merge pull request #39 from datum-cloud/fwidjaja-patch-3
Add rate limiter, to prevent API hit limit
2 parents 6f1246e + f4178ca commit 0e9e157

File tree

1 file changed

+40
-2
lines changed

1 file changed

+40
-2
lines changed

scripts/monitor_news.py

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
import os
88
import json
9+
import time
910
import anthropic
1011
from datetime import datetime, timedelta
1112
from typing import List, Dict, Any
@@ -150,6 +151,37 @@ def search_category(self, category: str, config: Dict[str, Any]) -> List[Dict[st
150151
print(f"✅ Found {len(results)} candidates in {category}")
151152
return results
152153

154+
except anthropic.RateLimitError as e:
155+
print(f"⚠️ Rate limit hit for {category}, waiting 10 seconds...")
156+
time.sleep(10)
157+
# Retry once
158+
try:
159+
response = self.client.messages.create(
160+
model="claude-sonnet-4-20250514",
161+
max_tokens=4096,
162+
tools=[{
163+
"type": "web_search_20250305",
164+
"name": "web_search"
165+
}],
166+
messages=[{
167+
"role": "user",
168+
"content": prompt
169+
}]
170+
)
171+
results = []
172+
for block in response.content:
173+
if block.type == "text":
174+
text = block.text.strip()
175+
if text.startswith('[') and text.endswith(']'):
176+
try:
177+
results = json.loads(text)
178+
except json.JSONDecodeError:
179+
pass
180+
print(f"✅ Found {len(results)} candidates in {category} (retry)")
181+
return results
182+
except Exception as retry_error:
183+
print(f"❌ Retry failed for {category}: {retry_error}")
184+
return []
153185
except Exception as e:
154186
print(f"❌ Error searching {category}: {e}")
155187
return []
@@ -173,10 +205,16 @@ def run_daily_monitor(self) -> Dict[str, Any]:
173205

174206
all_candidates = []
175207

176-
# Search each category
177-
for category, config in CATEGORIES.items():
208+
# Search each category with rate limiting
209+
for i, (category, config) in enumerate(CATEGORIES.items()):
178210
candidates = self.search_category(category, config)
179211
all_candidates.extend(candidates)
212+
213+
# Rate limiting: wait between requests to avoid hitting API limits
214+
# 30k tokens/min limit = need ~2 second delay between calls
215+
if i < len(CATEGORIES) - 1: # Don't sleep after last one
216+
print(f"⏱️ Rate limiting: waiting 3 seconds...")
217+
time.sleep(3)
180218

181219
# Deduplicate
182220
unique_candidates = self.deduplicate_against_existing(all_candidates)

0 commit comments

Comments
 (0)