
    7|h2                    .   d dl mZ d dlZd dlmZmZmZmZmZm	Z	 d dl
mZ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 d	lmZmZmZmZmZ d d
lmZ  ej>                  e       Z! G d de      Z" G d de"e      Z#	 	 	 	 	 	 ddZ$ddZ%ddZ&ddZ'ddZ(y)    )annotationsN)AnyCallableDictListOptionalSequence)AsyncCallbackManagerForLLMRunCallbackManagerForLLMRun)LLM)Serializable)convert_to_secret_strget_from_dict_or_envpre_init)	SecretStr)before_sleep_logretryretry_if_exception_typestop_after_attemptwait_exponential)enforce_stop_tokensc                  "   e Zd ZU 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<   	 dZded<   	 dZded<   	 dZded<   	 dZded<   ed#d        Zed$d!       Zed%d"       Zy)&_BaseYandexGPT r   	iam_tokenapi_keystr	folder_id	model_urizyandexgpt-lite
model_namelatestmodel_versiong333333?floattemperaturei  int
max_tokensNOptional[List[str]]stopzllm.api.cloud.yandex.net:443url   max_retriesg      ?sleep_intervalFbooldisable_request_loggingzOptional[Sequence]grpc_metadatac                     y)N
yandex_gpt selfs    ^/var/www/html/test/engine/venv/lib/python3.12/site-packages/langchain_community/llms/yandex.py	_llm_typez_BaseYandexGPT._llm_type>   s        c                v    | j                   | j                  | j                  | j                  | j                  dS )zGet the identifying parameters.r   r$   r&   r(   r+   r9   r3   s    r5   _identifying_paramsz"_BaseYandexGPT._identifying_paramsB   s5     ++//II++
 	
r7   c                V   t        t        |ddd            }||d<   t        t        |ddd            }||d<   t        |ddd      }||d<   |j                         dk(  r|j                         dk(  rt        d      |d   r;d	d
|d   j                          fg|d<   |d   r6|d   j	                  d|d   f       nd	d|d   j                          fg|d<   |d   dk(  r|d   dk(  rt        d      |d   sd|d    d|d    d|d    |d<   |d   r|d   j	                  d       |S )z.Validate that iam token exists in environment.r   YC_IAM_TOKENr   r   
YC_API_KEYr   YC_FOLDER_IDz7Either 'YC_API_KEY' or 'YC_IAM_TOKEN' must be provided.authorizationzBearer r/   zx-folder-idzApi-Key r   z3Either 'model_uri' or 'folder_id' must be provided.zgpt:///r    r"   r.   )zx-data-logging-enabledfalse)r   r   get_secret_value
ValueErrorappend)clsvaluesr   r   r   s        r5   validate_environmentz#_BaseYandexGPT.validate_environmentM   s    * nbI
	 ({' L"E
 $y(nbQ	'{##%+	0J0J0LPR0RVWW+ GF;,?,P,P,R+S"TU'F?# k"'..vk?R/ST !HVI->-O-O-Q,R"ST'F?# +"$)<)BRSSk",-Qvl/C.DAf_F]E^_ ; +,?#** r7   )returnr   )rH   zDict[str, Any])rF   r   rH   r   )__name__
__module____qualname__r   __annotations__r   r   r   r    r"   r$   r&   r(   r)   r+   r,   r.   r/   propertyr6   r:   r   rG   r2   r7   r5   r   r      s    Iy.GY.Is Is&J&!M3!KJJ= !%D
$9-C-K<NE$$)T)P(,M%,  
 
 ' 'r7   r   c                  P    e Zd ZdZ	 	 d	 	 	 	 	 	 	 	 	 ddZ	 	 d	 	 	 	 	 	 	 	 	 ddZy)	YandexGPTaV  Yandex large language models.

    To use, you should have the ``yandexcloud`` python package installed.

    There are two authentication options for the service account
    with the ``ai.languageModels.user`` role:
        - You can specify the token in a constructor parameter `iam_token`
        or in an environment variable `YC_IAM_TOKEN`.
        - You can specify the key in a constructor parameter `api_key`
        or in an environment variable `YC_API_KEY`.

    To use the default model specify the folder ID in a parameter `folder_id`
    or in an environment variable `YC_FOLDER_ID`.

    Or specify the model URI in a constructor parameter `model_uri`

    Example:
        .. code-block:: python

            from langchain_community.llms import YandexGPT
            yandex_gpt = YandexGPT(iam_token="t1.9eu...", folder_id="b1g...")
    Nc                <    t        | |      }|t        ||      }|S )at  Call the Yandex GPT model and return the output.

        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 = YandexGPT("Tell me a joke.")
        prompt)completion_with_retryr   r4   rR   r(   run_managerkwargstexts         r5   _callzYandexGPT._call   s'    * %T&9&tT2Dr7   c                X   K   t        | |       d{   }|t        ||      }|S 7 w)a  Async call the Yandex GPT model and return the output.

        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.
        rQ   N)acompletion_with_retryr   rT   s         r5   _acallzYandexGPT._acall   s4       ,D@@&tT2D As   *(*)NN)
