
    Ng8                        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 d dlmZ d d	lmZ d d
lmZ d dlmZmZ ddZ G d de          Z G d dee          ZdS )    )annotationsN)AnyAsyncIteratorDictIteratorListOptional)AsyncCallbackManagerForLLMRunCallbackManagerForLLMRun)LLM)Serializable)GenerationChunk	LLMResult)pre_init)get_from_dict_or_env)convert_to_secret_str)Field	SecretStrstream_responser   returnr   c                    | j         dk    r*t          | j        dt          | j                  i          S t          d          S )z0Convert a stream response to a generation chunk.token_sampledtoken)textgeneration_info )r   )eventr   r   strr   )r   s    ]/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/llms/friendli.py$_stream_response_to_generation_chunkr       sS    // %$c/*?&@&@A
 
 
 	
 ####    c                      e Zd ZU dZ edd          Zde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dS ) BaseFriendlizBase class of Friendli.NT)defaultexcluder   clientasync_clientzmixtral-8x7b-instruct-v0-1r   modelzOptional[SecretStr]friendli_tokenzOptional[str]friendli_teamFbool	streamingzOptional[float]frequency_penaltypresence_penaltyzOptional[int]
max_tokensOptional[List[str]]stoptemperaturetop_pvaluesr   r   c                   	 ddl }n"# t          $ r}t          d          |d}~ww xY wt          t          |dd                    }||d<   |                                }|d         pt          j        d          }||d<   |d         p|                    ||	          |d<   |d
         p|                    ||	          |d
<   |S )z=Validate if personal access token is provided in environment.r   NzfCould not import friendli-client python package. Please install it with `pip install friendli-client`.r)   FRIENDLI_TOKENr*   FRIENDLI_TEAMr&   )r   team_idr'   )	friendliImportErrorr   r   get_secret_valueosgetenvFriendliAsyncFriendli)clsr4   r9   er)   friendli_token_strr*   s          r   validate_environmentz!BaseFriendli.validate_environmentF   s   	OOOO 	 	 	H  	 / )9;KLL
 
 $2 +<<>>/M29_3M3M"/!(+ 
x/@/@$m 0A 0
 0
x "(!7 "
8;Q;Q$m <R <
 <
~ s    
&!&)r4   r   r   r   )__name__
__module____qualname____doc__r   r&   __annotations__r'   r(   r)   r*   r,   r-   r.   r/   r1   r2   r3   r   rC    r!   r   r#   r#      s4        !! %d333F3333dD999L9999-E----*.N....#'M''''I
 *.---- )-,,,, !%J$$$$ !%D$$$$ $(K'''' "E!!!!   X  r!   r#   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#dZ		 	 d$d%dZ
	 	 d$d&dZ	 	 d$d'dZ	 	 d$d(dZ	 	 d$d) fdZ	 	 d$d* fdZ xZS )+r>   a  Friendli LLM.

    ``friendli-client`` package should be installed with `pip install friendli-client`.
    You must set ``FRIENDLI_TOKEN`` environment variable or provide the value of your
    personal access token for the ``friendli_token`` argument.

    Example:
        .. code-block:: python

            from langchain_community.llms import Friendli

            friendli = Friendli(
                model="mixtral-8x7b-instruct-v0-1", friendli_token="YOUR FRIENDLI TOKEN"
            )
    r   Dict[str, str]c                
    ddiS )Nr)   r6   rI   selfs    r   
