
     hfF                     n   d dl Z d dlZd dlmZmZ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  e              e
j        d          Z e	e          Zed	efd
            Zed             Zededefd            Zededefd            Zededefd            Zededefd            Zededefd            Zededefd            Zedefd            Z eddeeg          Z eddeeg          Z  edd eeg          Z! ed!d"eeg          Z" ed#d$e!e"ee geeg%          Z#dS )&    N)AgentRunnerfunction_tool)SQLDatabase)OpenAI)	b64encode)load_dotenvOPENAI_API_KEY)api_keye_mailc           	      p    d}d| i}ddddddd	d
d}t          j        |||          }t          |          S )Nz,https://api.sistemaml.net/app/password/emailemailno-cachePostmanRuntime/7.43.4*/*gzip, deflate, br
keep-aliveuser_compratelia
1nt3l14p1$!application/x-www-form-urlencoded)Cache-Control
User-AgentAcceptAccept-Encoding
Connectionr   passwordContent-Typedataheaders)requestspoststr)r   urlpayloadr    responses         /var/www/FlaskApp/agent_test1.pyreset_passwordr(   .   s_    
8C 	G $-."":	 	G }Sw@@@Hx==    c                      dS )Nz2Please wait while your request its been processing r+   r)   r'   wait_messager,   G   s    ??r)   Access_tokenuser_idc           
      \   d| }d|  dddddd}t          |           t          |            t          j        ||	          }|                                }g }|                    d
g           D ]l}|                    |                    dd          |                    dd          |                    dd          |                    dd          d           mdt          |           dt          |          |d}t          t          |                     t          |          S )Nz,https://api.sistemaml.net/app/preAlert/list/Bearer r   r   r   r   r   Authorizationr   r   r   r   r   r    r   tracking descriptionpriceinstructions)r4   r6   r7   r8   Tz prealertas encontrados.)successmessagetotalr   )printr!   getjsonappendlenr#   )	r-   r.   r$   r    r&   response_data	prealertsitemoutputs	            r'   prealertlist_processrE   K   sX    C
B
BC .|--)* G 
'NNN	, |C000HMMOOMI!!&"--  R0088M266XXgr** HH^R88	
 
 	 	 	 	 )nn>>>Y	 F 
#f++v;;r)   c                    d| }d|  dddddd}t          j        ||	          }|                                }g }d
}|                    dg           D ]w}|                    dg           D ]^}	|	                    dd          |	                    dd          |	                    dd
          d}
|                    |
           |dz  }_x||d}t	          t          |                     t          |          S )Nz'https://api.sistemaml.net/app/shs/list/r0   r   r   r   r   r   r1   r3   r   r   shsubs	contenidor5   tipolibras)rH   rI   rJ      )total_shsubspackages)r!   r=   r>   r?   r<   r#   )r-   r.   r$   r    r&   r   resultrL   packageshsubentryrD   s               r'   shsList_processrR   u   s>   
=G
=
=C .|--)* G |C000H==??D F L 88FB'' 	 	[[2.. 	 	E"YY{B77		&"--))Ha00 E
 MM%   ALL	 % F 
#f++v;;r)   c                    d| }d|  dddddd}t          j        ||	          }t          |j                   |                                }g }d
}|                    dg           D ]}|                    dd          }	|                    dd          }
|                    dd          }|                    dg           D ]a}|	|
||                    dd          |                    dd          |                    dd
          d}|                    |           |dz  }b||d}t          t          |                     t          |          S )Nz'https://api.sistemaml.net/app/wrs/list/r0   r   r   r   r   r   r1   r3   r   r   r4   r5   id
verificadowrsubsrH   rI   rJ   )r4   	wr_numberrU   rH   rI   rJ   rK   )total_wrsubsrM   )r!   r=   r<   textr>   r?   r#   )r-   r.   r$   r    r&   r   rN   rX   rO   r4   WRrU   wrsubrQ   rD   s                  r'   wrsList_processr\      s   
=G
=
=C .|--)* G |C000H	(- ==??D F L 88FB''  ;;z2..;;tB;;|B//
[[2.. 
	 
	E$'"YY{B77		&"--))Ha00 E MM%   ALL
	 % F
 
#f++v;;r)   usrEmailusrPassc                    d}dd| |d}ddi}t          j        |||          }t          |j                   	 |                                }|                    d          rd	|v r|d	                             d
          }|d	         d                             d          }|d	         d                             d          }	|d	         d                             d          }
