|
6 | 6 |
|
7 | 7 | from .core import MemgraphLightRAGWrapper |
8 | 8 |
|
| 9 | + |
| 10 | +# Patch lightrag.llm.anthropic for current Anthropic SDK: |
| 11 | +# - require max_tokens; use top-level system= (not "system" role in messages). |
| 12 | +def _patch_anthropic() -> None: |
| 13 | + try: |
| 14 | + import os |
| 15 | + import logging |
| 16 | + from typing import Any, Union |
| 17 | + from collections.abc import AsyncIterator |
| 18 | + |
| 19 | + import lightrag.llm.anthropic as _mod |
| 20 | + from anthropic import ( |
| 21 | + AsyncAnthropic, |
| 22 | + APIConnectionError, |
| 23 | + RateLimitError, |
| 24 | + APITimeoutError, |
| 25 | + ) |
| 26 | + from tenacity import ( |
| 27 | + retry, |
| 28 | + stop_after_attempt, |
| 29 | + wait_exponential, |
| 30 | + retry_if_exception_type, |
| 31 | + ) |
| 32 | + from lightrag.utils import safe_unicode_decode, logger, VERBOSE_DEBUG |
| 33 | + from lightrag.api import __api_version__ |
| 34 | + |
| 35 | + _orig = _mod.anthropic_complete_if_cache |
| 36 | + if getattr(_orig, "_lightrag_memgraph_patched", False): |
| 37 | + return |
| 38 | + |
| 39 | + @retry( |
| 40 | + stop=stop_after_attempt(3), |
| 41 | + wait=wait_exponential(multiplier=1, min=4, max=10), |
| 42 | + retry=retry_if_exception_type( |
| 43 | + (RateLimitError, APIConnectionError, APITimeoutError) |
| 44 | + ), |
| 45 | + ) |
| 46 | + async def _wrapped( |
| 47 | + model: str, |
| 48 | + prompt: str, |
| 49 | + system_prompt: str | None = None, |
| 50 | + history_messages: list[dict[str, Any]] | None = None, |
| 51 | + enable_cot: bool = False, |
| 52 | + base_url: str | None = None, |
| 53 | + api_key: str | None = None, |
| 54 | + **kwargs: Any, |
| 55 | + ) -> Union[str, AsyncIterator[str]]: |
| 56 | + if history_messages is None: |
| 57 | + history_messages = [] |
| 58 | + kwargs.setdefault("max_tokens", 4096) |
| 59 | + if not api_key: |
| 60 | + api_key = os.environ.get("ANTHROPIC_API_KEY") |
| 61 | + |
| 62 | + default_headers = { |
| 63 | + "User-Agent": f"Mozilla/5.0 LightRAG/{__api_version__}", |
| 64 | + "Content-Type": "application/json", |
| 65 | + } |
| 66 | + kwargs.pop("hashing_kv", None) |
| 67 | + kwargs.pop("keyword_extraction", None) |
| 68 | + timeout = kwargs.pop("timeout", None) |
| 69 | + |
| 70 | + client = ( |
| 71 | + AsyncAnthropic( |
| 72 | + default_headers=default_headers, api_key=api_key, timeout=timeout |
| 73 | + ) |
| 74 | + if base_url is None |
| 75 | + else AsyncAnthropic( |
| 76 | + base_url=base_url, |
| 77 | + default_headers=default_headers, |
| 78 | + api_key=api_key, |
| 79 | + timeout=timeout, |
| 80 | + ) |
| 81 | + ) |
| 82 | + |
| 83 | + # API expects top-level system=, not a message with role "system" |
| 84 | + messages: list[dict[str, Any]] = list(history_messages) |
| 85 | + messages.append({"role": "user", "content": prompt}) |
| 86 | + |
| 87 | + create_kwargs: dict[str, Any] = { |
| 88 | + "model": model, |
| 89 | + "messages": messages, |
| 90 | + "stream": True, |
| 91 | + **kwargs, |
| 92 | + } |
| 93 | + if system_prompt: |
| 94 | + create_kwargs["system"] = system_prompt |
| 95 | + |
| 96 | + if not VERBOSE_DEBUG and logger.level == logging.DEBUG: |
| 97 | + logging.getLogger("anthropic").setLevel(logging.INFO) |
| 98 | + |
| 99 | + response = await client.messages.create(**create_kwargs) |
| 100 | + |
| 101 | + # Consume stream and return a single string (caller expects str, not AsyncIterator) |
| 102 | + # Only content_block_delta events have delta.text; message_delta etc. have no .text |
| 103 | + parts: list[str] = [] |
| 104 | + async for event in response: |
| 105 | + content = ( |
| 106 | + getattr(getattr(event, "delta", None), "text", None) |
| 107 | + if hasattr(event, "delta") |
| 108 | + else None |
| 109 | + ) |
| 110 | + if not content: |
| 111 | + continue |
| 112 | + if r"\u" in content: |
| 113 | + content = safe_unicode_decode(content.encode("utf-8")) |
| 114 | + parts.append(content) |
| 115 | + return "".join(parts) |
| 116 | + |
| 117 | + _wrapped._lightrag_memgraph_patched = True # type: ignore[attr-defined] |
| 118 | + _mod.anthropic_complete_if_cache = _wrapped |
| 119 | + except Exception: |
| 120 | + pass |
| 121 | + |
| 122 | + |
| 123 | +_patch_anthropic() |
| 124 | + |
9 | 125 | __all__ = ["MemgraphLightRAGWrapper"] |
0 commit comments