o
    ZhFQ                     @   sZ  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mZ d dlmZ d dlmZmZ d dlmZmZ d d	lmZmZmZmZmZ d
ZG dd deZ G dd de!eZ"G dd dZ#G dd de#Z$G dd de$Z%G dd de#Z&G dd de#Z'G dd de#Z(G dd de(Z)G dd deZ*G dd  d ee*Z+dS )!    N)abstractmethod)Enum)AnyDictListMappingOptional)CallbackManagerForLLMRun)BaseLLM)
Generation	LLMResult)convert_to_secret_strget_from_dict_or_env)	BaseModel
ConfigDict	SecretStrmodel_validator	validator2   c                   @   sV   e Zd ZdZdefdededededdf
d	d
Z	ddede	e
 dedefddZdS )AzureMLEndpointClientz AzureML Managed Endpoint client. endpoint_urlendpoint_api_keydeployment_nametimeoutreturnNc                 C   s,   |r|st d|| _|| _|| _|| _dS )zInitialize the class.zXA key/token and REST endpoint should 
                be provided to invoke the endpointN)
ValueErrorr   r   r   r   )selfr   r   r   r    r   `/var/www/html/lang_env/lib/python3.10/site-packages/langchain_community/llms/azureml_endpoint.py__init__   s   
zAzureMLEndpointClient.__init__bodyrun_managerkwargsc                 K   s\   dd| j  d}| jdkr| j|d< tj| j||}tjj||d| jd}|	 }|S )zcall.application/jsonzBearer )zContent-TypeAuthorizationr   zazureml-model-deploymentr   )r   )
r   r   urllibrequestRequestr   urlopengetr   read)r   r!   r"   r#   headersreqresponseresultr   r   r   call&   s   

zAzureMLEndpointClient.callN)__name__
__module____qualname____doc__DEFAULT_TIMEOUTstrintr    bytesr   r	   r   r0   r   r   r   r   r      s2    
r   c                   @   s   e Zd ZdZdZdZdZdS )AzureMLEndpointApiTypezAzure ML endpoints API types. Use `dedicated` for models deployed in hosted
    infrastructure (also known as Online Endpoints in Azure Machine Learning),
    or `serverless` for models deployed as a service with a
    pay-as-you-go billing or PTU.
    	dedicatedrealtime
serverlessN)r2   r3   r4   r5   r;   r<   r=   r   r   r   r   r:   @   s
    r:   c                	   @   s   e Zd ZU dZ	 dZee ed< 	 dZee ed< 	 dZ	eed< e
dedefd	d
Zedee fddZejfdedededefddZeejfdededefddZdS )ContentFormatterBasezZTransform request and response of AzureML endpoint to match with
    required schema.
    r$   content_typeacceptszError while formatting response payload for chat model of type  `{api_type}`. Are you using the right formatter for the deployed  model and endpoint type?format_error_msgpromptr   c                 C   s6   dddddddd}|  D ]
\}}| ||} q| S )	z*Escapes any special characters in `prompt`z\\z\"z\bz\fz\nz\rz\t)\"
	)itemsreplace)rB   Z
escape_mapZescape_sequenceZescaped_sequencer   r   r   escape_special_charactersy   s   z.ContentFormatterBase.escape_special_charactersc                 C      t jgS )zSupported APIs for the given formatter. Azure ML supports
        deploying models using different hosting methods. Each method may have
        a different API structure.r:   r;   r   r   r   r   supported_api_types   s   z(ContentFormatterBase.supported_api_typesmodel_kwargsapi_typec                 C   s   t  )zFormats the request body according to the input schema of
        the model. Returns bytes or seekable file like object in the
        format specified in the content_type request header.
        )NotImplementedError)r   rB   rQ   rR   r   r   r   format_request_payload   s   
z+ContentFormatterBase.format_request_payloadoutputc                 C      dS )zFormats the response body according to the output
        schema of the model. Returns the data type that is
        received from the response.
        Nr   )r   rU   rR   r   r   r   format_response_payload   s    z,ContentFormatterBase.format_response_payloadN)r2   r3   r4   r5   r?   r   r7   __annotations__r@   rA   staticmethodrL   propertyr   r:   rP   r;   r   r   rT   r   r9   r   rW   r   r   r   r   r>   L   s@   
 

r>   c                   @   V   e Zd ZdZedee fddZdede	dede
fdd	Zd
e
dedefddZdS )GPT2ContentFormatterzContent handler for GPT2r   c                 C   rM   r1   rN   rO   r   r   r   rP         z(GPT2ContentFormatter.supported_api_typesrB   rQ   rR   c                 C   2   t |}tdd| dgi|d}t|S )Ninput_stringrD   Zinputs
parametersr>   rL   jsondumpsr7   encoder   rB   rQ   rR   request_payloadr   r   r   rT         

z+GPT2ContentFormatter.format_request_payloadrU   c              
   C   sT   zt |d d }W n tttfy$ } z
t| jj|d|d }~ww t|dS )Nr   0rR   text	rc   loadsKeyError
IndexError	TypeErrorr   rA   formatr   r   rU   rR   choiceer   r   r   rW      s   
z,GPT2ContentFormatter.format_response_payloadNr2   r3   r4   r5   rZ   r   r:   rP   r7   r   r9   rT   r   rW   r   r   r   r   r\      (    
r\   c                       0   e Zd ZU dZdZeed< d fddZ  ZS )OSSContentFormatterz`Deprecated: Kept for backwards compatibility

    Content handler for LLMs from the OSS catalog.Ncontent_formatterr   c                       t    td d S )Nz`OSSContentFormatter` will be deprecated in the future. 
                      Please use `GPT2ContentFormatter` instead.  
                      superr    warningswarnrO   	__class__r   r   r          