lc_secretszFriendli.lc_secretsr   s     "233r!   Dict[str, Any]c                P    | j         | j        | j        | j        | j        | j        dS )z@Get the default parameters for calling Friendli completions API.r-   r.   r/   r1   r2   r3   rR   rM   s    r   _default_paramszFriendli._default_paramsv   s4     "&!7 $ 5/I+Z
 
 	
r!   c                "    d| j         i| j        S )zGet the identifying parameters.r(   )r(   rS   rM   s    r   _identifying_paramszFriendli._identifying_params   s     <t';<<r!   r   c                    dS )zReturn type of llm.r9   rI   rM   s    r   	_llm_typezFriendli._llm_type   s	     zr!   Nr1   r0   kwargsr   c                z    | j         }| j        |t          d          | j        | j        |d<   n||d<   i ||S )z,Get the parameters used to invoke the model.Nz2`stop` found in both the input and default params.r1   )rS   r1   
ValueError)rN   r1   rX   paramss       r   _get_invocation_paramszFriendli._get_invocation_params   sV     %9 T%5QRRRY"!YF6NN!F6N#&#F##r!   promptrun_manager"Optional[CallbackManagerForLLMRun]c                     | j         dd|i|} | j        j        j        d| j        |dd|}|j        d         j        S )a1  Call out Friendli's completions API.

        Args:
            prompt (str): The text prompt to generate completion for.
            stop (Optional[List[str]], optional): When one of the stop phrases appears
                in the generation result, the API will stop generation. The stop phrases
                are excluded from the result. If beam search is enabled, all of the
                active beams should contain the stop phrase to terminate generation.
                Before checking whether a stop phrase is included in the result, the
                phrase is converted into tokens. We recommend using stop_tokens because
                it is clearer. For example, after tokenization, phrases "clear" and
                " clear" can result in different token sequences due to the prepended
                space character. Defaults to None.

        Returns:
            str: The generated text output.

        Example:
            .. code-block:: python

                response = frienldi("Give me a recipe for the Old Fashioned cocktail.")
        r1   Fr(   r]   streamr   rI   )r\   r&   completionscreater(   choicesr   rN   r]   r1   r^   rX   r[   
completions          r   _callzFriendli._call   sh    : -,AA$A&AA3T[,3 
*VE
 
=C
 

 !!$))r!   'Optional[AsyncCallbackManagerForLLMRun]c                   K    | j         dd|i|} | j        j        j        d| j        |dd| d{V }|j        d         j        S )a%  Call out Friendli's completions API Asynchronously.

        Args:
            prompt (str): The text prompt to generate completion for.
            stop (Optional[List[str]], optional): When one of the stop phrases appears
                in the generation result, the API will stop generation. The stop phrases
                are excluded from the result. If beam search is enabled, all of the
                active beams should contain the stop phrase to terminate generation.
                Before checking whether a stop phrase is included in the result, the
                phrase is converted into tokens. We recommend using stop_tokens because
                it is clearer. For example, after tokenization, phrases "clear" and
                " clear" can result in different token sequences due to the prepended
                space character. Defaults to None.

        Returns:
            str: The generated text output.

        Example:
            .. code-block:: python

                response = await frienldi("Tell me a joke.")
        r1   Fra   Nr   rI   )r\   r'   rc   rd   r(   re   r   rf   s          r   _acallzFriendli._acall   s      : -,AA$A&AA?4,8? 
*VE
 
=C
 
 
 
 
 
 
 

 !!$))r!   Iterator[GenerationChunk]c              +     K    | j         dd|i|} | j        j        j        d| j        |dd|}|D ]3}t          |          }|r|                    |j        |           |V  4d S Nr1   Tra   )chunkrI   )r\   r&   rc   rd   r(   r    on_llm_new_tokenr   	rN   r]   r1   r^   rX   r[   rb   linero   s	            r   _streamzFriendli._stream   s       -,AA$A&AA/(/ 
*VD
 
<B
 
  	 	D8>>E E,,TYe,DDDKKKK		 	r!   AsyncIterator[GenerationChunk]c                  K    | j         dd|i|} | j        j        j        d| j        |dd| d {V }|2 3 d {V }t          |          }|r"|                    |j        |           d {V  |W V  @6 d S rn   )r\   r'   rc   rd   r(   r    rp   r   rq   s	            r   _astreamzFriendli._astream   s       -,AA$A&AA;t(4; 
*VD
 
