
    3h/                     $   d dl mZmZmZmZmZmZ d dlmZ d dl	Z	d dl
Z
d dlZd dlZd dlmZ d dlZd dlZd dl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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* d dl+m,Z, d dl-m.Z. d dl/m0Z0 d dl%m1Z1 d dlmZ d dl2m3Z3 d dl4m5Z5 d dlm6Z6mZ 	  ee7      Z8e8j2                  js                  e        e	jt                  d      e8_;        	  ede3      Z	 d Z<	 d Z=	 e8j}                  d      d         Z?e8j}                  d!d"g#      d$        Z@d%ZAe8j}                  d&d"g#      d'        ZBe8j}                  d(d"g#      d)        ZCe7d*k(  re8j                  d+d,d-.       yy)/    )Flaskrequestjsonifyrender_templatecurrent_appsession)SessionManagerN)datetime)PyPDFLoader)RecursiveCharacterTextSplitter)create_stuff_documents_chain)ChatGroq)Config)ChatPromptTemplateMessagesPlaceholder)HumanMessage)Document)PromptTemplate)FAISS)LLMChain)BaseRetriever)PrivateAttr)RetrievalQA)hub)StrOutputParser)RunnablePassthrough)create_retrieval_chain)
hotelgraph)VectorStore)	AIMessager         )session_expiry_minutes
llm_clientc                     t        d       t        j                  j                  d      } t        j                  j                  d      }t        j                  j                  d      }| r[|rY| dk(  r/|t        j
                  d   k(  rt        j                  d       |dfS t        j                  d	       t        d
dd      dfS t        j                  d       t        d
dd      dfS )NzFROM WHATSAPP..VERIFYING...zhub.modezhub.verify_tokenzhub.challenge	subscribeVERIFY_TOKENWEBHOOK_VERIFIED   VERIFICATION_FAILEDerrorzVerification failedstatusmessagei  MISSING_PARAMETERzMissing parameters  )	printr   argsgetappconfiglogginginfor   )modetoken	challenges      0/home/kushmeetdev/Regenta/Chatbot/testwithweb.pyverifyr<   D   s    	
'(<<J'DLL/0E  1I;5CJJ~,F#FLL+,c>! LL./g:OPQSVVV 	()'6JKLcQQ    c                     t        j                         } | j                  di g      d   j                  di g      d   j                  di       j                  d      r$t        j                  d       t        ddi      d	fS 	 t        |       rt        |        t        ddi      d	fS t        d
dd      fS # t        j                  $ r( t        j                  d       t        d
dd      dfcY S w xY w)a  
    Handle incoming webhook events from the WhatsApp API.

    This function processes incoming WhatsApp messages and other events,
    such as delivery statuses. If the event is a valid message, it gets
    processed. If the incoming payload is not a recognized WhatsApp event,
    an error is returned.

    Every message send will trigger 4 HTTP requests to your webhook: message, sent, delivered, read.

    Returns:
        response: A tuple containing a JSON response and an HTTP status code.
    entryr   changesvaluestatuseszReceived a WhatsAp                                                                                                                                           [p status update.r-   okr)   r+   zNot a WhatsApp API eventr,   zFailed to decode JSONzInvalid JSON providedr0   )r   get_jsonr3   r6   r7   r   is_valid_whatsapp_message"process_whatsapp_message_forAgentsjsonJSONDecodeErrorr+   )bodys    r;   handle_incoming_whatsapp_msgrJ   b   s    D
 	2$"	Y	a	!	Wb		Z	
 	  F  	G$'(#--U$T*.t4Hd+,c11 77QRSV V  U-.'6MNOQTTTUs   $B7 (B7 78C21C2/c                      t        d      S )Nz
index.html)r    r=   r;   indexrN      s    <((r=   z/uploadPOST)methodsc                      t        d       	 t               } t        d       	 y# t        $ r'}t        d|        t        ddi      dfcY d }~S d }~ww xY w# w xY w)NzCreating FAISS store....zvectorStore job done.zJ<div class='alert alert-success'>Knowledebase processed successfully</div>z%Error during query processing FAISS: r+   z/An error occurred during query processing FAISS  )r1   r   	Exceptionr   )vector_storees     r;   upload_documentrV      sl    	$&"}%'[
 		  Z5aS9:!RSTVYYY	Z 	s,   $ 	AA	A
A AA Au  
You are Rumi, a friendly and efficient virtual assistant designed to enhance the guest experience at our hotel called Hotel International. 
Your job is to assists guests with a variety of needs, from booking and reservations to answering questions about hotel
amenities and local attractions.
You will answer questions based on the context provided only. Dont make up an answer.
However, if you cannot confidently answer a query:
Acknowledge that you cannot help directly, Inform the guest that you will log their request with the reception team,
Use the tool_catchall function to log the unresolved query. 

Important Guidelines:
- Always strive to provide the most helpful response possible
- If you do not find a satisfactory answer in the knowledge base:
    - Do not fabricate information
    - Do not guess or provide potentially incorrect information
    - Instead, use the catch-all tool to log the query for reception follow-up

