
    ih)                    4   d Z 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mZmZmZ ddlmZ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!  ejD                  e#      Z$ddZ%ddZ& G d de!e      Z'	 	 	 	 	 	 ddZ(ddZ)ddZ*ddZ+ddZ,y)z%Wrapper around YandexGPT chat models.    )annotationsN)AnyCallableDictListOptionalcast)AsyncCallbackManagerForLLMRunCallbackManagerForLLMRun)BaseChatModel)	AIMessageBaseMessageHumanMessageSystemMessage)ChatGeneration
ChatResult)before_sleep_logretryretry_if_exception_typestop_after_attemptwait_exponential)enforce_stop_tokens)_BaseYandexGPTc                    | |dS )Nroletext r   s     d/var/www/html/dev/engine/venv/lib/python3.12/site-packages/langchain_community/chat_models/yandex.py_parse_messager    "   s    $''    c                P   g }| D ]  }t        t        |j                        }t        |t              r|j                  t        d|             t        |t              r|j                  t        d|             t        |t              s|j                  t        d|              |S )z`Parse a sequence of messages into history.

    Returns:
        A list of parsed messages.
    user	assistantsystem)	r	   strcontent
isinstancer   appendr    r   r   )historychat_historymessager'   s       r   _parse_chat_historyr-   &   s     L CsGOO,g|,vw ?@gy){G DEg}-x ABC r!   c                  P    e Zd ZdZ	 	 d	 	 	 	 	 	 	 	 	 ddZ	 	 d	 	 	 	 	 	 	 	 	 ddZy)ChatYandexGPTaD  YandexGPT large language models.

    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`.

    Example:
        .. code-block:: python

            from langchain_community.chat_models import ChatYandexGPT
            chat_model = ChatYandexGPT(iam_token="t1.9eu...")

    Nc                    t        | |      }||nt        ||      }t        |      }t        t	        |      g      S )a  Generate next turn in the conversation.
        Args:
            messages: The history of the conversation as a list of messages.
            stop: The list of stop words (optional).
            run_manager: The CallbackManager for LLM run, it's not used at the moment.

        Returns:
            The ChatResult that contains outputs generated by the model.

        Raises:
            ValueError: if the last message in the list is not from human.
        messagesr'   r,   generations)completion_with_retryr   r   r   r   selfr2   stoprun_managerkwargsr   r,   s          r   	_generatezChatYandexGPT._generateJ   s@    & %TH=|t)<T4)HD)~g'F&GHHr!   c                   K   t        | |       d{   }||nt        ||      }t        |      }t        t	        |      g      S 7 7w)a  Async method to generate next turn in the conversation.

        Args:
            messages: The history of the conversation as a list of messages.
            stop: The list of stop words (optional).
            run_manager: The CallbackManager for LLM run, it's not used at the moment.

        Returns:
            The ChatResult that contains outputs generated by the model.

        Raises:
            ValueError: if the last message in the list is not from human.
        r1   Nr3   r4   r5   )acompletion_with_retryr   r   r   r   r8   s          r   
_ageneratezChatYandexGPT._agenerateb   sM     ( ,D8DD|t)<T4)HD)~g'F&GHH Es   AA8A)NN)
r2   List[BaseMessage]r:   Optional[List[str]]r;   z"Optional[CallbackManagerForLLMRun]r<   r   returnr   )
r2   rA   r:   rB   r;   z'Optional[AsyncCallbackManagerForLLMRun]r<   r   rC   r   )__name__
__module____qualname____doc__r=   r@   r   r!   r   r/   r/   8   s    ( %):>	I#I "I 8	I
 I 
I6 %)?C	I#I "I =	I
 I 
Ir!   r/   c                   	 dd l }ddlm}m} 	 ddlm}m} ddlm} ddl	m
} |st!        d      t#        |      }
|j%                         }|j'                  | j(                  |      } || j*                   | || j,                         || j.                        	      |
D cg c]
  } |di | c}
      } ||      }|j1                  || j2                        }t5        |      d   j6                  d   j8                  j:                  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c c}w )Nr   DoubleValue
Int64ValueCompletionOptionsMessage)CompletionRequest)TextGenerationServiceStubkPlease install YandexCloud SDK  with `pip install yandexcloud`             or upgrade it to recent version.:You should provide at least one message to start the chat!valuetemperature
max_tokens	model_uricompletion_optionsr2   metadatar   )grpcgoogle.protobuf.wrappers_pb2rJ   rK   4yandex.cloud.ai.foundation_models.v1.text_common_pb2rM   rN   Pyandex.cloud.ai.foundation_models.v1.text_generation.text_generation_service_pb2rO   Uyandex.cloud.ai.foundation_models.v1.text_generation.text_generation_service_pb2_grpcrP   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
ValueErrorr-   ssl_channel_credentialssecure_channelurlrY   rV   rW   
Completiongrpc_metadatalistalternativesr,   r   )r9   r2   r]   rJ   rK   rM   rN   rO   rP   emessage_historychannel_credentialschannelr,   requeststubress                    r   _make_requestrv   |   sI   H	& UVV)(3O668!!$((,?@G..,#$*:*:;!8
 5DD'$G$DG %W-D
//'D,>,>/
?C9Q<$$Q'//444? # 
	 
	  .
 	  Es:   D2 D #ED/+D2 .D//D2 2	E;EE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} |st-        d	      t/        |      }d
}|j1                         }|j2                  j5                  | j6                  |      4 d {   } || j8                   | || j:                         || j<                              |D cg c]
  } |di | c}      } |
|      }|j?                  || j@                         d {   }|j2                  j5                  ||      4 d {   } ||      }|jB                  s^|jE                  d       d {     ||jF                        }|jI                  || j@                         d {   }|jB                  s^d d d       d {     |	       }|jJ                  jM                  |       |jN                  d   jP                  jR                  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 c c}w 7 M7 +7 7 7 # 1 d {  7  sw Y   xY w7 r# 1 d {  7  sw Y   y xY ww)Nr   rI   rL   )rO   CompletionResponse)TextGenerationAsyncServiceStub)GetOperationRequest)OperationServiceStubrQ   rR   z"operation.api.cloud.yandex.net:443rS   rU   rX   r[      )operation_idr   )*asyncior]   r^   rJ   rK   r_   rM   rN   r`   rO   rx   ra   ry   rb   rc   rd   re   ,yandex.cloud.operation.operation_service_pb2rz   1yandex.cloud.operation.operation_service_pb2_grpcr{   rf   rg   r-   rh   aiori   rj   rY   rV   rW   rk   rl   donesleepidGetresponseUnpackrn   r,   r   )r9   r2   r~   r]   rJ   rK   rM   rN   rO   rx   ry   rz   r{   ro   rp   operation_api_urlrq   rr   r,   rs   rt   	operationoperation_channeloperation_stuboperation_requestcompletion_responses                             r   _amake_requestr      s{    &H	 	U	
 UVV)(3O<668xx&&txx1DE @ @#nn0'd.>.>?%DOO<  9HHWg((H
 .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@ @ @5 # 	 	   .
 	@ I P
	
 '
	 
	 
	 
	@ @ @ @s  JH3 H H3 AJIJ=I<I0I<I$I<0I1I<4)I%I7I%I!I%'I<2I#3AI<;JI:JH0,H3 /H00H3 3	I<IIJI<I<I%!I%#I<%I7	+I.,I7	3I<:J<JJJ
J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)r]   r   sleep_intervalr   r   max_retriesr   r   r   loggerloggingWARNING)llmr   min_secondsmax_secondss       r   _create_retry_decoratorr      sS    $$KK0M&2%fgoo> r!   c                @     t               }|d fd       } |di |S )z*Use tenacity to retry the completion call.c                     t        fi | S N)rv   _kwargsr   s    r   _completion_with_retryz5completion_with_retry.<locals>._completion_with_retry  s    S,G,,r!   r   r   rC   r   r   r   r   r<   retry_decoratorr   s   `   r   r7   r7     s/    -c2O- - "+F++r!   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    r   r   z6acompletion_with_retry.<locals>._completion_with_retry  s     #C373333s   Nr   r   r   r   s   `   r   r?   r?     s9     -c2O4 4 (1&1111s   ",*,)r   r&   r   r&   rC   r   )r*   rA   rC   zList[Dict[str, str]])r9   r/   r2   rA   rC   r&   )r   r/   rC   zCallable[[Any], Any])r   r/   r<   r   rC   r   )-rG   
__future__r   r   typingr   r   r   r   r   r	   langchain_core.callbacksr
   r   *langchain_core.language_models.chat_modelsr   langchain_core.messagesr   r   r   r   langchain_core.outputsr   r   tenacityr   r   r   r   r   langchain_community.llms.utilsr   langchain_community.llms.yandexr   	getLoggerrD   r   r    r-   r/   rv   r   r   r7   r?   r   r!   r   <module>r      s    + "  < < E  >  ? :			8	$($AINM AIH25
2525 	25jF@R,2r!   