|
| 1 | +import asyncio |
| 2 | +import logging |
| 3 | +from typing import Dict, Optional |
| 4 | + |
| 5 | +from v2.nacos.ai.model.cache.prompt_subscribe_manager import PromptSubscribeManager |
| 6 | +from v2.nacos.ai.model.prompt.prompt import Prompt |
| 7 | +from v2.nacos.ai.util.prompt_util import build_prompt_cache_key |
| 8 | +from v2.nacos.common.constants import Constants |
| 9 | +from v2.nacos.common.nacos_exception import NacosException, NOT_FOUND, NOT_MODIFIED |
| 10 | + |
| 11 | +DEFAULT_PROMPT_UPDATE_INTERVAL = 10 |
| 12 | + |
| 13 | + |
| 14 | +class PromptCacheHolder: |
| 15 | + |
| 16 | + def __init__(self, subscribe_manager: PromptSubscribeManager, ai_client_proxy, |
| 17 | + update_interval: float = DEFAULT_PROMPT_UPDATE_INTERVAL): |
| 18 | + """ |
| 19 | + Args: |
| 20 | + subscribe_manager: Manager for prompt change subscribers |
| 21 | + ai_client_proxy: Any object with async query_prompt(prompt_key, version, label, md5) method. |
| 22 | + Can be AIGRPCClientProxy or AiHttpClientProxy. |
| 23 | + update_interval: Poll interval in seconds (default 10s) |
| 24 | + """ |
| 25 | + self.prompt_subscribe_manager = subscribe_manager |
| 26 | + self.ai_client_proxy = ai_client_proxy |
| 27 | + self.update_interval = update_interval |
| 28 | + self.prompt_cache: Dict[str, Prompt] = {} |
| 29 | + self.cache_lock = asyncio.Lock() |
| 30 | + self.logger = logging.getLogger(Constants.AI_MODULE) |
| 31 | + self.tasks: Dict[str, asyncio.Task] = {} |
| 32 | + |
| 33 | + async def shutdown(self): |
| 34 | + for task in self.tasks.values(): |
| 35 | + task.cancel() |
| 36 | + for task in self.tasks.values(): |
| 37 | + try: |
| 38 | + await task |
| 39 | + except asyncio.CancelledError: |
| 40 | + pass |
| 41 | + self.tasks.clear() |
| 42 | + |
| 43 | + async def subscribe_prompt(self, prompt_key: str, version: Optional[str], |
| 44 | + label: Optional[str]) -> Optional[Prompt]: |
| 45 | + cache_key = build_prompt_cache_key(prompt_key, version, label) |
| 46 | + prompt = None |
| 47 | + try: |
| 48 | + prompt = await self.ai_client_proxy.query_prompt(prompt_key, version, label, None) |
| 49 | + self._process_prompt(prompt_key, cache_key, prompt) |
| 50 | + except NacosException as e: |
| 51 | + if e.error_code != NOT_FOUND: |
| 52 | + raise |
| 53 | + self._process_prompt(prompt_key, cache_key, None) |
| 54 | + |
| 55 | + self._add_update_task(prompt_key, version, label) |
| 56 | + self.logger.info(f"Subscribed prompt: {prompt_key}, version: {version}, label: {label}") |
| 57 | + return prompt |
| 58 | + |
| 59 | + def unsubscribe_prompt(self, prompt_key: str, version: Optional[str], |
| 60 | + label: Optional[str]): |
| 61 | + cache_key = build_prompt_cache_key(prompt_key, version, label) |
| 62 | + self._remove_update_task(prompt_key, version, label) |
| 63 | + self.prompt_cache.pop(cache_key, None) |
| 64 | + self.logger.info(f"Unsubscribed prompt: {prompt_key}, version: {version}, label: {label}") |
| 65 | + |
| 66 | + def get_cached_prompt(self, prompt_key: str, version: Optional[str], |
| 67 | + label: Optional[str]) -> Optional[Prompt]: |
| 68 | + cache_key = build_prompt_cache_key(prompt_key, version, label) |
| 69 | + return self.prompt_cache.get(cache_key) |
| 70 | + |
| 71 | + def _add_update_task(self, prompt_key: str, version: Optional[str], |
| 72 | + label: Optional[str]): |
| 73 | + cache_key = build_prompt_cache_key(prompt_key, version, label) |
| 74 | + if cache_key not in self.tasks: |
| 75 | + self.tasks[cache_key] = asyncio.create_task( |
| 76 | + self._update_prompt_loop(prompt_key, version, label, cache_key)) |
| 77 | + |
| 78 | + def _remove_update_task(self, prompt_key: str, version: Optional[str], |
| 79 | + label: Optional[str]): |
| 80 | + cache_key = build_prompt_cache_key(prompt_key, version, label) |
| 81 | + task = self.tasks.pop(cache_key, None) |
| 82 | + if task is not None: |
| 83 | + task.cancel() |
| 84 | + |
| 85 | + async def _update_prompt_loop(self, prompt_key: str, version: Optional[str], |
| 86 | + label: Optional[str], cache_key: str): |
| 87 | + while True: |
| 88 | + try: |
| 89 | + await asyncio.sleep(self.update_interval) |
| 90 | + except asyncio.CancelledError: |
| 91 | + return |
| 92 | + |
| 93 | + try: |
| 94 | + current_prompt = self.prompt_cache.get(cache_key) |
| 95 | + current_md5 = current_prompt.md5 if current_prompt else None |
| 96 | + latest_prompt = await self.ai_client_proxy.query_prompt( |
| 97 | + prompt_key, version, label, current_md5) |
| 98 | + self._process_prompt(prompt_key, cache_key, latest_prompt) |
| 99 | + except NacosException as e: |
| 100 | + if e.error_code == NOT_FOUND: |
| 101 | + self._process_prompt(prompt_key, cache_key, None) |
| 102 | + elif e.error_code == NOT_MODIFIED: |
| 103 | + pass |
| 104 | + else: |
| 105 | + self.logger.warning( |
| 106 | + f"Prompt updater query failed: promptKey={prompt_key}, err={e.message}") |
| 107 | + except asyncio.CancelledError: |
| 108 | + return |
| 109 | + except Exception as e: |
| 110 | + self.logger.warning( |
| 111 | + f"Prompt updater unexpected error: promptKey={prompt_key}, err={e}") |
| 112 | + |
| 113 | + def _process_prompt(self, prompt_key: str, cache_key: str, |
| 114 | + new_prompt: Optional[Prompt]): |
| 115 | + old_prompt = self.prompt_cache.get(cache_key) |
| 116 | + if new_prompt is None: |
| 117 | + self.prompt_cache.pop(cache_key, None) |
| 118 | + else: |
| 119 | + self.prompt_cache[cache_key] = new_prompt |
| 120 | + |
| 121 | + if self._is_prompt_changed(old_prompt, new_prompt): |
| 122 | + subscribers = self.prompt_subscribe_manager.subscribers.get(cache_key, []) |
| 123 | + for callback_func in subscribers: |
| 124 | + try: |
| 125 | + asyncio.ensure_future(callback_func(prompt_key, new_prompt)) |
| 126 | + except Exception as e: |
| 127 | + self.logger.error(f"Prompt change callback error: {e}") |
| 128 | + |
| 129 | + @staticmethod |
| 130 | + def _is_prompt_changed(old_prompt: Optional[Prompt], |
| 131 | + new_prompt: Optional[Prompt]) -> bool: |
| 132 | + old_json = "" if old_prompt is None else old_prompt.model_dump_json() |
| 133 | + new_json = "" if new_prompt is None else new_prompt.model_dump_json() |
| 134 | + return old_json != new_json |
0 commit comments