perf(translate): fix slow translation startup — CJK estimation, output budget, provider token config

Root cause: batch sizing underestimated CJK token density (1.5→1.0 chars/token)
and ignored output budget as primary constraint, causing cascading finish_reason=length.

Changes:
- _token_budget.py: CJK_RATIO 1.5→1.0, OTHER_RATIO 2.2→1.8, safety factors 0.75/0.70
- _token_budget.py: new _compute_max_rows_by_output() — output budget is PRIMARY constraint
- _batch_sizer.py: resolve_provider_config() with DB-level context_window/max_output_tokens
- _batch_sizer.py: INPUT_SAFETY_FACTOR applied, max_rows_by_output used as row cap
- _llm_http.py: log actual usage.prompt_tokens/.completion_tokens from provider
- _llm_call.py: retry only missing rows after finish_reason=length (save partial result)
- models/llm.py + schema: provider-level context_window / max_output_tokens (nullable)
- services/llm_provider.py: get_provider_token_config() helper
- Alembic migration: add columns to llm_providers
- Svelte ProviderConfig: collapsible Advanced: Token Limits section
- 12 new tests (token budget, batch sizer, provider config)
- All 492 tests pass
This commit is contained in:
2026-06-03 23:25:08 +03:00
parent 1bde015165
commit a064b38a4e
18 changed files with 1303 additions and 109 deletions

View File

@@ -206,30 +206,36 @@ class BatchProcessingService:
return count
def _process_llm(self, job, run_id, rows_for_llm, dict_matches, bid, tls):
provider_model = None
# Resolve provider token config (DB values take priority over PROVIDER_DEFAULTS)
token_config = {"model": None, "context_window": None, "max_output_tokens": None}
if job.provider_id:
try:
p = LLMProviderService(self.db).get_provider(job.provider_id)
if p:
provider_model = p.default_model or "gpt-4o-mini"
token_config = LLMProviderService(self.db).get_provider_token_config(job.provider_id)
except Exception:
provider_model = None
pass
tb = estimate_token_budget(
source_rows=rows_for_llm, target_languages=tls,
source_column="source_text", context_columns=None,
dictionary_entries=dict_matches, batch_size=len(rows_for_llm),
provider_info=provider_model,
provider_info=token_config["model"],
context_window=token_config["context_window"],
max_output_tokens=token_config["max_output_tokens"],
)
if tb["warning"]:
logger.explore("Token budget warning", {"batch_id": bid, "warning": tb["warning"]})
max_rows_by_out = tb.get("max_rows_by_output", 0)
logger.reason(
f"LLM process batch start", {
"batch_id": bid, "llm_rows": len(rows_for_llm),
"provider_model": provider_model,
"provider_model": token_config["model"],
"max_output_needed": tb.get("max_output_needed"),
"estimated_input_tokens": tb.get("estimated_input_tokens"),
"max_rows_by_output": max_rows_by_out,
"context_window": token_config["context_window"],
"max_output_tokens": token_config["max_output_tokens"],
},
)