zOSSContentFormatter.__init__r   N	r2   r3   r4   r5   rz   r   rX   r    __classcell__r   r   r   r   ry         
 ry   c                   @   r[   )HFContentFormatterz6Content handler for LLMs from the HuggingFace catalog.r   c                 C   rM   r1   rN   rO   r   r   r   rP      r]   z&HFContentFormatter.supported_api_typesrB   rQ   rR   c                 C   s.   t | td| dg|d}t|S )NrD   r`   rb   rf   r   r   r   rT      s   

z)HFContentFormatter.format_request_payloadrU   c              
   C   sX   zt |d d d }W n tttfy& } z
t| jj|d|d }~ww t|dS )Nr   ri   generated_textrj   rk   rm   rs   r   r   r   rW      s   
z*HFContentFormatter.format_response_payloadNrv   r   r   r   r   r      rw   r   c                   @   r[   )DollyContentFormatterz*Content handler for the Dolly-v2-12b modelr   c                 C   rM   r1   rN   rO   r   r   r   rP      r]   z)DollyContentFormatter.supported_api_typesrB   rQ   rR   c                 C   r^   )Nr_   rD   )
input_datara   rb   rf   r   r   r   rT      rh   z,DollyContentFormatter.format_request_payloadrU   c              
   C   sP   z	t |d }W n tttfy" } z
t| jj|d|d }~ww t|dS )Nr   rj   rk   rm   rs   r   r   r   rW   	  s   
z-DollyContentFormatter.format_response_payloadNrv   r   r   r   r   r      rw   r   c                   @   r[   )CustomOpenAIContentFormatterzAContent formatter for models that use the OpenAI like API scheme.r   c                 C   s   t jt jgS r1   )r:   r;   r=   rO   r   r   r   rP     s   z0CustomOpenAIContentFormatter.supported_api_typesrB   rQ   rR   c                 C   sr   t |}|tjtjfv rtdd| dg|di}n|tjkr,td|i|}ntd| dt	
|S )z/Formats the request according to the chosen apir   rD   )r_   ra   rB   `api_type` # is not supported by this formatter)r>   rL   r:   r;   r<   rc   rd   r=   r   r7   re   rf   r   r   r   rT     s$   



z3CustomOpenAIContentFormatter.format_request_payloadrU   c              
   C   s  |t jt jfv r2zt|d d }W n tttfy, } z
t| j	j
|d|d}~ww t|dS |t jkryzt|d d }t|tsJtdW n tttfyd } z
t| j	j
|d|d}~ww t|d  t|d	|d
ddS td| d)zFormats responser   ri   rj   Nrk   choicesziEndpoint response is not well formed for a chat model. Expected `dict` but `{type(choice)}` was received.rl   finish_reasonlogprobs)r   r   )rl   Zgeneration_infor   r   )r:   r;   r<   rc   rn   ro   rp   rq   r   rA   rr   r   r=   
isinstancedictstripr*   rs   r   r   r   rW   3  s>   



z4CustomOpenAIContentFormatter.format_response_payloadNrv   r   r   r   r   r     s(    
r   c                       rx   )LlamaContentFormatterzNDeprecated: Kept for backwards compatibility

    Content formatter for Llama.Nrz   r   c                    r{   )Nz`LlamaContentFormatter` will be deprecated in the future. 
                Please use `CustomOpenAIContentFormatter` instead.  
            r|   rO   r   r   r   r    \  r   zLlamaContentFormatter.__init__r   r   r   r   r   r   r   U  r   r   c                   @   s8  e Zd ZU dZdZeed< 	 ejZ	eed< 	 e
dZeed< 	 dZeed< 	 eZeed< 	 dZeed	< d
Zeed< dZeed< 	 dZee ed< 	 eddZeddededefddZeddededefddZ eddedefddZ!eddededefddZ"ed	dddedede#fdd Z$dS )!AzureMLBaseEndpointz Azure ML Online Endpoint models.r   r   endpoint_api_typer   r   r   Nhttp_client   max_retriesrz   rQ   r   )Zprotected_namespacesbefore)modevaluesr   c                 C   sd   t t|dd|d< t|dd|d< t|ddd|d< t|dd	tj|d< t|d
dtt|d
< |S )Nr   ZAZUREML_ENDPOINT_API_KEYr   ZAZUREML_ENDPOINT_URLr   ZAZUREML_DEPLOYMENT_NAMEr   r   ZAZUREML_ENDPOINT_API_TYPEr   ZAZUREML_TIMEOUT)r   r   r:   r;   r7   r6   )clsr   r   r   r   validate_environ  s,   
z$AzureMLBaseEndpoint.validate_environfield_valuec                 C   s:   | d}||jvrtdt| d|j d| d|S )z>Validate that content formatter is supported by endpoint type.r   zContent formatter fz8 is not supported by this endpoint. Supported types are z but endpoint is .)r*   rP   r   type)r   r   r   r   r   r   r   validate_content_formatter  s   

z.AzureMLBaseEndpoint.validate_content_formatterc                 C   s,   | dr|dd }| drtd|S )z'Validate that endpoint url is complete./Nzinference.ml.azure.comz`endpoint_url` should contain the full invocation URL including `/score` for `endpoint_api_type='dedicated'` or `/completions` or `/models/chat/completions` for `endpoint_api_type='serverless'`)endswithr   )r   r   r   r   r   validate_endpoint_url  s   

z)AzureMLBaseEndpoint.validate_endpoint_urlc                 C   sZ   | d}|tjks|tjkr|dstd|tjkr+|ds+|ds+td|S )zBValidate that endpoint api type is compatible with the URL format.r   z/scorezEndpoints of type `dedicated` should follow the format `https://<your-endpoint>.<your_region>.inference.ml.azure.com/score`. If your endpoint URL ends with `/completions` or`/models/chat/completions`,use `endpoint_api_type='serverless'` instead.z/completionsz/models/chat/completionszEndpoints of type `serverless` should follow the format `https://<your-endpoint>.<your_region>.inference.ml.azure.com/completions` or `https://<your-endpoint>.<your_region>.inference.ml.azure.com/models/chat/completions`)r*   r:   r;   r<   r   r   r=   )r   r   r   r   r   r   r   validate_endpoint_api_type  s"   



