
    dhz9                        S SK Jr  S SKrS SKJrJrJrJrJrJ	r	  S SK
JrJr  S SKJr  S SKJr  S SKJrJr  S SKJr  S S	KJr  S S
KJr  S SKJrJr      SS jr " S S\5      r " S S\\5      rg)    )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	SecretStrc                    U R                  SS5      (       d	  [        SS9$ [        U R                  S   R                  S9$ )z0Convert a stream response to a generation chunk.choicesN )textr   )getr   r   r   )stream_responses    Y/var/www/html/shao/venv/lib/python3.13/site-packages/langchain_community/llms/friendli.py$_stream_response_to_generation_chunkr      sC     y$//B''$$Q',,     c                      \ rS rSr% Sr\" SSS9rS\S'   \" SSS9rS\S'   S	r	S
\S'   Sr
S\S'   SrS\S'   SrS\S'   SrS\S'   SrS\S'   SrS\S'   SrS\S'   SrS\S'   SrS\S'   \SS j5       rSrg)BaseFriendli"   zBase class of Friendli.NT)defaultexcluder   clientasync_clientzmeta-llama-3.1-8b-instructstr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_pc                d    SSK n[        [        USS5      5      nXAS'   UR	                  5       nUS   =(       d    [
        R                  " S5      nXaS'   US   =(       d    UR                  XVS	9US'   US
   =(       d    UR                  XVS	9US
'   U$ ! [         a  n[        S5      UeSnAff = f)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#   )tokenteam_idr$   )	friendliImportErrorr   r   get_secret_valueosgetenvFriendliAsyncFriendli)clsvaluesr7   er'   friendli_token_strr(   s          r   validate_environment!BaseFriendli.validate_environmentK   s    	 / )9;KL
 $2 +<<>/M299_3M"/!(+ 
x/@/@$ 0A 0
x "(!7 "
8;Q;Q$ <R <
~ '  	H 	s   B 
B/B**B/ )r?   r   returnr   )__name__
__module____qualname____firstlineno____doc__r   r#   __annotations__r$   r&   r'   r(   r*   r+   r,   r-   r/   r0   r1   r   rB   __static_attributes__rD   r   r   r   r   "   s    ! d3FC3dD9L#9-E3-*.N'.#'M='It
 *.- )-o, !%J$ !%D
$ $(K' "E?! r   r   c                  n  ^  \ rS rSrSr\SS j5       r\SS j5       r\SS j5       r\SS j5       r	 S     SS jjr
  S         SS jjr  S         SS	 jjr  S         SS
 jjr  S         SS jjr  S         SU 4S jjjr  S         SU 4S jjjrSrU =r$ )r<   f   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="meta-llama-3.1-8b-instruct", friendli_token="YOUR FRIENDLI TOKEN"
        )
c                
    SS0$ )Nr'   r3   rD   selfs    r   
lc_secretsFriendli.lc_secretsw   s     "233r   c                    U R                   U R                  U R                  U R                  U R                  U R
                  S.$ )z@Get the default parameters for calling Friendli completions API.r+   r,   r-   r/   r0   r1   rU   rP   s    r   _default_paramsFriendli._default_params{   s>     "&!7!7 $ 5 5//II++ZZ
 	
r   c                6    SU R                   0U R                  E$ )zGet the identifying parameters.r&   )r&   rV   rP   s    r   _identifying_paramsFriendli._identifying_params   s     <t';';<<r   c                    g)zReturn type of llm.r7   rD   rP   s    r   	_llm_typeFriendli._llm_type   s     r   c                    U R                   nU R                  b  Ub  [        S5      eU R                  b  U R                  US'   OXS'   0 UEUE$ )z,Get the parameters used to invoke the model.z2`stop` found in both the input and default params.r/   )rV   r/   
ValueError)rQ   r/   kwargsparamss       r   _get_invocation_paramsFriendli._get_invocation_params   sX     %%99 T%5QRRYY"!YYF6N!6N#&#F##r   c                    U R                   " SSU0UD6nU R                  R                  R                  " SU R                  USS.UD6nUR
                  S   R                  $ )a  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.")
