o
    Zh1                     @  s  d dl mZ d dl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 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mZ d dlmZ 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eZ"G dd dee"Z#dS )    )annotationsN)ABCabstractmethod)Enum)AnyDictIteratorListMappingOptional)CallbackManagerForLLMRun)LLM)GenerationChunk)pre_init)	BaseModel
ConfigDictField)enforce_stop_tokenszocid1.generativeaiendpointc                   @  s,   e Zd Zeed
ddZedddZd	S )Providerreturnstrc                 C     d S N selfr   r   a/var/www/html/lang_env/lib/python3.10/site-packages/langchain_community/llms/oci_generative_ai.pystop_sequence_key   s   zProvider.stop_sequence_keyresponser   c                 C  r   r   r   r   r   r   r   r   completion_response_to_text   s   z$Provider.completion_response_to_textNr   r   r   r   r   r   )__name__
__module____qualname__propertyr   r   r    r   r   r   r   r      s    r   c                   @  .   e Zd ZU dZded< dddZdd
dZdS )CohereProviderZstop_sequencesr   r   r   Nonec                 C     ddl m} |j| _d S Nr   models)oci.generative_ai_inferencer-   ZCohereLlmInferenceRequestllm_inference_requestr   r-   r   r   r   __init__      zCohereProvider.__init__r   r   c                 C     |j jjd jS Nr   )datainference_responseZgenerated_textstextr   r   r   r   r    $      z*CohereProvider.completion_response_to_textNr   r)   r"   r#   r$   r%   r   __annotations__r1   r    r   r   r   r   r(         
 
r(   c                   @  r'   )MetaProviderstopr   r   r   r)   c                 C  r*   r+   )r.   r-   ZLlamaLlmInferenceRequestr/   r0   r   r   r   r1   +   r2   zMetaProvider.__init__r   r   c                 C  r3   r4   )r5   r6   choicesr7   r   r   r   r   r    0   r8   z(MetaProvider.completion_response_to_textNr9   r"   r:   r   r   r   r   r=   (   r<   r=   c                   @  s    e Zd ZdZdZdZdZdZdS )OCIAuthTypez'OCI authentication types as enumerator.            N)r#   r$   r%   __doc__API_KEYZSECURITY_TOKENZINSTANCE_PRINCIPALZRESOURCE_PRINCIPALr   r   r   r   r@   4   s    r@   c                   @  s   e Zd ZU dZedddZded< dZded	< 	 d
Zded< 	 dZ	ded< 	 dZ
ded< 	 dZded< 	 dZded< 	 dZded< 	 dZded< 	 dZded< 	 eddddZed%ddZed&d d!Zd'd#d$ZdS )(OCIGenAIBasezBase class for OCI GenAI modelsNT)defaultexcluder   clientrF   zOptional[str]	auth_typeDEFAULTauth_profilez~/.oci/configauth_file_locationmodel_idproviderzOptional[Dict]model_kwargsservice_endpointcompartment_idFbool	is_streamforbidr   )extraarbitrary_types_allowedZprotected_namespacesvaluesr   r   c              
     sx  |d dur|S zddl  i d|d  jjdd}|d tdjkr7 jj|d	 |d
 d|d< |dd nU|d tdjkr^ fdd} jj|d	 |d
 d|d< ||d d|d< n.|d tdjkrp jj	
 |d< n|d tdjkr jj	 |d< n
td|d  d jjdi ||d< W |S  ty } ztd|d}~w ty } ztd||d}~ww )zBValidate that OCI config and python package exists in environment.rJ   Nr   rR   )
      )configsignerrR   Zretry_strategytimeoutrK   rA   rN   rM   )Zfile_locationZprofile_namer\   r]   rB   c                   s^    j | dd }t| ddd}| }W d    n1 s"w   Y   jj||S )Nkey_fileZsecurity_token_filezutf-8)encoding)r]   Zload_private_key_from_filegetopenreadauthsignersZSecurityTokenSigner)
oci_configpkfZ	st_stringocir   r   make_security_token_signer   s   


zEOCIGenAIBase.validate_environment.<locals>.make_security_token_signer)rf   rC   rD   z)Please provide valid value to auth_type, z is not valid.zYCould not import oci python package. Please make sure you have the oci package installed.zCould not authenticate with OCI client.
                If INSTANCE_PRINCIPAL or RESOURCE_PRINCIPAL is used, 
                please check the specified
                auth_profile, auth_file_location and auth_type are valid.r   )rj   retryZDEFAULT_RETRY_STRATEGYr@   namer\   	from_filepoprd   re   Z%InstancePrincipalsSecurityTokenSignerZget_resource_principals_signer
ValueErrorZgenerative_ai_inferenceZGenerativeAiInferenceClientImportErrorModuleNotFoundError	Exception)clsrY   Zclient_kwargsrk   exer   ri   r   validate_environmentp   sp   





