Compare commits

...

2 Commits

Author SHA1 Message Date
90ed399cd9 Merge pull request 'fix(offers): survive Claude rate limits (429)' (#6) from worktree-citti-arkiver-tur into main
All checks were successful
Build and Deploy citti / build-and-deploy (push) Successful in 45s
Reviewed-on: #6
2026-10-30 12:09:37 +01:00
Henrik Jess Nielsen
bf5439f7ad fix(offers): survive Claude rate limits (429)
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
2026-10-30 12:07:01 +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 # ANTHROPIC_API_KEY + Haiku pattern). Cached per heading, so only new headings
# cost a call. Without a key, offers simply stay in German. # cost a call. Without a key, offers simply stay in German.
TRANSLATE_MODEL = os.environ.get("TRANSLATE_MODEL", "claude-haiku-5-5") 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 # Moderate batches keep each request's max_tokens small. OAuth/subscription
# repeated per 40 and we don't hammer the rate limit. ~22 output tokens/item, # tokens have a tight output-tokens-per-minute limit, and the API reserves
# so 250 stays well under max_tokens=16000. # max_tokens against it — big requests 429 fast. ~22 output tokens/item, so
TRANSLATE_BATCH = int(os.environ.get("TRANSLATE_BATCH", "250")) # 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 # 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. # heuristic). Bump to claude-sonnet-5-5 via env for harder cases.
MATCH_MODEL = os.environ.get("MATCH_MODEL", "claude-haiku-5-5") 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-" "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' 'array på formen [{"i":0,"da":"..."}], ét element per linje, intet andet.\n\n'
+ numbered) + numbered)
text = _claude_json(client, TRANSLATE_MODEL, 16000, prompt) text = _claude_json(client, TRANSLATE_MODEL, 4000, prompt)
m = re.search(r"\[.*\]", text, re.DOTALL) m = re.search(r"\[.*\]", text, re.DOTALL)
out = list(headings) out = list(headings)
if not m: if not m:
@@ -366,14 +368,18 @@ def translate_missing():
except Exception as e: except Exception as e:
app.logger.warning("citti translate: anthropic SDK unavailable: %s", e) app.logger.warning("citti translate: anthropic SDK unavailable: %s", e)
return 0 return 0
client = anthropic.Anthropic() client = anthropic.Anthropic(max_retries=CLAUDE_MAX_RETRIES)
now = datetime.now(timezone.utc).isoformat() now = datetime.now(timezone.utc).isoformat()
done = 0 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] batch = todo[i:i + TRANSLATE_BATCH]
try: try:
das = _translate_batch(client, batch) das = _translate_batch(client, batch)
except Exception as e: 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) app.logger.warning("citti translate batch failed: %s", e)
continue continue
with get_db() as c: with get_db() as c:
@@ -381,6 +387,8 @@ def translate_missing():
c.execute("INSERT OR REPLACE INTO translations(de,da,created) " c.execute("INSERT OR REPLACE INTO translations(de,da,created) "
"VALUES(?,?,?)", (de, da, now)) "VALUES(?,?,?)", (de, da, now))
done += len(batch) 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) app.logger.info("citti translate: %d headings translated", done)
return done return done
@@ -432,8 +440,14 @@ def match_offers_ai():
"julekalender'). Vælg det billigste ved flere ens. Returnér KUN et " "julekalender'). Vælg det billigste ved flere ens. Returnér KUN et "
'JSON-array [{"item_key":"...","offer_id":"..."}] med de sikre match, ' 'JSON-array [{"item_key":"...","offer_id":"..."}] med de sikre match, '
"intet andet.") "intet andet.")
client = anthropic.Anthropic() client = anthropic.Anthropic(max_retries=CLAUDE_MAX_RETRIES)
text = _claude_json(client, MATCH_MODEL, 8000, prompt) 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) m = re.search(r"\[.*\]", text, re.DOTALL)
if not m: if not m:
app.logger.warning("citti match: unparseable response: %s", text[:200]) app.logger.warning("citti match: unparseable response: %s", text[:200])