z.AzureMLBaseEndpoint.validate_endpoint_api_typeT)alwaysc                 C   s@   | d}| d}| d}| dt}t|| ||}|S )z?Validate that api key and python package exists in environment.r   r   r   r   )r*   r6   r   Zget_secret_value)r   r   r   r   Zendpoint_keyr   r   r   r   r   r   validate_client  s   


z#AzureMLBaseEndpoint.validate_client)%r2   r3   r4   r5   r   r7   rX   r:   r;   r   r   r   r   r   r6   r   r8   r   r   r   rz   rQ   r   r   r   Zmodel_configr   classmethodr   r   r   r>   r   r   r   r   r   r   r   r   r   r   e  sT   
 

r   c                   @   sp   e Zd ZdZedeeef fddZedefddZ			dde
e d	ee
e  d
ee dedef
ddZdS )AzureMLOnlineEndpointa  Azure ML Online Endpoint models.

    Example:
        .. code-block:: python
            azure_llm = AzureMLOnlineEndpoint(
                endpoint_url="https://<your-endpoint>.<your_region>.inference.ml.azure.com/score",
                endpoint_api_type=AzureMLApiType.dedicated,
                endpoint_api_key="my-api-key",
                timeout=120,
                content_formatter=content_formatter,
            )
    r   c                 C   s    | j pi }i d| jid|iS )zGet the identifying parameters.r   rQ   )rQ   r   )r   _model_kwargsr   r   r   _identifying_params   s   
z)AzureMLOnlineEndpoint._identifying_paramsc                 C   rV   )zReturn type of llm.Zazureml_endpointr   rO   r   r   r   	_llm_type	  s   zAzureMLOnlineEndpoint._llm_typeNpromptsstopr"   r#   c                 K   sv   | j pi }|| |r||d< g }|D ]!}| j||| j}| jj||d}	| j|	| j}
||
g qt	|dS )an  Run the LLM on the given prompts.

        Args:
            prompts: The prompt to pass into the model.
            stop: Optional list of stop words to use when generating.
        Returns:
            The string generated by the model.
        Example:
            .. code-block:: python
                response = azureml_model.invoke("Tell me a joke.")
        r   )r!   r"   )generations)
rQ   updaterz   rT   r   r   r0   rW   appendr   )r   r   r   r"   r#   r   r   rB   rg   Zresponse_payloadr   r   r   r   	_generate  s"   


zAzureMLOnlineEndpoint._generate)NN)r2   r3   r4   r5   rZ   r   r7   r   r   r   r   r   r	   r   r   r   r   r   r   r     s&    
r   ),rc   urllib.requestr&   r~   abcr   enumr   typingr   r   r   r   r   Z langchain_core.callbacks.managerr	   Z#langchain_core.language_models.llmsr
   Zlangchain_core.outputsr   r   Zlangchain_core.utilsr   r   Zpydanticr   r   r   r   r   r6   objectr   r7   r:   r>   r\   ry   r   r   r   r   r   r   r   r   r   r   <module>   s0    /`B 