
    H5j`                      r    d dl mZ d dlmZ d dlmZ d dlZd dlZd dlmZ d dl	m	Z	 dZ
dZd	 Zd
 Zd Zd ZdS )    )Chroma)ChatPromptTemplate)OllamaN)datetime)get_embedding_functionchromaa  
You are DGDelizie's customer service assistant.

Use the provided context to answer questions about DGDelizie.

If the user sends greetings, casual conversation, or messages that do not require documentation context, respond naturally and politely in the same language as the user.

If the answer is not in the context, politely say you do not have that information instead of inventing it.

Context:
{context}

Question:
{question}
c                 n   | sdS g }| D ]}|                     dd          }|                     dd          }|dk    r|                    d|            M|dk    r|                    d|            l|                    |                                 d|            d	                    |          S )
zDConvert a list of message dicts into a readable conversation string. roleusercontentz
Customer: 	assistantzAssistant: z: 
)getappend
capitalizejoin)messageslinesmsgr   r   s        $/var/www/FlaskApp/Agent_DGDelizie.pyformat_conversation_historyr      s     rE < <wwvv&&'')R((6>>LL/g//0000[  LL0w001111LLDOO--::::;;;;99U    c                 :   | r8| d         d         dk    r&| d         d         }t          | dd                   }nt          |           }d}t                      }t          t          |          }|                    |d	          }d
                    d |D                       }t          j        |          }|                    |||          }	t          dd          }
|

                    |	          }d |D             }d| d| }t          |           |S )u   
    conversation_history: list of dicts with 'role' and 'content'
    new_query: the latest user message (string) – may already be the last message in history
    r   r   r   Na6  
You are DGDelizie's customer service assistant.

Use the following conversation history (if any) and the provided documentation context to answer the customer's latest question.

If the user sends greetings, casual conversation, or messages that do not require documentation context, respond naturally and politely in the same language as the user.

If the answer is not in the context, politely say you do not have that information instead of inventing it.

Conversation history:
{history}

Documentation context:
{context}

Customer's latest question: {question}
)persist_directoryembedding_function   )kz

---

c                 "    g | ]\  }}|j         S  )page_content.0doc_scores      r   
<listcomp>z*query_rag_with_history.<locals>.<listcomp>R   s    &S&S&SKCs'7&S&S&Sr   )historycontextquestionzhttp://104.189.92.139:10500zgemma4:latest)base_urlmodelc                 J    g | ] \  }}|j                             d d          !S )idN)metadatar   r#   s      r   r'   z*query_rag_with_history.<locals>.<listcomp>^   s.    GGGVs|d++GGGr   z
Response: z

Sources: )r   r   r   CHROMA_PATHsimilarity_search_with_scorer   r   from_templateformatr   invokeprint)conversation_history	new_queryhistory_textPROMPT_TEMPLATEr   dbresultscontext_textprompt_templatepromptr,   response_textsourcesformatted_responses                 r   query_rag_with_historyrB   .   sQ     I 4R 8 @F J J(,Y7	23G3LMM23GHHO& 011	+BT	U	U	UB--i1-==G %%&S&S7&S&S&STTL(6GGO## $  F 9QQQELL((MGGwGGGGImIIII	
r   c                    d}d}d}d}t          | t                    rd| dg} t          |           D ]H}	t          |	t                    r1|	                    d          dk    r|	                    dd          } nIt          |           D ]X}	t          |	t                    rA|	                    dd                              d          r|	                    dd          } nYt          |           D ]}	t          |	t                    r|	                    d          d	k    r|	                    d
d          }
t          |
t                    rV	 t          j        |
          }t          |t                    rd|v rt          |d                   } n# t          $ r Y w xY wt          j
                                        d          }d|||||d}d}d}dddd}t          j        d|||d          }|                                }|d         }d}d| ddddddd }t          j        |||!          }|                                }t!          |           d S )"Nr
   r   )r   r   r   r   r.   msg_typefunction_call_outputoutputuser_idz%Y-%m-%d %H:%M:%S
msg_123456)
message_idassistant_responsecustomer_idmessage_botphone_numberphone_number_idz(https://crmiq.sistemaml.org/api/v1/loginzuser=soporte&password=s0p0rt3z!application/x-www-form-urlencodedzno-cachez$5b949b74-4434-a3fb-4e91-33f22b22f02c)zcontent-typezcache-controlzpostman-tokenPOST<   )dataheaderstimeouttokenz.https://crmiq.sistemaml.org/api/v1/message/botzBearer zPostmanRuntime/7.44.0zapplication/jsonz*/*zgzip, deflate, brz
keep-alive)AuthorizationzCache-Controlz
User-AgentzContent-TypeAcceptzAccept-Encoding
Connection)jsonrS   )
isinstancestrreverseddictr   
startswithastliteral_eval	Exceptionr   nowstrftimerequestsrequestrY   postr5   )
input_dataCustomerPhone	respuestarN   rO   last_msg_idlast_user_messagelast_assistant_messagerH   itemrG   	user_data	timestampjson_payloadurlpayloadrS   response	json_dataaccess_tokenresponse_datas                        r   chat_monitorrw   c   s    KG *c"" 
 % 

 $$  dD!! 	dhhv&6&6&&@&@ $B 7 7E $$  dD!! 	dhhtR&8&8&C&CF&K&K 	((4,,KE $$ 
 
dD!! 		dhhv&6&6:P&P&PXXh++F&#&&  # 0 8 8I!)T22 yI7M7M"%i	&:";";    H  ''(;<<I #/$ $* L 5C6G 8; G
 '7SUVVVHI W%L
 
:C .|--)%* G }Sl7CCCHMMOOM	-s   AF
F! F!c                 z  K   t          | t                    rg }| }nlt          | t                    rH| }d}t          |          D ]3}|                    d          dk    r|                    dd          } n4nt          d          t          ||          }t          |           t          | ||||           |S )u   
    input_data can be either:
        - a string (first message) – no history
        - a list of message dicts (full conversation history)
    r
   r   r   r   zinput_data must be str or list)	rZ   r[   listr\   r   	TypeErrorrB   r5   rw   )rg   rh   rN   rO   r6   latest_messager   ri   s           r   AgentDGDelizier|      s       *c"" :!#	J	%	% 
:)011 	 	Cwwv&((!$B!7!7 ) 8999&';^LLI	)]I|_UUUr   ) langchain_community.vectorstoresr   langchain.promptsr   langchain_community.llms.ollamar   rd   r_   r   r   r0   r9   r   rB   rw   r|   r!   r   r   <module>r      s    3 3 3 3 3 3 0 0 0 0 0 0 2 2 2 2 2 2  



       9 9 9 9 9 9   3 3 3jf f fR    r   