rR   r   r(   r'   rU   z"Optional[CallbackManagerForLLMRun]rV   r   rH   r   )
rR   r   r(   r'   rU   z'Optional[AsyncCallbackManagerForLLMRun]rV   r   rH   r   )rI   rJ   rK   __doc__rX   r[   r2   r7   r5   rO   rO   x   s    4 %):>	 " 8	
  
: %)?C	 " =	
  
r7   rO   c           	     V   	 dd l }ddlm}m} 	 ddlm}m} ddlm} ddl	m
} |j!                         }
|j#                  | j$                  |
      } || j&                   | || j(                         || j*                               |d	|
      g      } ||      }|j-                  || j.                        }t1        |      d   j2                  d   j4                  j6                  S # t        $ r ddlm}m} ddlm} ddlm
} Y w xY w# t        $ r}	t        d      |	d }	~	ww xY w)Nr   DoubleValue
Int64ValueCompletionOptionsMessage)CompletionRequest)TextGenerationServiceStubkPlease install YandexCloud SDK  with `pip install yandexcloud`             or upgrade it to recent version.valuer$   r&   userrolerW   r   completion_optionsmessagesmetadata)grpcgoogle.protobuf.wrappers_pb2r_   r`   4yandex.cloud.ai.foundation_models.v1.text_common_pb2rb   rc   Pyandex.cloud.ai.foundation_models.v1.text_generation.text_generation_service_pb2rd   Uyandex.cloud.ai.foundation_models.v1.text_generation.text_generation_service_pb2_grpcre   ModuleNotFoundError:yandex.cloud.ai.foundation_models.v1.foundation_models_pb2Byandex.cloud.ai.foundation_models.v1.foundation_models_service_pb2Gyandex.cloud.ai.foundation_models.v1.foundation_models_service_pb2_grpcImportErrorssl_channel_credentialssecure_channelr)   r   r$   r&   
Completionr/   listalternativesmessagerW   )r4   rR   rr   r_   r`   rb   rc   rd   re   echannel_credentialschannelrequeststubress                  r5   _make_requestr      s   H	& 668!!$((,?@G..,#$*:*:;!8
 vF34G %W-D
//'D,>,>/
?C9Q<$$Q'//4449 # 
	
	  .
 	s4   D C+ +DD 
DD 	D(D##D(c           
       K   	 dd l }dd l}ddlm}m} 	 ddlm}m} ddlm	}m
}	 ddlm}
 ddlm} ddlm} d	}|j-                         }|j.                  j1                  | j2                  |      4 d {   } || j4                   | || j6                  
       || j8                  
             |d|      g      } |
