diff --git a/README.md b/README.md index 70c1acc..ccea35c 100644 --- a/README.md +++ b/README.md @@ -165,6 +165,14 @@ Try two chapters first to judge quality before paying for a full book: python3 main.py -t "Sample Run" -c "Your concept" -n 2 --target-words 5000 --provider ollama ``` +Models grade their own prose leniently, so judge with a different, stronger model. This also keeps costs down, because the expensive model only reviews: + +```bash +python3 main.py -t "Your Title" -c "Your concept" --provider gemini --editor-provider anthropic +``` + +If an account runs out of quota or credit, the run stops immediately with a clear message instead of retrying. Rerun the same command to resume. + Set `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` or `GEMINI_API_KEY` for cloud providers. Local models are free, but small ones will rarely clear the editorial bar. Run the same command again to resume. To add real endorsements, put permissioned quotes in `books//manuscript/praise.md`. @@ -183,6 +191,7 @@ To add real endorsements, put permissioned quotes in `books/<title>/manuscript/p | `--tamil` | | off | Shortcut for `--language tamil` | | `--provider` | `-p` | auto-detected | `ollama`, `gemini`, `openai`, `anthropic`, `jev` | | `--model` | `-m` | provider default | Model name | +| `--editor-provider` / `--editor-model` | | same as writer | Separate model that scores chapters, picks the opening and reviews the book | | `--ollama-url` | | `http://localhost:11434` | Ollama endpoint | | `--chapters` | `-n` | `24` | Number of chapters | | `--scenes-per-chapter` | | `4` | Scenes per chapter | diff --git a/generator/llm_client.py b/generator/llm_client.py index 9d62119..4558d6b 100644 --- a/generator/llm_client.py +++ b/generator/llm_client.py @@ -13,11 +13,27 @@ RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504, 529} MAX_ATTEMPTS = 5 +MAX_SERVER_DELAY = 120 +# Billing or daily-limit exhaustion: waiting minutes will not help, so fail at once +QUOTA_EXHAUSTED_MARKERS = ("insufficient_quota", "PerDay", "credit balance is too low", "billing_not_active") REQUEST_TIMEOUT = 600 META_PREAMBLE = re.compile(r"^(okay|ok|sure|certainly|of course|here is|here's|below is|as an ai)\b", re.IGNORECASE) META_SUBJECT = re.compile(r"\b(chapter|scene|draft|manuscript|prose|revis|rewrit|json|beat|section)", re.IGNORECASE) +class QuotaExceededError(RuntimeError): + """The account is out of quota or credit; retrying cannot succeed.""" + + +def _server_retry_delay(error: urllib.error.HTTPError, detail: str): + """Seconds the provider asked us to wait, from Retry-After or Gemini's RetryInfo.""" + header = error.headers.get("Retry-After") if error.headers else None + if header and header.strip().isdigit(): + return int(header) + match = re.search(r'"retryDelay":\s*"(\d+(?:\.\d+)?)s"', detail) + return float(match.group(1)) if match else None + + class LlmClient: def __init__( self, @@ -122,23 +138,38 @@ def _call_jev(self, prompt: str, system_prompt: str, max_tokens: int) -> str: return json.dumps(res_data.get("decisions", {}), ensure_ascii=False) def _post_json(self, url: str, payload: dict, headers: dict) -> dict: - """POST with exponential backoff on rate limits, server errors and dropped connections.""" + """POST with backoff on rate limits, server errors and dropped connections; fails at once on exhausted quota.""" body = json.dumps(payload).encode("utf-8") last_error = None + delay = 0 for attempt in range(MAX_ATTEMPTS): if attempt: - delay = min(2 ** attempt, 60) - print(f" [LLM Retry] {last_error}. Attempt {attempt + 1}/{MAX_ATTEMPTS} in {delay}s...") + print(f" [LLM Retry] {last_error[:200]}. Attempt {attempt + 1}/{MAX_ATTEMPTS} in {delay:.0f}s...") time.sleep(delay) + delay = min(2 ** (attempt + 1), 60) req = urllib.request.Request(url, data=body, headers=headers) try: with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as response: return json.loads(response.read().decode("utf-8")) except urllib.error.HTTPError as e: - detail = e.read().decode("utf-8", errors="replace")[:500] - last_error = f"HTTP {e.code} from {self.provider}: {detail}" + detail = e.read().decode("utf-8", errors="replace") + last_error = f"HTTP {e.code} from {self.provider}: {detail[:500]}" + if any(marker in detail for marker in QUOTA_EXHAUSTED_MARKERS): + raise QuotaExceededError( + f"{self.provider} account for model '{self.model}' is out of quota or credit. " + f"Add billing, wait for the quota to reset, or switch --provider/--model. " + f"Progress is saved; rerun the same command to resume.\n{detail[:500]}" + ) if e.code not in RETRYABLE_STATUS: break + requested = _server_retry_delay(e, detail) + if requested is not None: + if requested > MAX_SERVER_DELAY: + raise QuotaExceededError( + f"{self.provider} asked to wait {requested:.0f}s before retrying model '{self.model}'. " + f"Progress is saved; rerun the same command later to resume." + ) + delay = requested + 1 except (urllib.error.URLError, TimeoutError, ConnectionError, json.JSONDecodeError) as e: last_error = f"{self.provider} request failed: {e}" raise RuntimeError(f"LLM call failed for model '{self.model}': {last_error}") diff --git a/main.py b/main.py index 15fd1f0..044d2e5 100644 --- a/main.py +++ b/main.py @@ -21,6 +21,8 @@ def main(): parser.add_argument("--tamil", action="store_true", help="Shortcut for --language tamil") parser.add_argument("--provider", "-p", default=None, choices=["auto", "ollama", "jev", "openai", "gemini", "anthropic"], help="LLM provider (default: auto-detected from environment)") parser.add_argument("--model", "-m", default=None, help="Model name") + parser.add_argument("--editor-provider", default=None, choices=["ollama", "openai", "gemini", "anthropic"], help="Provider for the editor that scores chapters (default: same as --provider)") + parser.add_argument("--editor-model", default=None, help="Model for the editor that scores chapters. A different, stronger model judges more honestly") parser.add_argument("--ollama-url", default="http://localhost:11434", help="Ollama server URL") parser.add_argument("--chapters", "-n", type=int, default=24, help="Number of chapters (default: 24)") parser.add_argument("--scenes-per-chapter", type=int, default=4, help="Scenes in each chapter (default: 4)") @@ -48,6 +50,9 @@ def main(): resolved_provider = "gemini" if (os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY")) else "ollama" llm_client = LlmClient(provider=resolved_provider, model=args.model, ollama_url=args.ollama_url) + editor_llm = None + if args.editor_provider or args.editor_model: + editor_llm = LlmClient(provider=args.editor_provider or resolved_provider, model=args.editor_model, ollama_url=args.ollama_url) print("\n" + "=" * 80) print(" BOOKGENERATOR AI - MULTI-AGENT PIPELINE") @@ -58,6 +63,8 @@ def main(): print(f" Language: {language.upper()}") print(f" Provider: {llm_client.provider.upper()}") print(f" Model: {llm_client.model}") + if editor_llm: + print(f" Editor: {editor_llm.provider.upper()} / {editor_llm.model}") print(f" Plan: {args.chapters} chapters, {args.scenes_per_chapter} scenes each, {args.target_words:,} words") print(f" Book Folder: {book_dir_for(args.title)}") print("=" * 80 + "\n") @@ -75,7 +82,7 @@ def main(): output=args.output, epub=args.epub, cover=args.cover, reset=args.reset, export_cards=args.export_cards, import_lorebook=args.import_lorebook, publishing=publishing, ) - BookPipeline(config, llm_client).run() + BookPipeline(config, llm_client, editor_llm=editor_llm).run() if __name__ == "__main__": diff --git a/pipeline.py b/pipeline.py index 5b4591e..6925750 100644 --- a/pipeline.py +++ b/pipeline.py @@ -79,9 +79,11 @@ def _rank(brief: RevisionBrief) -> tuple: class BookPipeline: - def __init__(self, config: BookConfig, llm_client: LlmClient): + def __init__(self, config: BookConfig, llm_client: LlmClient, editor_llm: Optional[LlmClient] = None): self.config = config self.llm = llm_client + # Judging is done by a separate model when given, since models grade their own prose leniently + self.editor_llm = editor_llm or llm_client self.book_dir = book_dir_for(config.title, config.books_root) self.manuscript_dir = os.path.join(self.book_dir, "manuscript") self.publishing_dir = os.path.join(self.book_dir, "publishing") @@ -104,7 +106,7 @@ def run(self) -> dict: print("\nPHASE 2 & 3: Execution & Adversarial Revision Loop...") self.drafter = ProseDrafterAgent(self.llm) - self.reviewer = MasterAdversarialReviewer(self.llm) + self.reviewer = MasterAdversarialReviewer(self.editor_llm) self.story_state = self.state.get_story_state() if not self.story_state.foreshadowing_clues: self.story_state.foreshadowing_clues = list(self.outline.foreshadowing) @@ -126,7 +128,7 @@ def run(self) -> dict: print("\n" + "=" * 80) print("PHASE 4: Whole-Book Release Review...") chapters, briefs = self._load_finished_chapters() - result = BookReviewer(self.llm).review(config.title, self.brief, self.story_state, chapters, briefs, config.target_words) + result = BookReviewer(self.editor_llm).review(config.title, self.brief, self.story_state, chapters, briefs, config.target_words) report_path = BookReviewer.write_report(result, config.title, briefs, self.publishing_dir) if not self.brief.is_fiction: self._write_fact_check(chapters) @@ -280,7 +282,7 @@ def _choose_opening(self, candidates: List[str]) -> str: system = "You are an acquiring editor choosing the opening most likely to make a stranger keep reading." validator = lambda choice: None if 1 <= choice.best <= len(candidates) else "'best' is out of range." try: - choice = generate_validated(self.llm, prompt, system, OpeningChoice, validator=validator, max_tokens=300) + choice = generate_validated(self.editor_llm, prompt, system, OpeningChoice, validator=validator, max_tokens=300) print(f" -> Opening {choice.best} of {len(candidates)} selected.") return candidates[choice.best - 1] except StructuredOutputError as e: diff --git a/tests/test_llm_client.py b/tests/test_llm_client.py index dde0664..1f11bb7 100644 --- a/tests/test_llm_client.py +++ b/tests/test_llm_client.py @@ -1,6 +1,16 @@ import unittest from unittest.mock import patch -from generator.llm_client import LlmClient +import io +import urllib.error +from email.message import Message +from generator.llm_client import LlmClient, QuotaExceededError + + +def http_error(code, body, retry_after=None): + headers = Message() + if retry_after: + headers["Retry-After"] = retry_after + return urllib.error.HTTPError("https://x", code, "err", headers, io.BytesIO(body.encode())) class TestCleanOutput(unittest.TestCase): @@ -30,5 +40,38 @@ def test_truncated_reply_retries_with_more_room(self): self.assertEqual(post.call_args.args[1]["max_tokens"], 200) +class TestRetries(unittest.TestCase): + def setUp(self): + self.client = LlmClient(provider="openai", api_key="x", model="m") + + def post(self, *errors): + with patch("urllib.request.urlopen", side_effect=list(errors)) as urlopen, patch("time.sleep") as sleep: + try: + self.client._post_json("https://x", {}, {}) + finally: + self.calls, self.sleeps = urlopen.call_count, [c.args[0] for c in sleep.call_args_list] + + def test_exhausted_quota_fails_without_retrying(self): + with self.assertRaises(QuotaExceededError): + self.post(http_error(429, '{"error": {"code": "insufficient_quota"}}')) + self.assertEqual(self.calls, 1) + + def test_gemini_daily_limit_fails_without_retrying(self): + with self.assertRaises(QuotaExceededError): + self.post(http_error(429, '{"quotaId": "GenerateRequestsPerDayPerProjectPerModel-FreeTier"}')) + self.assertEqual(self.calls, 1) + + def test_long_requested_wait_fails_fast(self): + with self.assertRaises(QuotaExceededError): + self.post(http_error(429, "slow down", retry_after="3600")) + self.assertEqual(self.calls, 1) + + def test_brief_rate_limit_waits_as_asked_then_retries(self): + with self.assertRaises(RuntimeError): + self.post(http_error(429, '{"retryDelay": "17s"}'), http_error(400, "bad")) + self.assertEqual(self.calls, 2) + self.assertEqual(self.sleeps, [18]) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index e892ecb..44edb84 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -87,6 +87,15 @@ def generate_text(self, prompt, system_prompt="", max_tokens=4096): with self.assertRaises(RuntimeError): pipeline.run() + def test_editor_model_does_all_judging(self): + writer, editor = FakeLlm(), FakeLlm() + config = BookConfig(title="Split", author="A", books_root=self.tmp.name, chapters=2, scenes_per_chapter=2, target_words=500, opening_candidates=2) + BookPipeline(config, writer, editor_llm=editor).run() + judging = {"chapter review", "book review", "choose opening"} + self.assertFalse(judging & set(writer.tasks)) + self.assertTrue(judging <= set(editor.tasks)) + self.assertNotIn("scene draft", editor.tasks) + def test_slug_keeps_tamil_and_blocks_traversal(self): self.assertEqual(slugify("../../etc/passwd"), "etc_passwd") self.assertEqual(slugify("வேல்விழியின் சபதம்"), "வேல்விழியின்_சபதம்")