""" LLM Rewriter -- Stage 2 of the humanization pipeline. KEY INSIGHT FROM RESEARCH (RAID Benchmark ACL 2024): - Originality.ai uses an ELECTRA-style discriminator trained on millions of samples including humanized/paraphrased content. - GPT-4o is detected at 97.8% under standard parameters. - Using the same model twice (two-pass) reinforces the same statistical fingerprint. - High frequency/presence penalty + high temperature = more unusual token choices = higher perplexity = harder to detect. - Changing the generation FRAMING (not "rewrite" but "write from notes") produces different statistical distributions. Strategy: Single pass. High diversity parameters. "Write from notes" framing, not "rewrite". Fallback to secondary LLM if primary fails. """ from __future__ import annotations import asyncio import logging import re import time from dataclasses import dataclass from typing import Any from app.config import get_settings from app.core.prompt_manager import PromptManager from app.utils.text_utils import count_words from app.utils.token_utils import calculate_max_tokens logger = logging.getLogger(__name__) @dataclass class RewriteResult: """Return value from LLMRewriter.rewrite().""" output_text: str = "" success: bool = False llm_used: str = "" variant_used: str = "" stage2_time_ms: float = 0.0 error: str = "" class LLMRewriter: """Async LLM rewriter with primary/fallback support. Uses a single-pass approach with high diversity parameters. Two-pass (same model) was removed: it reinforces the statistical fingerprint. """ def __init__(self, prompt_manager: PromptManager | None = None) -> None: self.prompt_manager = prompt_manager or PromptManager() self._settings = get_settings() async def rewrite( self, original_text: str, analysis_result: dict[str, Any], ) -> RewriteResult: """Single-pass rewrite with high diversity parameters.""" t0 = time.perf_counter() system_prompt, user_content, variant_id = self.prompt_manager.build_prompt( original_text, analysis_result ) word_count = count_words(original_text) max_tokens = calculate_max_tokens(word_count) # Build ordered provider chain: primary first, then fallbacks providers = { "claude": (self._call_claude, f"claude ({self._settings.claude_model})"), "openai": (self._call_openai, f"openai ({self._settings.openai_model})"), "groq": (self._call_groq, f"groq ({self._settings.groq_model})"), } primary = self._settings.primary_llm chain = [providers[primary]] + [ v for k, v in providers.items() if k != primary ] errors: list[str] = [] for call_fn, name in chain: output_text, error = await self._try_call( call_fn, system_prompt, user_content, max_tokens, name ) if output_text: elapsed = (time.perf_counter() - t0) * 1000 return RewriteResult( output_text=output_text, success=True, llm_used=name, variant_used=variant_id, stage2_time_ms=round(elapsed, 1), ) errors.append(f"{name}: {error}") if len(errors) < len(chain): logger.warning("%s failed: %s. Trying next.", name, error) elapsed = (time.perf_counter() - t0) * 1000 error_summary = "; ".join(errors) logger.error("All LLMs failed. %s", error_summary) return RewriteResult( output_text=original_text, success=False, llm_used="none", variant_used=variant_id, stage2_time_ms=round(elapsed, 1), error=error_summary, ) async def _try_call(self, call_fn, system_prompt, user_content, max_tokens, name): """Call an LLM with timeout. Returns (text, error).""" timeout = self._settings.llm_timeout_seconds try: output = await asyncio.wait_for( call_fn(system_prompt, user_content, max_tokens), timeout=timeout, ) if output and output.strip(): return output.strip(), "" return "", f"{name} returned empty output" except asyncio.TimeoutError: return "", f"{name} timed out after {timeout}s" except Exception as exc: return "", f"{name} error: {exc}" async def _call_claude(self, system_prompt: str, user_content: str, max_tokens: int) -> str: """Call Anthropic Claude API.""" from anthropic import AsyncAnthropic api_key = self._settings.anthropic_api_key if not api_key: raise ValueError("ANTHROPIC_API_KEY not set") client = AsyncAnthropic(api_key=api_key) message = await client.messages.create( model=self._settings.claude_model, max_tokens=max_tokens, temperature=1.0, # Claude performs well at max temperature top_p=0.99, system=system_prompt, messages=[{"role": "user", "content": user_content}], ) return message.content[0].text if message.content else "" async def _call_openai(self, system_prompt: str, user_content: str, max_tokens: int) -> str: """Call OpenAI ChatCompletion API. Diversity parameters calibrated to raise perplexity without causing degeneration: - frequency_penalty=0.9: Raises perplexity meaningfully without word-salad collapse - presence_penalty=0.6: Broadens vocabulary range at a stable level - temperature=1.0: Max safe temperature; above 1.0 triggers degeneration on long outputs - top_p=0.98: Near-full distribution, allows rare tokens to surface """ from openai import AsyncOpenAI api_key = self._settings.openai_api_key if not api_key: raise ValueError("OPENAI_API_KEY not set") client = AsyncOpenAI(api_key=api_key) response = await client.chat.completions.create( model=self._settings.openai_model, max_tokens=max_tokens, temperature=1.0, top_p=0.98, frequency_penalty=0.9, presence_penalty=0.6, messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_content}, ], ) choice = response.choices[0] if response.choices else None return choice.message.content if choice and choice.message else "" async def _call_groq(self, system_prompt: str, user_content: str, max_tokens: int) -> str: """Call Groq API. Groq hosts open-source models on fast LPU hardware. Some models (DeepSeek-R1, Qwen-3, etc.) emit reasoning inside tags — we strip those so only the final output is returned. """ from groq import AsyncGroq api_key = self._settings.groq_api_key if not api_key: raise ValueError("GROQ_API_KEY not set") client = AsyncGroq(api_key=api_key) response = await client.chat.completions.create( model=self._settings.groq_model, max_completion_tokens=max_tokens, temperature=1.0, top_p=0.98, frequency_penalty=0.9, presence_penalty=0.6, messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_content}, ], ) choice = response.choices[0] if response.choices else None text = choice.message.content if choice and choice.message else "" return self._strip_think_tags(text) @staticmethod def _strip_think_tags(text: str) -> str: """Remove … blocks from thinking-model output.""" return re.sub(r"[\s\S]*?", "", text).strip()