o
    |qiP                     @   sj  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 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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)urlparse)CallbackManagerForLLMRun)BaseLLM)
Generation	LLMResult)convert_to_secret_strget_from_dict_or_env)	BaseModel
ConfigDict	SecretStrfield_validator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    p/home/app/PaddleOCR-VL/.venv_paddleocr/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   r2   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)r4   r5   r6   r7   r=   r>   r?   r    r    r    r!   r<   H   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)rD   Z
escape_mapZescape_sequenceZescaped_sequencer    r    r!   escape_special_characters   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   rD   rS   rT   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   rW   rT   r    r    r!   format_response_payload   s    z,ContentFormatterBase.format_response_payloadN)r4   r5   r6   r7   rA   r   r9   __annotations__rB   rC   staticmethodrN   propertyr   r<   rR   r=   r   r   rV   r   r;   r   rY   r    r    r    r!   r@   T   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   rO   r3   rP   rQ   r    r    r!   rR         z(GPT2ContentFormatter.supported_api_typesrD   rS   rT   c                 C   2   t |}tdd| dgi|d}t|S )Ninput_stringrF   Zinputs
parametersr@   rN   jsondumpsr9   encoder   rD   rS   rT   request_payloadr    r    r!   rV         

z+GPT2ContentFormatter.format_request_payloadrW   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rT   text	re   loadsKeyError
IndexError	TypeErrorr   rC   formatr   r   rW   rT   choiceer    r    r!   rY      s   
z,GPT2ContentFormatter.format_response_payloadNr4   r5   r6   r7   r\   r   r<   rR   r9   r   r;   rV   r   rY   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warnrQ   	__class__r    r!   r"         
zOSSContentFormatter.__init__r   N	r4   r5   r6   r7   r|   r   rZ   r"   __classcell__r    r    r   r!   r{         
 r{   c                   @   r]   )HFContentFormatterz6Content handler for LLMs from the HuggingFace catalog.r   c                 C   rO   r3   rP   rQ   r    r    r!   rR      r_   z&HFContentFormatter.supported_api_typesrD   rS   rT   c                 C   s.   t | td| dg|d}t|S )NrF   rb   rd   rh   r    r    r!   rV      s   

z)HFContentFormatter.format_request_payloadrW   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   rk   generated_textrl   rm   ro   ru   r    r    r!   rY      s   
z*HFContentFormatter.format_response_payloadNrx   r    r    r    r!   r      ry   r   c                   @   r]   )DollyContentFormatterz*Content handler for the Dolly-v2-12b modelr   c                 C   rO   r3   rP   rQ   r    r    r!   rR     r_   z)DollyContentFormatter.supported_api_typesrD   rS   rT   c                 C   r`   )Nra   rF   )
input_datarc   rd   rh   r    r    r!   rV     rj   z,DollyContentFormatter.format_request_payloadrW   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   rl   rm   ro   ru   r    r    r!   rY     s   
z-DollyContentFormatter.format_response_payloadNrx   r    r    r    r!   r      ry   r   c                   @   r]   )CustomOpenAIContentFormatterzAContent formatter for models that use the OpenAI like API scheme.r   c                 C   s   t jt jgS r3   )r<   r=   r?   rQ   r    r    r!   rR     s   z0CustomOpenAIContentFormatter.supported_api_typesrD   rS   rT   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   rF   )ra   rc   rD   `api_type` # is not supported by this formatter)r@   rN   r<   r=   r>   re   rf   r?   r   r9   rg   rh   r    r    r!   rV   "  s$   



z3CustomOpenAIContentFormatter.format_request_payloadrW   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   rk   rl   Nrm   choicesziEndpoint response is not well formed for a chat model. Expected `dict` but `{type(choice)}` was received.rn   finish_reasonlogprobs)r   r   )rn   Zgeneration_infor   r   )r<   r=   r>   re   rp   rq   rr   rs   r   rC   rt   r   r?   
isinstancedictstripr,   ru   r    r    r!   rY   ;  s>   



z4CustomOpenAIContentFormatter.format_response_payloadNrx   r    r    r    r!   r     s(    
r   c                       rz   )LlamaContentFormatterzNDeprecated: Kept for backwards compatibility

    Content formatter for Llama.Nr|   r   c                    r}   )Nz`LlamaContentFormatter` will be deprecated in the future. 
                Please use `CustomOpenAIContentFormatter` instead.  
            r~   rQ   r   r    r!   r"   d  r   zLlamaContentFormatter.__init__r   r   r    r    r   r!   r   ]  r   r   c                   @   s@  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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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_retriesr|   rS   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=   r9   r8   )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,   rR   r   type)r   r   r   r   r    r    r!   validate_content_formatter  s   

z.AzureMLBaseEndpoint.validate_content_formatteraftervaluec                 C   s:   | dr|dd }t|}|jr|jdkrtd|S )z'Validate that endpoint url is complete./Nz`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	   pathr   )r   r   urlr    r    r!   validate_endpoint_url  s   
z)AzureMLBaseEndpoint.validate_endpoint_urlc                 C   sT   t |d}|tjks|tjkr|jdkstd|tjkr(|jdvr(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    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,   r8   r   Zget_secret_value)r   r   r   r   Zendpoint_keyr   r   r   r    r    r!   validate_client  s   


z#AzureMLBaseEndpoint.validate_client)&r4   r5   r6   r7   r   r9   rZ   r<   r=   r   r   r   r   r   r8   r   r:   r   r   r   r|   rS   r   r   r   Zmodel_configr   classmethodr   r   r   r@   r   r   r   r   r   r   r    r    r    r!   r   m  sV   
 


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   rS   )rS   r   )r   _model_kwargsr    r    r!   _identifying_params  s   
z)AzureMLOnlineEndpoint._identifying_paramsc                 C   rX   )zReturn type of llm.Zazureml_endpointr    rQ   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)
rS   updater|   rV   r   r   r2   rY   appendr   )r   r   r   r$   r%   r   r   rD   ri   Zresponse_payloadr   r    r    r!   	_generate  s"   


zAzureMLOnlineEndpoint._generate)NN)r4   r5   r6   r7   r\   r   r9   r   r   r   r   r   r
   r   r   r    r    r    r!   r     s&    
r   )/re   urllib.requestr(   r   abcr   enumr   typingr   r   r   r   r   urllib.parser	   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   r   r8   objectr   r9   r<   r@   r^   r{   r   r   r   r   r   r   r    r    r    r!   <module>   s2     	/`B 