a
    bg1                     @  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                   @  s6   e Zd ZeeddddZedddddZd	S )
Providerstrreturnc                 C  s   d S N selfr   r   x/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain_community/llms/oci_generative_ai.pystop_sequence_key   s    zProvider.stop_sequence_keyr   responser   c                 C  s   d S r   r   r   r   r   r   r   completion_response_to_text   s    z$Provider.completion_response_to_textN)__name__
__module____qualname__propertyr   r   r!   r   r   r   r   r      s
   r   c                   @  s8   e Zd ZU dZded< ddddZddd	d
dZdS )CohereProviderZstop_sequencesr   r   Noner   c                 C  s   ddl m} |j| _d S Nr   models)oci.generative_ai_inferencer*   ZCohereLlmInferenceRequestllm_inference_requestr   r*   r   r   r   __init__   s    zCohereProvider.__init__r   r   c                 C  s   |j jjd jS Nr   )datainference_responseZgenerated_textstextr    r   r   r   r!   $   s    z*CohereProvider.completion_response_to_textNr"   r#   r$   r   __annotations__r.   r!   r   r   r   r   r&      s   
r&   c                   @  s8   e Zd ZU dZded< ddddZddd	d
dZdS )MetaProviderstopr   r   r'   r   c                 C  s   ddl m} |j| _d S r(   )r+   r*   ZLlamaLlmInferenceRequestr,   r-   r   r   r   r.   +   s    zMetaProvider.__init__r   r   c                 C  s   |j jjd jS r/   )r0   r1   choicesr2   r    r   r   r   r!   0   s    z(MetaProvider.completion_response_to_textNr3   r   r   r   r   r5   (   s   
r5   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   r8   4   s
   r8   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ddZeddd d!Zddd"d#d$ZdS )%OCIGenAIBasezBase class for OCI GenAI modelsNT)defaultexcluder   clientr>   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_namespacesr   )valuesr   c              
     s  |d dur|S z"ddl  i d|d  jjdd}|d tdjkrp jj|d	 |d
 d|d< |dd n|d tdjkr fdd} jj|d	 |d
 d|d< ||d d|d< n^|d tdjkr jj	
 |d< n:|d tdjkr jj	 |d< ntd|d  d jjf i ||d< W n` tyd } ztd|W Y d}~n:d}~0  ty } ztd||W Y d}~n
d}~0 0 |S )zBValidate that OCI config and python package exists in environment.rB   Nr   rJ   )
      )configsignerrJ   Zretry_strategytimeoutrC   r9   rF   rE   )Zfile_locationZprofile_namerT   rU   r:   c                   s^    j | dd }t| ddd}| }W d    n1 sD0    Y   jj||S )Nkey_fileZsecurity_token_filezutf-8)encoding)rU   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)r^   r;   r<   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.)rb   retryZDEFAULT_RETRY_STRATEGYr8   namerT   	from_filepopr\   r]   Z%InstancePrincipalsSecurityTokenSignerZget_resource_principals_signer
ValueErrorZgenerative_ai_inferenceZGenerativeAiInferenceClientImportErrorModuleNotFoundError	Exception)clsrQ   Zclient_kwargsrc   exer   ra   r   validate_environmentp   sj    





z!OCIGenAIBase.validate_environmentMapping[str, Any]r   c                 C  s   | j pi }i d|iS )zGet the identifying parameters.rI   )rI   )r   _model_kwargsr   r   r   _identifying_params   s    
z OCIGenAIBase._identifying_params)provider_mapr   c                 C  sZ   | j d ur| j }n&| jd u r$td| jdd  }||vrRt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)rH   rG   rh   splitlower)r   rs   rH   r   r   r   _get_provider   s    

zOCIGenAIBase._get_provider)r"   r#   r$   r=   r   rB   r4   rC   rE   rF   rG   rH   rI   rJ   rK   rM   r   model_configr   ro   r%   rr   rw   r   r   r   r   r?   =   s&   
Mr?   c                   @  s   e Zd ZdZedddZeddddZed	dd
dZeddddZ	dddddddZ
ddddddZdddddddddZd dddd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"
                )
    rN   T)rO   rP   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_typerp   c                 C  s   t  t dS )zGet the provider map)Zcoheremeta)r&   r5   r   r   r   r   _provider_map  s    zOCIGenAI._provider_mapr   c                 C  s   | j | jdS )z Get the internal provider object)rs   )rw   r|   r   r   r   r   	_provider  s    zOCIGenAI._providerzOptional[List[str]]zDict[str, Any])promptr6   kwargsr   c           	      C  s   ddl m} | jpi }|d ur*||| jj< | jd u r<td| jtrX|j	| jd}n|j
| jd}i ||}||d< | j|d< |j| j|| jjf i |d}|S )	Nr   r)   zDmodel_id is required to call the model, please provide the model_id.)Zendpoint_id)rG   r~   rM   )rK   serving_modeZinference_request)r+   r*   rI   r}   r   rG   rh   
startswithCUSTOM_ENDPOINT_PREFIXZDedicatedServingModeZOnDemandServingModerM   ZGenerateTextDetailsrK   r,   )	r   r~   r6   r   r*   rq   r   Zinference_paramsinvocation_objr   r   r   _prepare_invocation_object  s(    


z#OCIGenAI._prepare_invocation_object)r   r6   r   c                 C  s"   | j |}|d urt||}|S r   )r}   r!   r   )r   r   r6   r2   r   r   r   _process_response3  s    
zOCIGenAI._process_responseNz"Optional[CallbackManagerForLLMRun])r~   r6   run_managerr   r   c           	      K  sl   | j rFd}| j|||fi |D ]}||j7 }q |durBt||}|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)rM   _streamr2   r   r   rB   generate_textr   )	r   r~   r6   r   r   r2   chunkr   r   r   r   r   _call;  s    
zOCIGenAI._callzIterator[GenerationChunk]c                 k  sz   d| _ | |||}| j|}|j D ]J}t|j}d|v rL|d }	nd}	t|	d}
|rn|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.")
        Tr2   r   )r2   )r   N)rM   r   rB   r   r0   eventsjsonloadsr   Zon_llm_new_tokenr2   )r   r~   r6   r   r   r   r   eventZ	json_loadZevent_data_textr   r   r   r   r   \  s    

zOCIGenAI._stream)NN)NN)r"   r#   r$   r=   r   rx   r%   rz   r|   r}   r   r   r   r   r   r   r   r   ry      s&       $  ry   )$
__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&   r5   r8   r?   ry   r   r   r   r   <module>   s$    		 