
    NgM0                    V   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e          Z G d de          Z G d de          Z  G d de          Z! G d dee          Z" G 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                  N    e Zd Zeedd                        Zed	d            ZdS )
Providerreturnstrc                    d S N selfs    f/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/llms/oci_generative_ai.pystop_sequence_keyzProvider.stop_sequence_key   s    (+    responser   c                    d S r   r   r   r!   s     r   completion_response_to_textz$Provider.completion_response_to_text   s    ADr    Nr   r   r!   r   r   r   )__name__
__module____qualname__propertyr   r   r$   r   r    r   r   r      sF        +++ ^ X+DDD ^DDDr    r   c                  .    e Zd ZU dZded<   ddZdd	Zd
S )CohereProviderstop_sequencesr   r   r   Nonec                *    ddl m} |j        | _        d S Nr   models)oci.generative_ai_inferencer2   CohereLlmInferenceRequestllm_inference_requestr   r2   s     r   __init__zCohereProvider.__init__   s%    666666%+%E"""r    r!   r   c                :    |j         j        j        d         j        S Nr   )datainference_responsegenerated_textstextr#   s     r   r$   z*CohereProvider.completion_response_to_text$   s    }/?BGGr    Nr   r.   r&   r'   r(   r)   r   __annotations__r7   r$   r   r    r   r,   r,      sZ         -----F F F F
H H H H H Hr    r,   c                  .    e Zd ZU dZded<   ddZdd	Zd
S )MetaProviderstopr   r   r   r.   c                *    ddl m} |j        | _        d S r0   )r3   r2   LlamaLlmInferenceRequestr5   r6   s     r   r7   zMetaProvider.__init__+   s%    666666%+%D"""r    r!   r   c                :    |j         j        j        d         j        S r9   )r:   r;   choicesr=   r#   s     r   r$   z(MetaProvider.completion_response_to_text0   s    }/7:??r    Nr>   r&   r?   r   r    r   rB   rB   (   sZ         #####E E E E
@ @ @ @ @ @r    rB   c                  "    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_KEYSECURITY_TOKENINSTANCE_PRINCIPALRESOURCE_PRINCIPALr   r    r   rI   rI   4   s,        11GNr    rI   c                     e Zd ZU dZ 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          Zed d            Zed!d            Zd"dZdS )#OCIGenAIBasezBase class for OCI GenAI modelsNT)defaultexcluder   clientrO   zOptional[str]	auth_typeDEFAULTauth_profilemodel_idproviderzOptional[Dict]model_kwargsservice_endpointcompartment_idFbool	is_streamforbidr   )extraarbitrary_types_allowedprotected_namespacesvaluesr   r   c                   |d         |S 	 ddl i d|d         j        j        dd}|d         t          d          j        k    r;j                            |d	         
          |d<   |                    dd           n|d         t          d          j        k    r?fd}j                            |d	         
          |d<    ||d                   |d<   n|d         t          d          j        k    r"j        j	        
                                |d<   nY|d         t          d          j        k    r"j        j	                                        |d<   nt          d|d          d           j        j        di ||d<   n@# t          $ r}t!          d          |d}~wt"          $ r}t          d|          |d}~ww xY w|S )zBValidate that OCI config and python package exists in environment.rW   Nr   r^   )
      )configsignerr^   retry_strategytimeoutrX   rJ   rZ   )profile_namerj   rk   rK   c                @   j                             |                     d          d           }t          |                     d          d          5 }|                                }d d d            n# 1 swxY w Y   j        j                            ||          S )Nkey_filesecurity_token_filezutf-8)encoding)rk   load_private_key_from_filegetopenreadauthsignersSecurityTokenSigner)
oci_configpkf	st_stringocis       r   make_security_token_signerzEOCIGenAIBase.validate_environment.<locals>.make_security_token_signer   s    >>"z22D B "'<==   -$%FFHH	- - - - - - - - - - - - - - - 8+??	2NNNs   A55A9<A9)rz   rL   rM   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.a  Could not authenticate with OCI client. 
                Please check if ~/.oci/config exists.
                If INSTANCE_PRINCIPAL or RESOURCE_PRINCIPAL is used, 
                please check the specified
                auth_profile and auth_type are valid.r   )r~   retryDEFAULT_RETRY_STRATEGYrI   namerj   	from_filepoprw   rx   %InstancePrincipalsSecurityTokenSignerget_resource_principals_signer
ValueErrorgenerative_ai_inferenceGenerativeAiInferenceClientImportErrorModuleNotFoundError	Exception)clsrf   client_kwargsr   exer~   s         @r   validate_environmentz!OCIGenAIBase.validate_environmentk   s   
 ('MA	JJJ $*+=$>"%)"B$ M k"k!nn&999*-**>*>!'!7 +? + +h' !!(D1111$A(;;;O O O O O +.**>*>!'!7 +? + +h' +E*D,X6+ + +h'' $A(;;;H$JJLL h'' $A(;;;H$CCEE h'' !;k*; ; ;  
  Ws:V       F8  	 	 	%G    	 	 	9
   	 s$   F F 
GF((G5GGMapping[str, Any]c                     | j         pi }i d|iS )zGet the identifying parameters.r]   )r]   )r   _model_kwargss     r   _identifying_paramsz OCIGenAIBase._identifying_params   s(     )/R
}-
 	