|      }|j;                  || j<                         d {   }|j.                  j1                  ||      4 d {   } ||      }|j>                  s^|jA                  d       d {     ||jB                        }|jE                  || j<                         d {   }|j>                  s^d d d       d {     |	       }|jF                  jI                  |       |jJ                  d   jL                  jN                  cd d d       d {    S # t        $ r ddlm}m} ddlm	}m
}	 ddlm}
 Y w xY w# t*        $ r}t+        d      |d }~ww xY w7 7 H7 &7 7 7 # 1 d {  7  sw Y   xY w7 l# 1 d {  7  sw Y   y xY ww)Nr   r^   ra   )rd   CompletionResponse)TextGenerationAsyncServiceStub)GetOperationRequest)OperationServiceStubrf   z"operation.api.cloud.yandex.net:443rg   ri   rj   rk   rm   rp      )operation_id)(asynciorr   rs   r_   r`   rt   rb   rc   ru   rd   r   rv   r   rw   rx   ry   rz   ,yandex.cloud.operation.operation_service_pb2r   1yandex.cloud.operation.operation_service_pb2_grpcr   r{   r|   aior}   r)   r   r$   r&   r~   r/   donesleepidGetresponseUnpackr   r   rW   )r4   rR   r   rr   r_   r`   rb   rc   rd   r   r   r   r   r   operation_api_urlr   r   r   r   	operationoperation_channeloperation_stuboperation_requestcompletion_responses                           r5   _amake_requestr      sS    &H	 	U	
 =668xx&&txx1DE @ @#nn0'd.>.>?%DOO<  678
 .g6//'D<N<N/OO	88**2
 
	 
	12CDNnnmmA&&&$7Y\\$R!"0"4"4%!// #5 # 	  nn	
	 
	 12!!"56"//2::??3@ @ @/ # 	 	   .
 	@ P
	
 '
	 
	 
	 
	@ @ @ @s  I(H G* H <I(3H-4I(7A1I(H0)$IH3I)H<:H6;7H<2H83H<IH:AII($I%I(*H	H HH 	H*H%%H**I(0I3I6H<8H<:I<I	II	
II(I%II%!I(c           
         ddl m} | j                  }d}t        dt	        | j
                        t        d||      t        |      t        t        t        j                              S )Nr   )RpcError<   Tr   )
multiplierminmax)reraiser(   waitr   before_sleep)rr   r   r,   r   r   r+   r   r   r   loggerloggingWARNING)llmr   min_secondsmax_secondss       r5   _create_retry_decoratorr   8  sS    $$KK0M&2%fgoo> r7   c                @     t               }|d fd       } |di |S )z*Use tenacity to retry the completion call.c                     t        fi | S N)r   _kwargsr   s    r5   _completion_with_retryz5completion_with_retry.<locals>._completion_with_retryJ  s    S,G,,r7   r   r   rH   r   r2   r   r   rV   retry_decoratorr   s   `   r5   rS   rS   F  s/    -c2O- - "+F++r7   c                \    K   t               }|d fd       } |di | d{   S 7 w)z0Use tenacity to retry the async completion call.c                 8   K   t        fi |  d {   S 7 wr   )r   r   s    r5   r   z6acompletion_with_retry.<locals>._completion_with_retryU  s     #C373333s   Nr   r2   r   r   s   `   r5   rZ   rZ   Q  s9     -c2O4 4 (1&1111s   ",*,)r4   rO   rR   r   rH   r   )r   rO   rH   zCallable[[Any], Any])r   rO   rV   r   rH   r   ))
__future__r   r   typingr   r   r   r   r   r	   langchain_core.callbacksr
   r   #langchain_core.language_models.llmsr    langchain_core.load.serializabler   langchain_core.utilsr   r   r   pydanticr   tenacityr   r   r   r   r   langchain_community.llms.utilsr   	getLoggerrI   r   r   rO   r   r   r   rS   rZ   r2   r7   r5   <module>r      s    "  @ @ 4 9 V V   ?			8	$Z\ ZzE EP/5
/5/5 	/5dC@L,2r7   