a
    bgO                     @   sD  d dl 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	m
Z
mZmZm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 d dlmZmZ d dlmZ d dlm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& e'e(Z)dZ*dZ+dZ,G dd de-eZ.ee#e&f dddZ/e-dddZ0G dd deZ1dS )    N)Enum)
HTTPStatus)AnyDictListOptionalTuple)ClientTimeout)Document)get_runtime_environment)get_from_dict_or_env)VectorStoreRetriever)	BaseModel)Responserequest)RequestException)AppAuthContextContext	FrameworkPromptQaRuntimez0.1.1zhttp://localhost:8000zhttps://api.daxa.aic                   @   s   e Zd ZdZdZdZdZdS )Routesz2Routes available for the Pebblo API as enumerator.z/v1/app/discoverz
/v1/promptz/v1/prompt/governanceN)__name__
__module____qualname____doc__retrieval_app_discoverpromptprompt_governance r!   r!   /var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain_community/chains/pebblo_retrieval/utilities.pyr   %   s   r   )returnc                  C   s   t  } td| ddd}t }t|jtjd | dd|j	|j
t | dd| d	dd
}d|jv rvd|_d|_td|  td|  ||fS )zFetch the current Framework and Runtime details.

    Returns:
        Tuple[Framework, Runtime]: Framework and Runtime for the current app instance.
    Z	langchainZlibrary_versionN)nameversionZPWDplatformunknownruntimeZruntime_version)hostpathr&   os
os_versioniplanguageZlanguage_versionDarwinZdesktopzMac OSXz
framework zruntime )r   r   getr&   unamer   noder+   environsystemr%   get_iptyper(   loggerdebug)Zruntime_envZ	frameworkr1   r(   r!   r!   r"   get_runtime-   s*    



r9   c                  C   s@   ddl } |  }z| |}W n ty:   | d}Y n0 |S )zJFetch local runtime ip address.

    Returns:
        str: IP address
    r   N	localhost)socketgethostnamegethostbyname	Exception)r;   r)   Z	public_ipr!   r!   r"   r5   L   s    r5   c                       s  e Zd ZU dZee ed< dZeed< ee ed< ee ed< ed fdd	Z	e
d
dddZd'eeeeee ee eeef eed
d
ddZd(eeeeee ee eeef eed
d
ddZeeeeeef f dddZeeeeeef f dddZd)eedddZed*eeeee eee dddZeeee d
d d!d"Zed+eeeee eedd#d$Zd,eeeeee ee eeef eeed
d%d&Z  Z S )-PebbloRetrievalAPIWrapperz!Wrapper for Pebblo Retrieval API.api_keylocalclassifier_locationclassifier_url	cloud_url)kwargsc                    sL   t |ddd|d< t |ddt|d< t |ddt|d< t jf i | dS )	z%Validate that api key in environment.r@   ZPEBBLO_API_KEY rC   ZPEBBLO_CLASSIFIER_URLrD   ZPEBBLO_CLOUD_URLN)r   _DEFAULT_CLASSIFIER_URL_DEFAULT_PEBBLO_CLOUD_URLsuper__init__)selfrE   	__class__r!   r"   rJ   h   s    z"PebbloRetrievalAPIWrapper.__init__N)appr#   c           	      C   s   d}|j dd}| jdkrD|  }| j tjj }| d|||}| jr| jdd}|rzt	
|jd}|d|i |dti | j tjj }| d|||}dS )	z
        Send app discovery request to Pebblo server & cloud.

        Args:
            app (App): App instance to be discovered.
        NTZexclude_unsetrA   POSTcloud_requestpebblo_server_versionZpebblo_client_version)dictrB   _make_headersrC   r   r   valuemake_requestr@   jsonloadstextr0   updatePLUGIN_VERSIONrD   )	rK   rN   pebblo_resppayloadheadersZapp_discover_urlrS   Zpebblo_cloud_url_r!   r!   r"   send_app_discoveru   s"    
z+PebbloRetrievalAPIWrapper.send_app_discoverF)
app_name	retrieverquestionanswerauth_contextdocsprompt_entitiesprompt_timeprompt_gov_enabledr#   c
                 C   s   d}
|  |||||||||		}| jdkrR|  }| j tjj }| d|||}
| jr| jdkr~|
rn|
	 nd}
