
    &`i+                     P   U d Z ddlZddlmZmZ ddlmc mZ ddlm	Z
 ddlmZmZmZmZmZ ddlmZ  ee          ZdZdeded	efd
Zded	eg ef         fdZ G d d          Zi Zeeef         ed<   ded	efdZd Zeej         vrej         !                    e           dS dS )ap  Generic registry for LLM serving components using Ray's internal KV store.

This module provides a reusable registry mechanism that enables components to be
registered in the driver process and accessed across all Ray processes in the cluster,
including Ray Serve child processes.

Similar to RLlib/Tune's registry but with a fixed global prefix for cross-job access.
    N)AnyCallable)_internal_kv_del_internal_kv_exists_internal_kv_get_internal_kv_initialized_internal_kv_put)
get_loggerserve_globalcategorynamereturnc                     dt                               d          z   dz   |                     d          z   dz   |                    d          z   S )zGenerate a binary key for the KV store.

    Args:
        category: The component category (e.g., "kv_connector_backend")
        name: The component name

    Returns:
        The key to use for storing the value
    s   LLMServeRegistry:ascii   :   /)_SERVE_REGISTRY_PREFIXencode)r   r   s     z/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/llm/_internal/serve/utils/registry.py	_make_keyr      s`     	
 
'
'
0
0	1
	 //'
"
"	# 		
 ++g

	    valuec                      t           t                    r8d vrt          d  d                               dd          \  fd}|S  fdS )a  Create a loader callable for a value.

    Handles both direct objects/classes and string paths for lazy loading.

    Args:
        value: Either:
            - A class, object, or callable (returns lambda: value)
            - A string in format "module_path:class_name" (creates import loader)

    Returns:
        A callable that returns the value when called

    Raises:
        ValueError: If value is a string but doesn't have the correct format
    :z"Invalid format for string value: 'z?'. Expected format: 'module_path:class_name' or a class/object.   c                  L    t          j                  } t          |           S N)	importlibimport_modulegetattr)module
class_namemodule_paths    r   loaderz_create_loader.<locals>.loaderK   s#    ,[99F6:...r   c                       S r    )r   s   r   <lambda>z _create_loader.<locals>.<lambda>R   s    u r   )
isinstancestr
ValueErrorrsplit)r   r$   r"   r#   s   ` @@r   _create_loaderr,   3   s      % ePU P P P   #(,,sA"6"6Z	/ 	/ 	/ 	/ 	/ 	/  }}}r   c                   j    e Zd ZdZdefdZdededdfdZdedefd	Zdede	fd
Z
deddfdZddZdS )ComponentRegistrya}  Generic registry for LLM serving components using Ray's internal KV store.

    This registry enables components to be registered in the driver process and
    accessed across all Ray processes in the cluster, including Ray Serve child processes.

    Similar to RLlib/Tune's registry but with a fixed global prefix for cross-job access.

    **Usage Pattern:**
        This registry is designed for a "register once, read many" pattern:
        - Components are typically registered in the driver process before deployment
        - Ray Serve replicas read from the KV store during initialization
        - Once a component is resolved and cached in a process, subsequent `get()` calls return the cached value without checking the KV store for updates

    Example:
        # Create a registry for a component category
        registry = ComponentRegistry("my_component")

        # Register a component
        registry.register("my_component", MyComponentClass)

        # Get a registered component
        component = registry.get("my_component")

        # Check if registered
        if registry.contains("my_component"):
            ...
    r   c                 >    || _         i | _        i | _        i | _        dS )zInitialize a registry for a specific component category.

        Args:
            category: The category name (e.g., "kv_connector_backend")
        N)r   _loader_cache_resolved_cache_pending)selfr   s     r   __init__zComponentRegistry.__init__r   s&     !;=/1*,r   r   r   r   Nc           	      &   |                      |          rt          | j         d| d          t          |          }t	          j        |          }|| j        |<   t                      r	 t          | j        |          }t          ||d           t                              d| j         d| d           d
S # t          $ r?}t                              d| j         d| d| d	           || j        |<   Y d
}~d
S d
}~ww xY w|| j        |<   d
S )a  Register a component.

        Args:
            name: The name to register under
            value: The component to register. Can be:
                - A class, object, or callable (serialized directly)
                - A string in format "module_path:class_name" (lazy-loaded via import)

        Raises:
            ValueError: If the component is already registered. Use unregister() first if you need to change the registration.

        Examples:
            # Register a class directly
            registry.register("MyClass", MyClass)

            # Register via module path (lazy loading)
            registry.register("MyClass", "my.module:MyClass")
         'zW' is already registered. Use unregister() first if you need to change the registration.T	overwritezRegistered z' in KV storezFailed to register z' in KV store: exc_infoN)containsr*   r   r,   pickledumpsr0   r   r   r	   loggerdebug	Exceptionwarningr2   )r3   r   r   r$   
serializedkeyes          r   registerzComponentRegistry.register}   sv   ( == 	= R RD R R R    && \&))
 $*4  $%% 	-	1t44 jDAAAAO4=OODOOOPPPPP 1 1 1S$-SS4SSPQSS!     '1d#######1 #-DM$s   ,AB; ;
