
    i              
       T   d Z ddlZddlZddlmZmZmZmZ ddlm	Z
mZ ddlmZ ddlmZmZmZmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddl m!Z! ddl"m#Z#  ejH                  e%      Z& ee#jN                  d      Z( eddg      Z) e       Z* e       Z+ ee*      Z,defdZ-defdZ.e)j_                  deej`                         ee-       ee.       ee      fdededede1fd       Z2e)j_                  deej`                         ee      fdede1fd        Z3y)!zE
Endpoints de chat: /chat/conversation y /chat/conversation-analize.
    N)	APIRouterDependsHTTPExceptionstatus)HumanMessageSystemMessage)
ChatOpenAI   )SearchChatRequestSearchChatResponseConversationAnalizeRequestConversationAnalizeResponse)verify_api_key)ProductService)FlowService)IdentityService)conversation_graph)ConversationState)CONVERSATION_ANALIZE_PROMPT)settings)modeltemperaturez/chatchat)prefixtags)identity_servicereturnc                      t         S N)	_flow_svc     //opt/lhia/marcimex/agent/app/api/routes/chat.pyget_flow_servicer$   %   s    r"   c                      t         S r   )_product_svcr!   r"   r#   get_product_servicer'   )   s    r"   z/conversation)response_modelstatus_coderequestflow_svcproduct_svc_c                   K   t        j                          }| j                  }| j                  xs dj                         }t        j                  d| d       t        j                  d| d|dd  d| j                          	 i d	|d
|d| j                  d| j                  d| j                  d| j                  dd| dd| dd| d|d|dddg dddddddd}t        j                  |       d{   }|j                  d      xs |j                  d      }	|	t        dd       t        j                          |z
  }
t        j                  d!| d"|
d#d$       |	S 7 m# t        $ r  t        $ rm}t        j                          |z
  }
t        j                  d%| d&|
d#d't!        |       d()       t        t"        j$                  d*t!        |              d}~ww xY ww)+uR   Búsqueda de productos con respuesta natural del LLM — orquestado por LangGraph. u   🚀 [z.] === INICIO chat_conversation (LangGraph) ===u   📥 [z] Request: question='NP   z	', count=uuid_conversationquestioncountresume_purchaseplatform_idusuarioredirect_ctx_keyzsearch_redirect_ctx:balance_ctx_keyzsearch_balance_ctx:shown_ctx_keyzsearch_shown_ctx:r+   r,   sessionhistory_messagesis_firstFearly_responseintentresponsei  zEl grafo no produjo respuestar)   detailu   🏁 [z%] === FIN chat_conversation. Tiempo: z.2fzs ===u   ❌ [z] Error tras zs: Texc_infou   Error procesando búsqueda: )timer1   r2   striploggerinfor3   resumePurchase
platformIdr6   r   ainvokegetr   	Exceptionerrorstrr   HTTP_500_INTERNAL_SERVER_ERROR)r*   r+   r,   r-   
start_timeuuidr2   initial_statefinal_stateresultelapsedes               r#   chat_conversationrW   /   sq     J$$D  &B--/H
KK&LMN
KK&3HSbM?)GMM?[\#
,
,
,
 W]],
 w55	,

 7--,
 w,
 "6tf =,
 !4TF;,
 07,
 ,
 ;,
 t,
 ,
 ,
 d,
  d!,
" #,
& /66}EE!12Qkooj6Q>C8WXX))+
*fTF"GPS}TYZ[ F   
))+
*uTF-}CAxHSWX==1#a&:
 	

s?   BG6A>E4 E2A,E4 1G62E4 4G3A(G..G33G6z/conversation-analizec                 T  K   | j                   j                         }|st        d      S 	 t        t              t        |      g}t        j                  |       d{   }|j                  j                         j                         }|j                  d      }t        j                  d|dd  d| d	|        t        |      S 7 j# t        $ rO}t        j                  d
t        |       d       t!        t"        j$                  dt        |             d}~ww xY ww)zLDetermina si una pregunta es sobre productos o recomendaciones de productos.F)rT   )contentNtrueu&   🔍 [conversation_analize] question='r0   u   ' → raw='u   ' → result=u"   ❌ [conversation_analize] Error: TrB   zError analizando pregunta: r@   )r2   rE   r   LCSystemMessager   _HM_llmrJ   rY   lower
startswithrF   rG   rL   rM   rN   r   r   rO   )r*   r-   r2   messagesr?   answerrT   rV   s           r#   conversation_analizerb   b   s     %%'H*%88
$?@!
 h//!!'')//1""6*<Xcr]O;W]V^^klrkstu*&99	 0
  
9#a&BTR==0Q9
 	

s<   )D(4C  C!A)C 
D(C 	D%A
D  D%%D()4__doc__loggingrD   fastapir   r   r   r   langchain_core.messagesr   r\   r   r[   langchain_openair	   modelsr   r   r   r   authr   services.product_servicer   services.flow_servicer   services.identity_servicer   agent.conversation_graphr   agent.conversation_stater   agent.promptsr   config.settingsr   	getLogger__name__rF   
MODEL_NAMEr]   router_identity_svcr&   r    r$   r'   postHTTP_200_OKrN   rW   rb   r!   r"   r#   <module>rx      s[     = = Y '  " 5 / 7 7 6 5 $			8	$++;	'	1  !7	+ ^  _-?VM_M_` $$45")*=">^$	/
/
/
  /
 	/
 a/
d $5P^d^p^pq ^$
'


 r
r"   