Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions graphify/llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -2800,8 +2800,9 @@ def _label_batch_with_retry(
# Budget generously: a 2-5 word name is ~10 tokens, but models (notably
# gemini) often prepend a short preamble or reasoning that eats the
# completion and truncates the JSON mid-object, which used to fail the whole
# batch (#1690). The old 64 + 24*n floor left no headroom.
max_tokens = _resolve_max_tokens(min(256 + 48 * len(batch_cids), 8192))
# batch (#1690). Keep at least 512 tokens as adaptive retries shrink the
# batch; otherwise the recovery path starves its own base case (#2086).
max_tokens = _resolve_max_tokens(max(512, min(256 + 48 * len(batch_cids), 8192)))
call_kwargs: dict = {"backend": backend, "max_tokens": max_tokens}
if model is not None:
call_kwargs["model"] = model
Expand Down
25 changes: 25 additions & 0 deletions tests/test_label_retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,28 @@ def fake_call_llm(prompt: str, **_kwargs) -> str:

assert result == {42: "Label 42", 99: "Label 99", 137: "Label 137", 201: "Label 201"}
assert call_count["n"] >= 2


def test_label_batch_retry_keeps_a_safe_output_token_floor(monkeypatch):
"""Split retries must not starve small batches of output tokens (#2086)."""
token_budgets: list[int] = []
monkeypatch.delenv("GRAPHIFY_MAX_OUTPUT_TOKENS", raising=False)

def fake_call_llm(prompt: str, **kwargs) -> str:
token_budgets.append(kwargs["max_tokens"])
cids = [int(m) for m in re.findall(r"Community (\d+):", prompt)]
if len(cids) > 1:
return "not json"
return json.dumps({str(cids[0]): f"Label {cids[0]}"})

monkeypatch.setattr(llm_mod, "_call_llm", fake_call_llm)

result = llm_mod._label_batch_with_retry(
[1, 2],
["Community 1: auth", "Community 2: billing"],
backend="gemini",
model=None,
)

assert result == {1: "Label 1", 2: "Label 2"}
assert token_budgets == [512, 512, 512]
Loading