z!OCIGenAIBase.validate_environmentMapping[str, Any]c                 C  s   | j pi }i d|iS )zGet the identifying parameters.rQ   )rQ   )r   _model_kwargsr   r   r   _identifying_params   s   
z OCIGenAIBase._identifying_paramsprovider_mapc                 C  sZ   | j d ur	| j }n| jd u rtd| jdd  }||vr)td| j d|| S )Nzmodel_id is required to derive the provider, please provide the provider explicitly or specify the model_id to derive the provider..r   z(Invalid provider derived from model_id: zL Please explicitly pass in the supported provider when using custom endpoint)rP   rO   rp   splitlower)r   r{   rP   r   r   r   _get_provider   s   

zOCIGenAIBase._get_provider)rY   r   r   r   r   rx   )r{   rx   r   r   )r#   r$   r%   rE   r   rJ   r;   rK   rM   rN   rO   rP   rQ   rR   rS   rU   r   model_configr   rw   r&   rz   r   r   r   r   r   rG   =   s:   
 
MrG   c                   @  sz   e Zd ZdZedddZed!ddZed"d
dZed#ddZ	d$ddZ
d%ddZ		d&d'ddZ		d&d(dd ZdS ))OCIGenAIa  OCI large language models.

    To authenticate, the OCI client uses the methods described in
    https://docs.oracle.com/en-us/iaas/Content/API/Concepts/sdk_authentication_methods.htm

    The authentifcation method is passed through auth_type and should be one of:
    API_KEY (default), SECURITY_TOKEN, INSTANCE_PRINCIPAL, RESOURCE_PRINCIPAL

    Make sure you have the required policies (profile/roles) to
    access the OCI Generative AI service.
    If a specific config profile is used, you must pass
    the name of the profile (from ~/.oci/config) through auth_profile.
    If a specific config file location is used, you must pass
    the file location where profile name configs present
    through auth_file_location

    To use, you must provide the compartment id
    along with the endpoint url, and model id
    as named parameters to the constructor.

    Example:
        .. code-block:: python

            from langchain_community.llms import OCIGenAI

            llm = OCIGenAI(
                    model_id="MY_MODEL_ID",
                    service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com",
                    compartment_id="MY_OCID"
                )
    rV   T)rW   rX   r   r   c                 C  s   dS )zReturn type of llm.Zoci_generative_ai_completionr   r   r   r   r   	_llm_type  s   zOCIGenAI._llm_typerx   c                 C  s   t  t dS )zGet the provider map)Zcoheremeta)r(   r=   r   r   r   r   _provider_map  s   zOCIGenAI._provider_mapr   c                 C  s   | j | jdS )z Get the internal provider object)r{   )r   r   r   r   r   r   	_provider  s   zOCIGenAI._providerpromptr>   Optional[List[str]]kwargsDict[str, Any]c           	      C  s   ddl m} | jp
i }|d ur||| jj< | jd u rtd| jtr,|j	| jd}n|j
| jd}i ||}||d< | j|d< |j| j|| jjd	i |d}|S )
Nr   r,   zDmodel_id is required to call the model, please provide the model_id.)Zendpoint_id)rO   r   rU   )rS   serving_modeZinference_requestr   )r.   r-   rQ   r   r   rO   rp   
startswithCUSTOM_ENDPOINT_PREFIXZDedicatedServingModeZOnDemandServingModerU   ZGenerateTextDetailsrS   r/   )	r   r   r>   r   r-   ry   r   Zinference_paramsinvocation_objr   r   r   _prepare_invocation_object  s(   


z#OCIGenAI._prepare_invocation_objectr   c                 C  s"   | j |}|d urt||}|S r   )r   r    r   )r   r   r>   r7   r   r   r   _process_response2  s   
zOCIGenAI._process_responseNrun_manager"Optional[CallbackManagerForLLMRun]c           	      K  sl   | j r#d}| j|||fi |D ]}||j7 }q|dur!t||}|S | |||}| j|}| ||S )ak  Call out to OCIGenAI generate endpoint.

        Args:
            prompt: 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 = llm.invoke("Tell me a joke.")
         N)rU   _streamr7   r   r   rJ   generate_textr   )	r   r   r>   r   r   r7   chunkr   r   r   r   r   _call:  s   
zOCIGenAI._callIterator[GenerationChunk]c                 k  s|    d| _ | |||}| j|}|j D ]%}t|j}d|v r'|d }	nd}	t|	d}
|r8|j	|
j
|
d |
V  qdS )ac  Stream OCIGenAI LLM on given prompt.

        Args:
            prompt: The prompt to pass into the model.
            stop: Optional list of stop words to use when generating.

        Returns:
            An iterator of GenerationChunks.

        Example:
            .. code-block:: python

            response = llm.stream("Tell me a joke.")
        Tr7   r   )r7   )r   N)rU   r   rJ   r   r5   eventsjsonloadsr   Zon_llm_new_tokenr7   )r   r   r>   r   r   r   r   eventZ	json_loadZevent_data_textr   r   r   r   r   [  s   

zOCIGenAI._streamr!   r   )r   r   )r   r   r>   r   r   r   r   r   )r   r   r>   r   r   r   )NN)
r   r   r>   r   r   r   r   r   r   r   )
r   r   r>   r   r   r   r   r   r   r   )r#   r$   r%   rE   r   r   r&   r   r   r   r   r   r   r   r   r   r   r   r      s(     

$r   )$
__future__r   r   abcr   r   enumr   typingr   r   r   r	   r
   r   Zlangchain_core.callbacksr   Z#langchain_core.language_models.llmsr   Zlangchain_core.outputsr   Zlangchain_core.utilsr   Zpydanticr   r   r   Zlangchain_community.llms.utilsr   r   r   r(   r=   r@   rG   r   r   r   r   r   <module>   s&     		 