r/   Fr&   promptstreamr   rD   )rb   r#   completionscreater&   r   r   rQ   rf   r/   run_managerr`   ra   
completions          r   _callFriendli._call   sg    : ,,A$A&A[[,,33 
**VE
=C

 !!!$)))r   c                   #    U R                   " SSU0UD6nU R                  R                  R                  " SU R                  USS.UD6I Sh  vN nUR
                  S   R                  $  N7f)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.")
r/   Fre   Nr   rD   )rb   r$   rh   ri   r&   r   r   rj   s          r   _acallFriendli._acall   sv     : ,,A$A&A,,88?? 
**VE
=C
 

 !!!$)))
s   AA.A,A.c              +    #    U R                   " SSU0UD6nU R                  R                  R                  " SU R                  USS.UD6nU H3  n[        U5      nU(       a  UR                  UR                  US9  Uv   M5     g 7fNr/   Tre   )chunkrD   )rb   r#   rh   ri   r&   r   on_llm_new_tokenr   	rQ   rf   r/   rk   r`   ra   rg   linert   s	            r   _streamFriendli._stream   s      ,,A$A&A((// 
**VD
<B
 D8>E,,TYYe,DK	 s   BBc               F  #    U R                   " SSU0UD6nU R                  R                  R                  " SU R                  USS.UD6I S h  vN nU  S h  vN n[        U5      nU(       a"  UR                  UR                  US9I S h  vN   U7v   MD   NJ NA N
 g 7frs   )rb   r$   rh   ri   r&   r   ru   r   rv   s	            r   _astreamFriendli._astream   s      ,,A$A&A((44;; 
**VD
<B
 
 ! 	$8>E!22499E2JJJK
	 K !sH   AB!BB!BBB0B!BB!BB!B!c                "  > SU R                   0nU R                  (       aV  [        U5      S:  a  [        S5      eSnU R                  " US   X#40 UD6 H  nUc  UnM
  Xg-  nM     Uc   e[        U//US9$ [        T	U ]  " XU40 UD6nXXl        U$ )a  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*   lenr_   rx   r   super	_generater   
rQ   promptsr/   rk   r`   r   
generationrt   
llm_result	__class__s
            r   r   Friendli._generate  s    : tzz*
>>7|a !OPP48Jgaj$NvN%!&J'J	 O
 ))):,JOOW&wkLVL
 *r   c                L  >#    SU R                   0nU R                  (       aI  [        U5      S:  a  [        S5      eSnU R                  " US   X#40 UD6  Sh  vN nUc  UnM  Xg-  nM  [        T	U ]  " XU40 UD6I Sh  vN nXXl        U$  N3
 Uc   e[        U//US9$  N 7f)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&   r~   r   Nr   r   )	r&   r*   r   r_   r{   r   r   
_agenerater   r   s
            r   r   Friendli._agenerate5  s     > tzz*
>>7|a !OPPJ#}}WQZUfU (e%!&J'J !7-g[SFSS
 *(U
 ))):,JOOSs6   AB$BBB#B$B"B$BB$rD   )rE   zDict[str, str])rE   Dict[str, Any])rE   r%   )N)r/   r.   r`   r   rE   r   )NN)
rf   r%   r/   r.   rk   "Optional[CallbackManagerForLLMRun]r`   r   rE   r%   )
rf   r%   r/   r.   rk   'Optional[AsyncCallbackManagerForLLMRun]r`   r   rE   r%   )
rf   r%   r/   r.   rk   r   r`   r   rE   zIterator[GenerationChunk])
rf   r%   r/   r.   rk   r   r`   r   rE   zAsyncIterator[GenerationChunk])
r   	list[str]r/   r.   rk   r   r`   r   rE   r   )
r   r   r/   r.   rk   r   r`   r   rE   r   )rF   rG   rH   rI   rJ   propertyrR   rV   rY   r\   rb   rm   rp   rx   r{   r   r   rL   __classcell__)r   s   @r   r<   r<   f   s     4 4 	
 	
 = =  
 +/$'$:=$	$  %):>	!*!* "!* 8	!*
 !* 
!*L %)?C	!*!* "!* =	!*
 !* 
!*L %):>	 " 8	
  
#( %)?C	 " =	
  
(( %):>	-- "- 8	-
 - 
- -d %)?C	// "/ =	/
 / 
/ /r   r<   )r   r   rE   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<   rD   r   r   <module>r      sa    " 	 E E 4 9 = ) 9 < %A< AH~sL ~r   