Example Responses for Unresolved Queries:
"I apologize, but I don't have specific information about that. I'll log this request with our reception team, and they will get back to you shortly."
"I'm unable to help with this specific query at the moment. Our reception team will review your request and provide assistance."

Just stick with the context provided. Dont make up an answer. There are examples for you to follow. 
Just use them for your reference. DOnt use them as is when answering.
Always ask guest name and room no  when you greet.
Your Personality Traits:
Friendly and Welcoming: Always greets guests warmly and makes them feel valued.
Efficient and Knowledgeable: Provides quick and accurate information.
Patient and Attentive: Listens carefully to guest inquiries and provides thoughtful responses.
Professional and Polite: Maintains a high standard of professionalism and politeness at all times.
Show empathy when unable to resolve a query
Helpful and Resourceful: Goes the extra mile to assist guests with their needs and find solutions to their problems.
Your Interaction Style:
Greeting: Start with a warm and friendly greeting.
Example: “Hello and welcome to Hotel International! How can I assist you today? May I have your name and room no.”
Assisting with Inquiries:
Be clear and concise in providing information.
Example: “Our fitness center is open 24/7 and is located on the second floor, right next to the spa.”
Handling Requests:
Confirm understanding of the request.
Example: “I understand you would like extra towels sent to your room. I wll arrange that right away.”
Problem-Solving:
Acknowledge the issue and reassure the guest.
Example: “I am sorry to hear you are experiencing this issue. Let me take care of that for you immediately.”
Local Recommendations:
Provide personalized suggestions.s
Example: “If you re looking for a great place to dine, I recommend The Bistro, which is just a 
5-minute walk from the hotel?”

Your Key Functions:
Reservation Management:
Assist with booking rooms, modifying reservations, and checking availability.
Information Provider:
Provide details about hotel amenities, services, and policies.
Example: pool hours, Wi-Fi password, dining options.
Concierge Services:
Recommend local attractions, dining options, and transportation services.
Example: arrange taxis, suggest sightseeing tours.
Room Service Requests:
Handle guest requests for additional amenities, housekeeping, and room service.
YOur eedback Collection:
Gather guest feedback to improve services.
Example: “How was your stay with us? We would love to hear your feedback!”

Example Dialogue for your reference:
Guest: “Hi, I need to know the check-out time, please.” Rumi: “Greetings! Our check-out time is 11 AM. If you need a late check-out, please let me know and I’ll check the availability for you.”
Guest: “Can you recommend a good place for breakfast nearby?” Rumi: “Of course! There’s a wonderful café called Sunrise Bistro just around the corner. They serve delicious breakfast and freshly brewed coffee. Would you like directions?”
Guest: “I need extra pillows and a blanket in my room.” Rumi: “Absolutely, I’ll have extra pillows and a blanket sent to your room right away. Is there anything else I can assist you with?”
<context>
{context}
</context>
z/queryc                     t         j                  j                  d      } t         j                  j                  d      }|s"t        j	                         }t        d|z          	 t        j                  dt        |       gidd|ii      }|d   d   j                  }t        d	| d
|d      S # t        $ rO}t        dt        |              t        j                  |       t        dt        |      d      dfcY d }~S d }~ww xY w)Nquery
session_idznew session id is messages)contentconfigurable	thread_idz<p>z</p>)htmlrY   zError in query_document: r+   r,   rR   )r   formr3   session_managercreate_sessionr1   r   invoker   r[   r   rS   strclose_session)
query_textrY   responseassistant_responserU   s        r;   query_documentri      s   !!'*J!!,/J $335
"Z/0$$,z:;<k:67 &j1"5== ,-T2$
  	
  )#a&23%%j11v
   		s    $A
B/ /	D8AD<DDz/close_sessionc                  6   t         j                  j                  d      } | r#	 t        j	                  |        t        ddi      S t        ddd      d	fS # t        $ r:}t        dt        |              t        dt        |      d      dfcY d }~S d }~ww xY w)
NrY   r-   successzError in close_session route: r+   r,   rR   zNo session ID providedr0   )	r   r`   r3   ra   re   r   rS   r1   rd   )rY   rU   s     r;   re   re     s    !!,/J	H))*5Hi011 g2JKLcQQ  	H23q6(;<g#a&ABCGG	Hs   !A 	B/BBB__main__z157.173.210.15i  T)hostportdebug)Eflaskr   r   r   r   r   r   ra   r	   osrequestsreuuidr
   timer6   rG   $langchain_community.document_loadersr   langchain.text_splitterr   "langchain.chains.combine_documentsr   langchain_groqr   r5   r   langchain_core.promptsr   r   langchain_core.messagesr   langchain.schemar   r    langchain_community.vectorstoresr   langchain.chainsr   r   pydanticr   r   	langchainr   langchain_core.output_parsersr   langchain_core.runnablesr   r   chatbotr   rT   r   r    __name__r4   from_objecturandom
secret_keyr<   rJ   routerN   rV   SYSTEM_TEMPLATEri   re   runrM   r=   r;   <module>r      s   P P * 
  	      < B K #  J 0 % 1 2 % *   (  9 8 3 K  $ ;? Ho 

  v B !
SR0'UP 3) ) 9vh'
 (
EN 8fX& 'B fX.	R /	R zGG!4G8 r=   