|||	|
|                    dd          dS d|                    dd          iS # t          $ r}ddt          |           icY d }~S d }~ww xY w)Nz#https://api.sistemaml.net/app/loginr   r   )r   r   app_usernameapp_passwordr   r   r   r9   r   access_tokenuserrT   agentidRnamer:   zLogin success.)rb   r.   agent_idclient_namer:   errorzAuthentication failed.zFailed to parse response: )r!   r"   r<   rY   r>   r=   	Exceptionr#   )r]   r^   r$   r%   r    r&   r   tokenr.   rg   rf   es               r'   get_credentialsrm      s   
/C $  	 G 	;G
 }Sw@@@H	(-
}}88I 	6T>>L$$^44E6l6*..t44GF|G,0077Hff%))&11D !&"$"88I/?@@   )-EFF   
 
 
:#a&&::
 	
 	
 	
 	
 	
 	

s$   CD D 
E#D<6E<Elatitude	longitudec                 p    t          j        d|  d| d          }|                                }|d         S )zNReturns the weather including temperature and wind speed for a given location.0https://api.open-meteo.com/v1/forecast?latitude=&longitude=z&&current=temperature_2m,wind_speed_10mcurrentr!   r=   r>   rn   ro   r&   r   s       r'   get_weatherrv   
  sW     | 	B8  	B  	BPY  	B  	B  	B H ==??D	?r)   c                     t          j        d|  d| d          }|                                }d|d         d         iS )z1Returns only the wind speed for a given location.rq   rr   z&current=wind_speed_10m
wind_speedrs   wind_speed_10mrt   ru   s       r'   get_windspeedrz     sP     |r8rrPYrrr H ==??D$y/*:;<<r)   questionc                 8   d}t          j        |          }|                                }t          |           ddddd| d|  ddg}t          j        j                            d	|d
g          }|j        d         j	        j
        }t          j        d|t          j                  }|rl|                    d                                          }t          |           	 |                    |          }	|	S # t"          $ r}
dd|
 icY d}
~
S d}
~
ww xY wddiS )zOGenerates and executes a SQL query based on the given schema and user question.zLmysql+pymysql://hernanusera:XSCfC68HbltowIt?.,@3.134.237.40:3306/sistemamldbsystemz0You are a helpful AI that generates SQL queries.)rolecontentrc   zSchema:
z

Question: z

