
    SXi#                    6   d Z ddlmZ ddlZddlmZmZmZmZ ddl	m
Z
 ddlmZmZmZ  ej                  d      Z	 dd	lmZmZmZ  G d
 de      Z G d de      Z G d de      Z G d de      Z G d de      ZdZddZy# e$ r dZdZdZdZdZdZY w xY w)a  RLM Neo-Cortex -- Module 1: Memory Gateway FastAPI Router.

Exposes the MemoryGateway as a REST API mounted under /api/v1/memory.

Routes:
    POST   /api/v1/memory/write           Write a new memory
    POST   /api/v1/memory/search          Vector-search memories
    GET    /api/v1/memory/health          Health-check all backends
    DELETE /api/v1/memory/{tid}/{mid}     Delete a specific memory

Story 1.09.
    )annotationsN)AnyDictListOptional)UUID   )MemoryGatewayQuotaExceededErrorPartialDeleteErrorzcore.rlm.gateway_router)	BaseModelFieldfield_validatorc                      e Zd ZU dZded<    eddd      Zded	<    edd
      Zded<    edd
      Zded<    ed      Z	ded<    e
d	      edd              Zy)WriteMemoryRequestzRequest body for POST /write.r   	tenant_id.
   zMemory content (min 10 chars))
min_lengthdescriptionstrcontentr	   r   sourcedomainN)defaultzOptional[Dict[str, Any]]metadatac                @    |r|j                         st        d      |S )Nzcontent must not be blank)strip
ValueError)clsvs     0/mnt/e/genesis-system/core/rlm/gateway_router.pycontent_not_blankz$WriteMemoryRequest.content_not_blank&   s      AGGI !<==H    )r!   r   returnr   )__name__
__module____qualname____doc____annotations__r   r   r   r   r   r   classmethodr#    r$   r"   r   r      so    +SR=\]]CA..CA..-24-@*@		#		 
 
$	r$   r   c                  V    e Zd ZU dZdZded<   ded<   ded<   d	ed
<   ded<   dZded<   y)WriteMemoryResponsezResponse body for POST /write.NOptional[str]	memory_idr   r   r   tierfloatsurprise_score
created_atzOptional[int]pg_id)r&   r'   r(   r)   r0   r*   r5   r,   r$   r"   r.   r.   -   s.    ,#'	='	#}#r$   r.   c                  z    e Zd ZU dZded<    edd      Zded<    ed	dd
      Zded<    eddd      Zded<   y)SearchRequestzRequest body for POST /search.r   r   .r	   r   r   queryr   d   )r   geleintlimitg        g      ?r2   	min_scoreN)	r&   r'   r(   r)   r*   r   r8   r=   r>   r,   r$   r"   r7   r7   6   sA    ,31-s-2!4s4 =	5=r$   r7   c                  f    e Zd ZU dZdZded<   ded<   ded<   ded	<   ded
<   ded<   ded<   ded<   y)MemoryResponsez%Single memory item in search results.Nr/   r0   r   r   r   r   r   r   r1   r2   r3   r4   )r&   r'   r(   r)   r0   r*   r,   r$   r"   r@   r@   =   s3    3#'	='	r$   r@   c                  :    e Zd ZU dZded<   ded<   ded<   ded<   y)	HealthResponsezHealth check response.r   statusboolpgqdrantredisN)r&   r'   r(   r)   r*   r,   r$   r"   rB   rB   H   s    $r$   rB   TFc                    t         st        d      	 ddlm}m  |ddg      }|j                  d	t        d
      d fd       }|j                  dt        t           d
      d fd       }|j                  dt        d
      d fd       }|j                  dd
      d fd       }|S # t        $ r}t        d      |d}~ww xY w)um  Build and return a FastAPI APIRouter wired to *gateway*.

    Args:
        gateway: A MemoryGateway instance (initialised or not — the
                 endpoints themselves require it to be initialised).

    Returns:
        fastapi.APIRouter with all memory endpoints registered.

    Raises:
        ImportError: If fastapi or pydantic are not installed.
    zKpydantic is required for gateway_router. Install with: pip install pydanticr   )	APIRouterHTTPExceptionzIfastapi is required for gateway_router. Install with: pip install fastapiNz/api/v1/memorymemory)prefixtagsz/write   )response_modelstatus_codec           	       K   	 j                  | j                  | j                  | j                  | j                  | j
                         d{   }t        |j                  |j                  |j                  j                  |j                  |j                  j                         |j                        S 7 i# t        $ r;} ddt        |j                        |j                   |j"                  d      d}~wt$        $ r} dt        |            d}~wt&        $ r%}t(        j+                  d	|        d
