import time

def safe_llm_invoke(llm, messages, max_retries=10, base_delay=1.0, logger=None):
    """Invoke LLM with exponential backoff on rate limit (429) errors. Optionally logs rate limit events."""
    for attempt in range(max_retries):
        try:
            return llm.invoke(messages)
        except Exception as e:
            if "rate limit" in str(e).lower() or "429" in str(e):
                wait = base_delay * (2 ** attempt)
                msg = f"Rate limit hit. Retrying in {wait:.1f}s..."
                if logger:
                    logger.warning(msg)
                else:
                    print(msg)
                time.sleep(wait)
            else:
                raise
    raise RuntimeError("Max retries exceeded for LLM call")