SQL Query:zgpt-4o-miniz
SQLResult:)modelmessagesstopr   z```sql\n(.*?)\n```rK   ri   zError executing SQL query: Nz!No SQL query found in the result.)r   from_uriget_table_infor<   clientchatcompletionscreatechoicesr:   r   researchDOTALLgroupstriprunrj   )r{   	mysql_uridbschemar   r&   rN   query_match	sql_queryquery_resultrl   s              r'   SQL_Toolr     sc   & _I 
	i	(	(B  F	&MMM &XYY$^$^$^h$^$^$^__H {&--MH\j[k-llHa (0F )1629EEK 	@%%a((..00	i	@66),,L ! 	@ 	@ 	@>1>>???????	@ 899s   #C: :
DD
DD	wrs_agenta5  
        You are responsible for processing warehouse receive services or "wrs", these are the information of the packages received in the warehouse that belong to the customer. 
        Use the tool call `wrsList_process` to get the list of packages that the customer have in warehouse.
        The information need it to process the request is the "access_token": token and "user_id": user_id that were obtain in the respond of the get_credentials tool.
        Always request new "access_token" using the tool "get_credentials" before use "wrsList_process".
    )rf   r8   tools	shs_agentaJ  
        You are responsible for processing shipment services or "shs", these are the information of the packages that have been sent from the warehouse to the customer. 
        Use the tool call `shsList_process` to get the list of packages that have been sent to the customer from the warehouse already.
        The information need it to process the request is the "access_token": token and "user_id": user_id that were obtain in the respond of the get_credentials tool
        Always request new "access_token" using the tool "get_credentials" before use "shsList_process"
        prealert_agentaJ  
        You are responsible for processing prealert services. these are the information of the packages that are ready to be sent from the warehouse to the customer.
        Use the tool call `prealertlist_process` to get the list of packages that are ready to be sent to the customer from the warehouse.
        The information need it to process the request is the "access_token": token and "user_id": user_id that were obtain in the respond of the get_credentials tool
        Always request new "access_token" using the tool "get_credentials" before use "prealertlist_process"
    Weather_AgentzYou are a helpful agent to provide temperature and windspeed for any place in the world, using coordinates, find the coordinate of the location in the internet.zTriage agenta  
General Behavior  
Always maintain a polite, professional, and friendly tone when speaking with customers.  

Begin each interaction with a greeting and offer assistance.  

Never proceed with any service or action until the customer has been authenticated.  

---

2. Authentication Flow  
Before taking any action, validate the customer using the following steps:  

**a. Request Credentials**  
Ask the customer to provide their username and password.  

Use the tool called `get_credentials` to validate the credentials once they are received.  

Example:  
"Before we proceed, could you please provide your username and password so I can verify your account?"  

**b. Use get_credentials Tool**  
Send the username and password to the `get_credentials` tool.  

Wait for the response.  

**c. Handle Response**  
- If the response indicates **valid credentials**:  
    - Politely confirm to the customer that their credentials are valid.  
    - Address the customer by their name going forward.  
    - Save the `id` and `name` values returned in the JSON response for future reference in the session.  

    Example:  
    "Thank you, [Customer Name]. Your credentials are valid. How can I assist you today?"  

- If the response indicates **invalid credentials**:  
    - Politely inform the customer and ask them to try again.  

    Example:  
    "It looks like the credentials you provided are not correct. Could you please try again?"  

    - After **three failed attempts**, offer the customer the option to create a temporary password using their email.  

    Example:  
    "It seems you've entered invalid credentials multiple times. Would you like to reset your password and receive a temporary one via email?"  

    - If the customer agrees:  
        - Ask for their email address.  
        - Use the `reset_password` tool with the provided email.  
        - Inform the customer:  
          "A temporary password has been sent to your email. Please check your inbox and provide the new credentials here so I can verify your account."  

---

3. After Authentication  
Only after the customer has been successfully authenticated:  
- Extract from the JSON the `name` and `id` of the customer and save those values.  
- Proceed with handling their request or routing to a specialized agent.  
- Use their name in a respectful and personalized manner throughout the conversation.  
- Retain the authenticated `id` and `name` in memory during the session for logging and reference.  

---

4. Routing to Specialized Agents  
- If the customer wants to know the list of packages they have already prealerted or uses phrases like "prealerta" or "obtener una lista de paquetes en prealerta", route the customer to the `prealert_agent`.  

- If the customer wants to know if they have packages currently in the warehouse, route them to the `wrs_agent`.  
  Always ensure that the "verificado" value is included in the response for each package. Present the information as follows:

    - Tracking  
    - WR_number  
    - Weight (or "peso")  
    - Content (or "contenido")  
    - Verificado: include the value of the "verificado" variable:
        - If "verificado" is 0:  
          "Customer needs to provide the invoice of the package."
        - If "verificado" is 1:  
          "Waiting for customer to request shipment."

- If the customer wants to know about packages that have already been sent from the warehouse, route them to the `shs_agent`.  

- Reroute all relevant request information to the last agent.
)rf   r8   handoffsr   )$asyncior!   agentsr   r   r   langchain_community.utilitiesr   openair   osr   base64r   dotenvr	   getenvr   r   r#   r(   r,   intrE   rR   r\   rm   floatrv   rz   r   r   r   r   Weather_agenttriage_agentr+   r)   r'   <module>r      s/     / / / / / / / / / / 5 5 5 5 5 5       				 				              ")$
%
%		 	 	 4 #    0 @ @ @ 'c '3 ' ' ' 'R ) )c ) ) ) )X 3 3c 3 3 3 3p +
S +
# +
 +
 +
 +
\ % E     =E =e = = = = /:s /: /: /: /:d E	 ?
+	 	 		 E	 ?
+	 	 		 	 /
0	 	 	: 	 t
&   u	Rf ]9Y?>
*mW W Wr)   