fix(offers): survive Claude rate limits (429) #6

Merged
hjess merged 1 commits from worktree-citti-arkiver-tur into main 2026-10-30 12:09:37 +01:00

32
app.py
View File

@@ -33,10 +33,12 @@ OFFERS_REFRESH_HOURS = float(os.environ.get("OFFERS_REFRESH_HOURS", "20"))
# ANTHROPIC_API_KEY + Haiku pattern). Cached per heading, so only new headings
# cost a call. Without a key, offers simply stay in German.
TRANSLATE_MODEL = os.environ.get("TRANSLATE_MODEL", "claude-haiku-5-5")
# Big batches: ~all headings in 1-2 calls, so the instruction preamble isn't
# repeated per 40 and we don't hammer the rate limit. ~22 output tokens/item,
# so 250 stays well under max_tokens=16000.
TRANSLATE_BATCH = int(os.environ.get("TRANSLATE_BATCH", "250"))
# Moderate batches keep each request's max_tokens small. OAuth/subscription
# tokens have a tight output-tokens-per-minute limit, and the API reserves
# max_tokens against it — big requests 429 fast. ~22 output tokens/item, so
# 100 items fit in max_tokens=4000 with margin. Paced + retried below.
TRANSLATE_BATCH = int(os.environ.get("TRANSLATE_BATCH", "100"))
CLAUDE_MAX_RETRIES = int(os.environ.get("CLAUDE_MAX_RETRIES", "8"))
# AI matching of the fixed list against offers (more precise than the token
# heuristic). Bump to claude-sonnet-5-5 via env for harder cases.
MATCH_MODEL = os.environ.get("MATCH_MODEL", "claude-haiku-5-5")
@@ -336,7 +338,7 @@ def _translate_batch(client, headings):
"danske produktnavne. Behold mærke-/egennavne uændret. Svar KUN med et JSON-"
'array på formen [{"i":0,"da":"..."}], ét element per linje, intet andet.\n\n'
+ numbered)
text = _claude_json(client, TRANSLATE_MODEL, 16000, prompt)
text = _claude_json(client, TRANSLATE_MODEL, 4000, prompt)
m = re.search(r"\[.*\]", text, re.DOTALL)
out = list(headings)
if not m:
@@ -366,14 +368,18 @@ def translate_missing():
except Exception as e:
app.logger.warning("citti translate: anthropic SDK unavailable: %s", e)
return 0
client = anthropic.Anthropic()
client = anthropic.Anthropic(max_retries=CLAUDE_MAX_RETRIES)
now = datetime.now(timezone.utc).isoformat()
done = 0
for i in range(0, len(todo), TRANSLATE_BATCH):
batches = range(0, len(todo), TRANSLATE_BATCH)
for n, i in enumerate(batches):
batch = todo[i:i + TRANSLATE_BATCH]
try:
das = _translate_batch(client, batch)
except Exception as e:
# Rate limit or transient error: skip this batch, keep what's done
# (translations are cached), and let the next refresh pick up the
# rest. Never abort the whole refresh over it.
app.logger.warning("citti translate batch failed: %s", e)
continue
with get_db() as c:
@@ -381,6 +387,8 @@ def translate_missing():
c.execute("INSERT OR REPLACE INTO translations(de,da,created) "
"VALUES(?,?,?)", (de, da, now))
done += len(batch)
if n + 1 < len(batches):
time.sleep(1.5) # pace to stay under the rate limit
app.logger.info("citti translate: %d headings translated", done)
return done
@@ -432,8 +440,14 @@ def match_offers_ai():
"julekalender'). Vælg det billigste ved flere ens. Returnér KUN et "
'JSON-array [{"item_key":"...","offer_id":"..."}] med de sikre match, '
"intet andet.")
client = anthropic.Anthropic()
text = _claude_json(client, MATCH_MODEL, 8000, prompt)
client = anthropic.Anthropic(max_retries=CLAUDE_MAX_RETRIES)
try:
text = _claude_json(client, MATCH_MODEL, 2000, prompt)
except Exception as e:
# Rate limit or transient error: keep the existing matches and move on,
# never fail the whole refresh over matching.
app.logger.warning("citti match failed: %s", e)
return 0
m = re.search(r"\[.*\]", text, re.DOTALL)
if not m:
app.logger.warning("citti match: unparseable response: %s", text[:200])