| 
||
 | jdd}| j tjj }| d|||}n| jdkrtd tddS a  
        Send prompt to Pebblo server for classification.
        Then send prompt to Daxa cloud(If api_key is present).

        Args:
            app_name (str): Name of the app.
            retriever (VectorStoreRetriever): Retriever instance.
            question (str): Question asked in the prompt.
            answer (str): Answer generated by the model.
            auth_context (Optional[AuthContext]): Authentication context.
            docs (List[Document]): List of documents retrieved.
            prompt_entities (Dict[str, Any]): Entities present in the prompt.
            prompt_time (str): Time when the prompt was generated.
            prompt_gov_enabled (bool): Whether prompt governance is enabled.
        NrA   rP   TrQ   zpebblo-cloudz6API key is missing for sending prompt to Pebblo cloud.)build_prompt_qa_payloadrB   rU   rC   r   r   rV   rW   r@   rX   update_cloud_payloadrD   r7   warning	NameErrorrK   rb   rc   rd   re   rf   rg   rh   ri   rj   r]   r^   r_   Z
prompt_urlZpebblo_cloud_prompt_urlr`   r!   r!   r"   send_prompt   s4    



z%PebbloRetrievalAPIWrapper.send_promptc
                    s   d}
|  |||||||||		}| jdkrX|  }| j tjj }| d|||I dH }
| jr| jdkrt| 	||
 | jdd}| j
 tjj }| d|||I dH }n| jdkrtd tddS rk   )rl   rB   rU   rC   r   r   rV   amake_requestr@   rm   rD   r7   rn   ro   rp   r!   r!   r"   asend_prompt   s6    



z&PebbloRetrievalAPIWrapper.asend_prompt)rd   r#   c                 C   s~   d|i}i dd}d}| j dkrv|  }| j tjj }| d|||}|rv| di |d< | dd|d< ||fS )	  
        Check the validity of the given prompt using a remote classification service.

        This method sends a prompt to a remote classifier service and return entities
        present in prompt or not.

        Args:
            question (str): The prompt question to be validated.

        Returns:
            bool: True if the prompt is valid (does not contain deny list entities),
            False otherwise.
            dict: The entities present in the prompt
        r   r   entitiesentityCountTrA   rP   rv   rw   )	rB   rU   rC   r   r    rV   rW   rX   r0   rK   rd   Zprompt_payloadrh   Zis_valid_promptr_   Zprompt_gov_api_urlr]   r!   r!   r"   check_prompt_validity  s     

z/PebbloRetrievalAPIWrapper.check_prompt_validityc                    s|   d|i}i dd}d}| j dkrt|  }| j tjj }| d|||I dH }|rt|di |d< |d	d|d	< ||fS )
rt   r   r   ru   TrA   rP   Nrv   rw   )rB   rU   rC   r   r    rV   rr   r0   rx   r!   r!   r"   acheck_prompt_validity0  s    


z0PebbloRetrievalAPIWrapper.acheck_prompt_validity)rR   r#   c                 C   s4   ddd}|r0| j r&|d| j i n
td |S )z
        Generate headers for the request.

        args:
            cloud_request (bool): flag indicating whether the request is for Pebblo
            cloud.
        returns:
            dict: Headers for the request.

        zapplication/json)AcceptzContent-Typez	x-api-keyz,API key is missing for Pebblo cloud request.)r@   r[   r7   rn   )rK   rR   r_   r!   r!   r"   rU   Q  s    
z'PebbloRetrievalAPIWrapper._make_headers   )methodurlr_   r^   timeoutr#   c              
   C   s   zt | ||||d}td| |j jtt|j jr6|j jng t|j |jtj	krht
d|j  n>|jtjkrt
d|j  n|jtjkrt
d|j  |W S  ty   t
d| Y n0 ty } zt
d| W Y d}~n
d}~0 0 dS )	a  
        Make a request to the Pebblo server/cloud API.

        Args:
            method (str): HTTP method (GET, POST, PUT, DELETE, etc.).
            url (str): URL for the request.
            headers (dict): Headers for the request.
            payload (Optional[dict]): Payload for the request (for POST, PUT, etc.).
            timeout (int): Timeout for the request in seconds.

        Returns:
            Optional[Response]: Response object if the request is successful.
        )r}   r~   r_   rX   r   z5Request: method %s, url %s, len %s response status %sPebblo Server: Error $Pebblo received an invalid payload: -Pebblo returned an unexpected response code: Unable to reach server %sz'An Exception caught in make_request: %sN)r   r7   r8   r~   strlenbodystatus_coder   INTERNAL_SERVER_ERRORrn   BAD_REQUESTrZ   OKr   r>   )r}   r~   r_   r^   r   responseer!   r!   r"   rW   h  s6    
"z&PebbloRetrievalAPIWrapper.make_request)r^   r]   r#   c                 C   s   |r|  di }|| di  di  |dd |  di }|| di  di  |dd |  dg }|D ]}|dd qxni | d< i | d< g | d< dS )z
        Update the payload with response, prompt and context from Pebblo response.

        Args:
            payload (dict): Payload to be updated.
            pebblo_resp (Optional[dict]): Response from Pebblo server.
        r   Zretrieval_datadataNr   contextdoc)r0   r[   pop)r^   r]   r   r   r   Zcontext_datar!   r!   r"   rm     s    	z.PebbloRetrievalAPIWrapper.update_cloud_payloadc           
   
      sX  z t |d}t 4 I dH }|j| ||||d4 I dH }|jtjkr^td|j  n>|jtj	kr~td|j
  n|jtjkrtd|j  | I dH }W d  I dH  q1 I dH s0    Y  W d  I dH  q1 I dH s0    Y  |W S  ty"   td| Y n2 tyR }	 ztd|	 W Y d}	~	n
d}	~	0 0 dS )	a  
        Make a async request to the Pebblo server/cloud API.

        Args:
            method (str): HTTP method (GET, POST, PUT, DELETE, etc.).
            url (str): URL for the request.
            headers (dict): Headers for the request.
            payload (Optional[dict]): Payload for the request (for POST, PUT, etc.).
            timeout (int): Timeout for the request in seconds.

        Returns:
            Any: Response json if the request is successful.
        )totalN)r}   r~   rX   r_   r   r   r   r   r   z(An Exception caught in amake_request: %s)r	   aiohttpZClientSessionr   statusr   r   r7   rn   r   rZ   r   rX   r   r>   )
r}   r~   r_   r^   r   Zclient_timeoutZasessionr   Zresponse_jsonr   r!   r!   r"   rr     s<    

b"z'PebbloRetrievalAPIWrapper.amake_requestc
              
      st   t | fdd|D t||di |dd|	dt|d||rF|jnd|r\t|d	r\|jng | jd
}
|
jddS )a  
        Build the QA payload for the prompt.

         Args:
            app_name (str): Name of the app.
            retriever (VectorStoreRetriever): Retriever instance.
            question (str): Question asked in the prompt.
            answer (str): Answer generated by the model.
            auth_context (Optional[AuthContext]): Authentication context.
            docs (List[Document]): List of documents retrieved.
            prompt_entities (Dict[str, Any]): Entities present in the prompt.
            prompt_time (str): Time when the prompt was generated.
            prompt_gov_enabled (bool): Whether prompt governance is enabled.

        Returns:
            dict: The QA payload for the prompt.
        c              	      sH   g | ]@}t |trt|jd |jd|j jjj|jddqS )	full_pathsourcepb_checksum)Zretrieved_fromr   Z	vector_dbr   )	
isinstancer
   r   metadatar0   Zpage_contentZvectorstorerM   r   ).0r   rc   r!   r"   
<listcomp>  s   	

zEPebbloRetrievalAPIWrapper.build_prompt_qa_payload.<locals>.<listcomp>rv   rw   r   )r   rv   rw   rj   )r   r'   	user_auth)r$   r   r   r   ri   userZuser_identitiesrB   TrO   )r   r   r0   Zuser_idhasattrr   rB   rT   )rK   rb   rc   rd   re   rf   rg   rh   ri   rj   Zqar!   r   r"   rl     s,    
	

z1PebbloRetrievalAPIWrapper.build_prompt_qa_payload)F)F)F)Nr|   )Nr|   )F)!r   r   r   r   r   r   __annotations__rB   r   rJ   r   ra   r   r   r   r
   r   boolrq   rs   r   ry   rz   rT   rU   staticmethodintr   rW   rm   rr   rl   __classcell__r!   r!   rL   r"   r?   \   s   
) 
G 
> "!  1  ; 
r?   )2rX   loggingr+   r&   enumr   httpr   typingr   r   r   r   r   r   r	   Zlangchain_core.documentsr
   Zlangchain_core.envr   Zlangchain_core.utilsr   Zlangchain_core.vectorstoresr   Zpydanticr   requestsr   r   Zrequests.exceptionsr   Z2langchain_community.chains.pebblo_retrieval.modelsr   r   r   r   r   r   r   	getLoggerr   r7   r\   rG   rH   r   r   r9   r5   r?   r!   r!   r!   r"   <module>   s0   $