d      d}~ww xY ww)z0Write a new memory through the routing pipeline.)r   r   r   r   r   N)r0   r   r1   r3   r4   r5   i  quota_exceeded)errorr   r=   currentrP   detaili  zwrite_memory endpoint error: %s  Internal gateway error)write_memoryr   r   r   r   r   r.   	vector_idmemory_tiervaluer3   r4   	isoformatr5   r   r   r=   rT   r   	ExceptionloggerrS   )reqrecordexcrJ   gateways      r"   rY   z#create_router.<locals>.write_memory   s)    	R"//--zzzz 0  F ' ** **''--%44!,,668ll  " 		-!$S]]!3 YY"{{	   	BCCAA 	RLL:C@C8PQQ	RsT   EAB< B:A(B< 9E:B< <	E6C;;EDE& EEEz/searchc                  K   	 j                  | j                  | j                  | j                  | j                         d{   }|D cg c]}  }t        |j                  |j                  |j                  |j                  |j                  |j                  j                  |j                  |j                  j                                c}S 7 c c}w # t        $ r%}t         j#                  d|        dd      d}~ww xY ww)z)Vector-search memories by semantic query.)r   r8   r=   r>   N)r0   r   r   r   r   r1   r3   r4   z"search_memories endpoint error: %srW   rX   rU   )search_memoriesr   r8   r=   r>   r@   rZ   r   r   r   r[   r\   r3   r4   r]   r^   r_   rS   )r`   recordsrrb   rJ   rc   s       r"   re   z&create_router.<locals>.search_memories   s     	R#33--iiii--	 4  G" !  kkkkII8888,,#$#3#3 ||557	   	RLL=sCC8PQQ	RsN   DA C CC BCC DC C 	D# DDDz/healthc            	        K   j                          d{   } t        | d   | j                  dd      | j                  dd      | j                  dd            S 7 Fw)z,Return health status for all three backends.NrC   rE   FrF   rG   )rC   rE   rF   rG   )health_checkrB   get)resultrc   s    r"   healthzcreate_router.<locals>.health   s^      ++--(#zz$&::h.**We,	
 	
 .s   A AAA z/{tenant_id}/{memory_id})rP   c                >  K   	 j                  | |       d{   }|s dd| d|        d|dS 7 # $ r  t        $ r'} d	d
|j                  |j                  d      d}~wt        $ r%}t
        j                  d|        d	d      d}~ww xY ww)z*Delete a memory. Returns 404 if not found.)r   r0   Ni  zMemory z not found for tenant rU   T)deletedr0   rW   partial_delete)rS   r0   backends_failedz delete_memory endpoint error: %srX   )delete_memoryr   r0   rp   r^   r_   rS   )r   r0   rn   rb   rJ   rc   s       r"   rq   z$create_router.<locals>.delete_memory   s     	R#11## 2  G # #$YK/Ei[Q   $)<<  	! 	-!$'*':':   	RLL;SAC8PQQ	Rs=   B9 79 B9 B"A))B5 BBB)r`   r   r%   r.   )r`   r7   r%   zList[MemoryResponse])r%   rB   )r   r   r0   r   r%   zDict[str, Any])_PYDANTIC_OKImportErrorfastapirI   rJ   postr.   r   r@   rj   rB   delete)	rc   rI   rb   routerrY   re   rl   rq   rJ   s	   `       @r"   create_routerrx   ^   s    1
 	

4 .hZ@F [[*=3[O R P RL [[4+?S[QR RR< ZZ	.cZJ
 K
 ]]"  R	R8 MC  0
 	s   B3 3	C<CC)rc   r
   r%   r   )r)   
__future__r   loggingtypingr   r   r   r   uuidr   rc   r
   r   r   	getLoggerr_   pydanticr   r   r   r   r.   r7   r@   rB   rr   rs   rx   r,   r$   r"   <module>r      s    #  , ,  J J			4	5<::Y $i $>	 >	 	  LV  LMNNs   AB BB