r    provider_mapc                    | j         | j         }nH| j        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)r\   r[   r   splitlower)r   r   r\   s      r   _get_providerzOCIGenAIBase._get_provider   s    =$}HH}$ ;  
 }**3//288::H<''-4= - - -  
 H%%r    )rf   r   r   r   r   r   )r   r   r   r   )r'   r(   r)   rN   r   rW   r@   rX   rZ   r[   r\   r]   r^   r_   ra   r   model_configr   r   r*   r   r   r   r    r   rT   rT   =   s_        ))%d333F3333(I(((( #,L++++ #H""""7"H""""
 $(L''''0&*****$(N((((I1:2  L J J J XJX 
 
 
 X
& & & & & &r    rT   c                      e Zd ZdZ edd          Zedd            Zedd	            Zedd            Z	ddZ
ddZ	 	 dd dZ	 	 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.

    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"
                )
    rb   T)rc   rd   r   r   c                    dS )zReturn type of llm.oci_generative_ai_completionr   r   s    r   	_llm_typezOCIGenAI._llm_type   s
     .-r    r   c                <    t                      t                      dS )zGet the provider map)coheremeta)r,   rB   r   s    r   _provider_mapzOCIGenAI._provider_map   s#     %&& NN
 
 	
r    r   c                8    |                      | j                  S )z Get the internal provider object)r   )r   r   r   s    r   	_providerzOCIGenAI._provider  s     !!t/A!BBBr    promptrC   Optional[List[str]]kwargsDict[str, Any]c           	        ddl m} | j        pi }|||| j        j        <   | j        t          d          | j                            t                    r|	                    | j                  }n|
                    | j                  }i ||}||d<   | j        |d<   |                    | j        | | j        j        d	i |          }|S )
Nr   r1   zDmodel_id is required to call the model, please provide the model_id.)endpoint_id)r[   r   ra   )r_   serving_modeinference_requestr   )r3   r2   r]   r   r   r[   r   
startswithCUSTOM_ENDPOINT_PREFIXDedicatedServingModeOnDemandServingModera   GenerateTextDetailsr_   r5   )	r   r   rC   r   r2   r   r   inference_paramsinvocation_objs	            r   _prepare_invocation_objectz#OCIGenAI._prepare_invocation_object
  s    	766666)/R>BM$.:;= /  
 =##$:;; 	N!664=6QQLL!55t}5MML6m6v6%+"(,%33.%BdnBVVEUVV 4 
 
 r    r!   c                ^    | j                             |          }|t          ||          }|S r   )r   r$   r   )r   r!   rC   r=   s       r   _process_responsezOCIGenAI._process_response*  s1    ~99(CC&tT22Dr    Nrun_manager"Optional[CallbackManagerForLLMRun]c                   | j         r3d} | j        |||fi |D ]}||j        z  }|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.")
         )ra   _streamr=   r   r   rW   generate_textr   )	r   r   rC   r   r   r=   chunkr   r!   s	            r   _callzOCIGenAI._call2  s    * > 	D%fdKJJ6JJ # #
"*466K88vNN;,,^<<%%h555r    Iterator[GenerationChunk]c              +  f  K   d| _         |                     |||          }| j                            |          }|j                                        D ]\}t          j        |j                  }d|v r	|d         }	nd}	t          |	          }
|r|	                    |
j
        |
           |
V  ]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.")
        Tr=   r   )r=   )r   N)ra   r   rW   r   r:   eventsjsonloadsr   on_llm_new_tokenr=   )r   r   rC   r   r   r   r!   event	json_loadevent_data_textr   s              r   r   zOCIGenAI._streamS  s      , 88vNN;,,^<<]))++ 		 		E
5:..I"""+F"3"$#999E F,,UZu,EEEKKKK		 		r    r%   r   )r   r   )r   r   rC   r   r   r   r   r   )r!   r   rC   r   r   r   )NN)
r   r   rC   r   r   r   r   r   r   r   )
r   r   rC   r   r   r   r   r   r   r   )r'   r(   r)   rN   r   r   r*   r   r   r   r   r   r   r   r   r    r   r   r      s        : : $  L
 . . . X. 
 
 
 X
 C C C XC   @    %):>	6 6 6 6 6H %):>	# # # # # # #r    r   )$
__future__r   r   abcr   r   enumr   typingr   r   r	   r
   r   r   langchain_core.callbacksr   #langchain_core.language_models.llmsr   langchain_core.outputsr   langchain_core.utilsr   pydanticr   r   r   langchain_community.llms.utilsr   r   r   r,   rB   rI   rT   r   r   r    r   <module>r      s-   " " " " " "  # # # # # # # #       ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? = = = = = = 3 3 3 3 3 3 2 2 2 2 2 2 ) ) ) ) ) ) 1 1 1 1 1 1 1 1 1 1 > > > > > >5 E E E E Es E E E	H 	H 	H 	H 	HX 	H 	H 	H	@ 	@ 	@ 	@ 	@8 	@ 	@ 	@    $   U& U& U& U& U&9c U& U& U&pa a a a asL a a a a ar    