D4C??Dc           
         || j         v r| j         |         S | j                            |          }|t                      r	 t	          | j        |          }t          |          }|Dt          j        |          }|| j        |<   t          
                    d| j         d| d           nA# t          $ r4}t                              d| j         d| d| d           Y d}~nd}~ww xY w| |            }|| j         |<   |S t          | j         d| d	t          | j                                                             )
at  Get a registered component.

        Args:
            name: The name of the component

        Returns:
            The registered component. If registered with a string path,
            returns the imported class/object. If registered directly,
            returns the original value.

        Raises:
            ValueError: If the component is not registered
        NzLoaded r6   ' from KV storezFailed to load ' from KV store: Tr9   z' not found. Registered: )r1   r0   getr   r   r   r   r<   loadsr>   r?   r@   rA   r*   listkeys)r3   r   r$   rC   rB   rD   r   s          r   rI   zComponentRegistry.get   s    4''''--#''-->688>t44-c22
)#\*55F/5D&t,LL!Q4=!Q!QD!Q!Q!QRRR   QdmQQtQQaQQ!          FHHE).D &L } = = = = 2 7 7 9 9::= =
 
 	
s   A*B- -
C+7*C&&C+c           	         || j         v rdS t                      rg	 t          | j        |          }t	          |          S # t
          $ r5}t                              d| j         d| d| d           Y d}~dS d}~ww xY wdS )zCheck if a component is registered.

        Args:
            name: The name to check

        Returns:
            True if registered, False otherwise
        TzFailed to check if r6   z' exists in KV store: r9   NF)r0   r   r   r   r   r@   r>   rA   r3   r   rC   rD   s       r   r;   zComponentRegistry.contains   s     4%%%4#%% 		t44*3///   Z$-ZZ4ZZWXZZ!     uuuuu us   #? 
A>	*A99A>c           	         || j         v r| j         |= || j        v r| j        |= || j        v r| j        |= t                      r	 t	          | j        |          }t          |           t                              d| j         d| d           dS # t          $ r5}t          
                    d| j         d| d| d           Y d}~dS d}~ww xY wdS )	zUnregister a component.

        Removes the component from local cache, pending registrations, and KV store.

        Args:
            name: The name of the component to unregister
        zUnregistered r6   rG   zFailed to unregister rH   Tr9   N)r0   r1   r2   r   r   r   r   r>   r?   r@   rA   rN   s       r   
unregisterzComponentRegistry.unregister   s4    4%%%"4(4'''$T* 4=  d# $%% 		t44 %%%ST]SSdSSSTTTTT   WDMWWTWWTUWW!          		 		s   A
B 
C*C		Cc           
         t                      r| j        sdS | j                                        D ]\  }}	 t          | j        |          }t          ||d           t                              d| j         d| d           T# t          $ r4}t          	                    d| j         d| d| d	           Y d}~d}~ww xY w| j        
                                 dS )
zFlush pending registrations to KV store.

        This is called automatically when Ray initializes via _post_init_hooks.
        NTr7   z!Flushed pending registration for r6   'zFailed to flush z': r9   )r   r2   itemsr   r   r	   r>   r?   r@   rA   clear)r3   r   rB   rC   rD   s        r   flush_pendingzComponentRegistry.flush_pending  s0   
 ()) 	 	F $ 3 3 5 5 
	 
	D*	t44 jDAAAAPPPPPP       Dt}DDDDDDt         
 	s   AB
C*B>>C)r   N)__name__
__module____qualname____doc__r)   r4   r   rE   rI   boolr;   rP   rU   r&   r   r   r.   r.   U   s         8	- 	- 	- 	- 	-0-S 0- 0- 0- 0- 0- 0-d,
 ,
 ,
 ,
 ,
 ,
\S T    2s t    <     r   r.   _registriesc                 \    | t           vrt          |           t           | <   t           |          S )zGet or create a registry for a component category.

    Args:
        category: The component category name

    Returns:
        The ComponentRegistry instance for this category
    )r[   r.   )r   s    r   get_registryr]   /  s,     {"" 1( ; ;Hx  r   c                  f    t                                           D ]} |                                  dS )zFlush all pending registrations to KV store.

    This is registered as a Ray post-init hook to ensure registrations
    made before Ray initialization are available across processes.
    N)r[   valuesrU   )registrys    r   _flush_all_registriesra   =  s>      &&(( ! !    ! !r   )"rY   r   typingr   r   ray._private.worker_privateworkerray.cloudpicklecloudpickler<   ray.experimental.internal_kvr   r   r   r   r	   -ray.llm._internal.serve.observability.loggingr
   rV   r>   r   r)   bytesr   r,   r.   r[   dict__annotations__r]   ra   _post_init_hooksappendr&   r   r   <module>ro      s                         $ $ $ $ $ $ $ $ $                          E D D D D D	H		 (  3 5    (# (2s7"3    DS S S S S S S Sn -/T#(() . . .!3 !#4 ! ! ! !! ! !  777
""#899999 87r   