From bf5439f7ad0a827c6678dd0d6db839737e432100 Mon Sep 17 00:00:00 2001 From: Henrik Jess Nielsen Date: Fri, 30 Oct 2026 12:07:01 +0100 Subject: [PATCH] fix(offers): survive Claude rate limits (429) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The OAuth token works (429 = authenticated but throttled); subscription tokens have a tight output-tokens/min limit and the API reserves max_tokens against it, so the big translate calls 429'd and the error surfaced as a failed refresh. - Smaller requests: translate max_tokens 16000->4000, batch 250->100; match max_tokens 8000->2000 (less reserved OTPM per call) - Client max_retries=8 so the SDK waits out 429s (respects retry-after) - Pace 1.5s between translate batches - Matching no longer fails the whole refresh on a 429 — it keeps the existing matches; translations are cached per batch, so progress persists and the next refresh finishes the rest --- app.py | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/app.py b/app.py index 414792f..921582a 100644 --- a/app.py +++ b/app.py @@ -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]) -- 2.53.0