<B
 
 
 
 
 
 
 
 ! 	 	 	 	 	 	 	$8>>E K!2249E2JJJJJJJJJKKKKK	 !&&s   A:prompts	list[str]r   c                *   d| j         i}| j        r^t          |          dk    rt          d          d} | j        |d         ||fi |D ]}||}||z  }|J t          |gg|          S  t                      j        |||fi |}||_        |S )a1  Call out Friendli's completions API with k unique prompts.

        Args:
            prompt (str): The text prompt to generate completion for.
            stop (Optional[List[str]], optional): When one of the stop phrases appears
                in the generation result, the API will stop generation. The stop phrases
                are excluded from the result. If beam search is enabled, all of the
                active beams should contain the stop phrase to terminate generation.
                Before checking whether a stop phrase is included in the result, the
                phrase is converted into tokens. We recommend using stop_tokens because
                it is clearer. For example, after tokenization, phrases "clear" and
                " clear" can result in different token sequences due to the prepended
                space character. Defaults to None.

        Returns:
            str: The generated text output.

        Example:
            .. code-block:: python

                response = frienldi.generate(["Tell me a joke."])
        r(      ,Cannot stream results with multiple prompts.Nr   generations
llm_output)	r(   r,   lenrZ   rs   r   super	_generater~   
rN   rw   r1   r^   rX   r~   
generationro   
llm_result	__class__s
            r   r   zFriendli._generate  s    : tz*
> 	P7||a !OPPP48J%gaj$NNvNN ( (%!&JJ%'JJ))):,JOOOO&UWW&wkLLVLL
 *
r!   c                F  K   d| j         i}| j        rdt          |          dk    rt          d          d} | j        |d         ||fi |2 3 d{V }||}||z  }6 |J t          |gg|          S  t                      j        |||fi | d{V }||_        |S )a  Call out Friendli's completions API asynchronously with k unique prompts.

        Args:
            prompt (str): The text prompt to generate completion for.
            stop (Optional[List[str]], optional): When one of the stop phrases appears
                in the generation result, the API will stop generation. The stop phrases
                are excluded from the result. If beam search is enabled, all of the
                active beams should contain the stop phrase to terminate generation.
                Before checking whether a stop phrase is included in the result, the
                phrase is converted into tokens. We recommend using stop_tokens because
                it is clearer. For example, after tokenization, phrases "clear" and
                " clear" can result in different token sequences due to the prepended
                space character. Defaults to None.

        Returns:
            str: The generated text output.

        Example:
            .. code-block:: python

                response = await frienldi.agenerate(
                    ["Give me a recipe for the Old Fashioned cocktail."]
                )
        r(   rz   r{   Nr   r|   )	r(   r,   r   rZ   rv   r   r   
_agenerater~   r   s
            r   r   zFriendli._agenerate0  s     > tz*
> 	P7||a !OPPPJ,t}WQZ{UUfUU ( ( ( ( ( ( (e%!&JJ%'JJ	  V
 ))):,JOOOO-577-gt[SSFSSSSSSSS
 *
s   A )r   rK   )r   rP   )r   r   )N)r1   r0   rX   r   r   rP   )NN)
r]   r   r1   r0   r^   r_   rX   r   r   r   )
r]   r   r1   r0   r^   ri   rX   r   r   r   )
r]   r   r1   r0   r^   r_   rX   r   r   rl   )
r]   r   r1   r0   r^   ri   rX   r   r   rt   )
rw   rx   r1   r0   r^   r_   rX   r   r   r   )
rw   rx   r1   r0   r^   ri   rX   r   r   r   )rD   rE   rF   rG   propertyrO   rS   rU   rW   r\   rh   rk   rs   rv   r   r   __classcell__)r   s   @r   r>   r>   a   s          4 4 4 X4 	
 	
 	
 X	
 = = = X=    X
 +/$ $ $ $ $  %):>	!* !* !* !* !*L %)?C	!* !* !* !* !*L %):>	    ( %)?C	    ( %):>	- - - - - - -d %)?C	/ / / / / / / / / / /r!   r>   )r   r   r   r   ) 
__future__r   r<   typingr   r   r   r   r   r	    langchain_core.callbacks.managerr
   r   #langchain_core.language_models.llmsr    langchain_core.load.serializabler   langchain_core.outputsr   r   langchain_core.utilsr   langchain_core.utils.envr   langchain_core.utils.utilsr   pydanticr   r   r    r#   r>   rI   r!   r   <module>r      s   " " " " " " 				 E E E E E E E E E E E E E E E E        4 3 3 3 3 3 9 9 9 9 9 9 = = = = = = = = ) ) ) ) ) ) 9 9 9 9 9 9 < < < < < < % % % % % % % %$ $ $ $A A A A A< A A AH~ ~ ~ ~ ~sL ~ ~ ~ ~ ~r!   