
    dh;                    l   S SK Jr  S SKrS SKrS SKrS SKJrJrJrJ	r	J
r
Jr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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$J%r%J&r&J'r'  \RP                  " \)5      r*\" S5      r+SS jr,SS jr-SS jr.SS jr/SS jr0SS jr1    SS jr2 " S S\5      r3g)    )annotationsN)AnyAsyncIterableAsyncIteratorCallableDictIterableIteratorListMappingOptionalTupleTypeVar)AsyncCallbackManagerForLLMRunCallbackManagerForLLMRun)BaseLLM)
GenerationGenerationChunk	LLMResult)get_from_dict_or_envpre_init)Field)	HTTPError)before_sleep_logretryretry_if_exception_typestop_after_attemptwait_exponentialTTongyic           
         SnSn[        S[        U R                  5      [        SXS9[	        [
        5      [        [        [        R                  5      S9$ )N      T)
multiplierminmax)reraisestopwaitr   before_sleep)
r   r   max_retriesr   r   r   r   loggerloggingWARNING)llmmin_secondsmax_secondss      W/var/www/html/shao/venv/lib/python3.13/site-packages/langchain_community/llms/tongyi.py_create_retry_decoratorr3   *   sJ    KK 0M&y1%fgoo>     c                    U S   S:X  a  U $ U S   S;   a#  [        SU S    SU S    SU S    S	U S
    35      e[        SU S    SU S    S	U S
    3U S9e)z,Check the response from the completion call.status_code   )i  i  zrequest_id: 
request_idz 
 status_code: z	 
 code: codez 
 message: messagez"HTTP error occurred: status_code: )response)
ValueErrorr   )resps    r2   check_responser>   8   s    Mc!	m	
	*4-. / /0 1&\N-Y/@B
 	
 0m1D0E F&\N-Y/@B
 	
r4   c                D   ^  [        T 5      nUSU 4S jj5       nU" S0 UD6$ )*Use tenacity to retry the completion call.c                 R   > TR                   R                  " S0 U D6n[        U5      $ N clientcallr>   )_kwargsr=   r/   s     r2   _generate_with_retry1generate_with_retry.<locals>._generate_with_retryN   s#    zz))d##r4   rG   r   returnr   rC   r3   )r/   kwargsretry_decoratorrH   s   `   r2   generate_with_retryrO   J   s/    -c2O$ $  )&))r4   c                D   ^  [        T 5      nUSU 4S jj5       nU" S0 UD6$ )r@   c               ;  r   >#    TR                   R                  " S0 U D6nU H  n[        U5      v   M     g 7frB   rD   )rG   	responsesr=   r/   s      r2   _stream_generate_with_retry?stream_generate_with_retry.<locals>._stream_generate_with_retryZ   s0     JJOO.g.	D && s   47rJ   rC   rL   )r/   rM   rN   rS   s   `   r2   stream_generate_with_retryrU   V   s/    -c2O' '
 '000r4   c               X   #     " S S5      nU" U 40 UD6  Sh  vN nU7v   M   N
 g7f)zAsync version of `stream_generate_with_retry`.

Because the dashscope SDK doesn't provide an async API,
we wrap `stream_generate_with_retry` with an async generator.c                  <    \ rS rSrSS jrS	S jrS
S jrS
S jrSrg)8astream_generate_with_retry.<locals>._AioTongyiGeneratori   c                &    [        U40 UD6U l        g N)rU   	generator)self_llmrG   s      r2   __init__Aastream_generate_with_retry.<locals>._AioTongyiGenerator.__init__j   s    7HHDNr4   c                    U $ r[   rC   r]   s    r2   	__aiter__Bastream_generate_with_retry.<locals>._AioTongyiGenerator.__aiter__m   s    Kr4   c                   #    [         R                  " 5       R                  S U R                  5      I S h  vN nUb  U$ [        e N7fr[   )asyncioget_running_looprun_in_executor
_safe_nextStopAsyncIteration)r]   values     r2   	__anext__Bastream_generate_with_retry.<locals>._AioTongyiGenerator.__anext__p   sD     !224DDdoo E  ((s   3AAAc                N     [        U R                  5      $ ! [         a     g f = fr[   )nextr\   StopIterationrb   s    r2   ri   Castream_generate_with_retry.<locals>._AioTongyiGenerator._safe_nexty   s(    DNN++  s    
$$)r\   N)r^   r    rG   r   )rK   zAsyncIterator[Any])rK   r   )	__name__
__module____qualname____firstlineno__r_   rc   rl   ri   __static_attributes__rC   r4   r2   _AioTongyiGeneratorrX   i   s    	I		)	r4   rw   NrC   )r/   rM   rw   chunks       r2   astream_generate_with_retryry   c   s2      , +39&9 e9s   *(&(*(*c              #     #    [        U 5      n [        U5      nU H  nUS4v   UnM     US4v   g! [         a     gf = f7f)zWGenerate elements from an iterable,
and a boolean indicating if it is the last element.NFT)iterro   rp   iterableiteratoritem	next_items       r2   generate_with_last_element_markr      sX      H~HH~ 	Ek  *  s    A2 A
?A?Ac                  #    U R                  5       n UR                  5       I Sh  vN nU  Sh  vN nUS47v   UnM   N! [         a     gf = f N!
 US47v   g7f)z]Generate elements from an async iterable,
and a boolean indicating if it is the last element.NFT)rc   rl   rj   r|   s       r2    agenerate_with_last_element_markr      sp     
 !!#H'')) $ iEk * 8 *sW   AA AA AAAAAA 
AAAAA	Ac                    ^  \ rS rSr% Sr\S'S j5       rSrS\S'   \	" SSS	9r
S
\S'    \	" \S9rS\S'   SrS\S'    \	" SSS	9rS\S'    SrS\S'    SrS\S'    \S(S j5       r\S)S j5       r\S*S j5       r\S+U 4S jj5       r  S,         S-S jjr  S,         S.S  jjr  S,         S/S! jjr  S,         S0S" jjrS1S# jr\ S2     S3S$ jj5       r\S4S% j5       rS&rU =r$ )5r       u  Tongyi completion model integration.

Setup:
    Install ``dashscope`` and set environment variables ``DASHSCOPE_API_KEY``.

    .. code-block:: bash

        pip install dashscope
        export DASHSCOPE_API_KEY="your-api-key"

Key init args — completion params:
    model: str
        Name of Tongyi model to use.
    top_p: float
        Total probability mass of tokens to consider at each step.
    streaming: bool
        Whether to stream the results or not.

Key init args — client params:
    api_key: Optional[str]
        Dashscope API KEY. If not passed in will be read from env var DASHSCOPE_API_KEY.
    max_retries: int
        Maximum number of retries to make when generating.

See full list of supported init args and their descriptions in the params section.

Instantiate:
    .. code-block:: python

        from langchain_community.llms import Tongyi

        llm = Tongyi(
            model="qwen-max",
            # top_p="...",
            # api_key="...",
            # other params...
        )

Invoke:
    .. code-block:: python

        input_text = "用50个字左右阐述，生命的意义在于"
        llm.invoke(input_text)

    .. code-block:: python

        '探索、成长、连接与爱——在有限的时间里，不断学习、体验、贡献并寻找与世界和谐共存之道，让每一刻充满价值与意义。'

Stream:
    .. code-block:: python

        for chunk in llm.stream(input_text):
            print(chunk)

    .. code-block:: python

        探索 | 、 | 成长 | 、连接与爱。 | 在有限的时间里，寻找个人价值， | 贡献于他人，共同体验世界的美好 | ，让世界因自己的存在而更 | 温暖。

Async:
    .. code-block:: python

        await llm.ainvoke(input_text)

        # stream:
        # async for chunk in llm.astream(input_text):
        #    print(chunk)

        # batch:
        # await llm.abatch([input_text])

    .. code-block:: python

        '探索、成长、连接与爱。在有限的时间里，寻找个人价值，贡献于他人和社会，体验丰富多彩的情感与经历，不断学习进步，让世界因自己的存在而更美好。'

c                
    SS0$ )Ndashscope_api_keyDASHSCOPE_API_KEYrC   rb   s    r2   
lc_secretsTongyi.lc_secrets   s    #%899r4   Nr   rE   z	qwen-plusmodel)defaultaliasstr
model_name)default_factoryDict[str, Any]model_kwargsg?floattop_papi_keyzOptional[str]r   Fbool	streaming
   intr+   c                    g)zReturn type of llm.tongyirC   rb   s    r2   	_llm_typeTongyi._llm_type  s     r4   c                    [        USS/S5      US'    SSKn UR                  US'   U$ ! [         a    [        S5      ef = f! [         a    [        S5      ef = f)	z?Validate that api key and python package exists in environment.r   r   r   r   NzZCould not import dashscope python package. Please install it with `pip install dashscope`.rE   z`dashscope` has no `Generation` attribute, this is likely due to an old version of the dashscope package. Try upgrading it with `pip install --upgrade dashscope`.)r   	dashscopeImportErrorr   AttributeErrorr<   )clsvaluesr   s      r2   validate_environmentTongyi.validate_environment	  s     ';()46I'
"#		(33F8   	B 	  	: 	s   * A A Ac                j    U R                   U R                  U R                  S.n0 UEU R                  E$ )z7Get the default parameters for calling Tongyi Qwen API.)r   r   r   )r   r   r   r   )r]   normal_paramss     r2   _default_paramsTongyi._default_params!  s:     __ZZ--
 6-54#4#455r4   c                4   > SU R                   0[        TU ]  E$ )Nr   )r   super_identifying_params)r]   	__class__s    r2   r   Tongyi._identifying_params,  s    dooM1LMMr4   c           
        / nU R                   (       al  [        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R	                  U R                  U5      /5        OUU R                  " SSU0UD6nU H;  n	[        U 4SU	0UD6n
UR	                  [        S0 U R                  U
5      D6/5        M=     [        USU R                  0S9$ )	Nr"   ,Cannot stream results with multiple prompts.r   r(   promptr   generations
llm_outputrC   )r   lenr<   _streamappend_chunk_to_generation_invocation_paramsrO   r   _generation_from_qwen_respr   r   r]   promptsr(   run_managerrM   r   
generationrx   paramsr   
completions              r2   	_generateTongyi._generate0  s    >>7|a !OPP48Jgaj$NvN%!&J'J	 O
 ))) 9 9* EFG%)%<%<%Q$%Q&%QF!0OfOO
""N$"A"A*"MNO "
 #doo
 	
r4   c                h  #    / 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  U R                  " SSU0UD6nU Hw  n	[        R                  " 5       R                  S [        R                  " [        40 X	S.UED65      I S h  vN n
UR	                  [        S0 U R                  U
5      D6/5        My     [        USU R                   0S9$  N
 Uc   eUR	                  U R                  U5      /5        N@ Nr7f)	Nr"   r   r   r(   )r/   r   r   r   rC   )r   r   r<   _astreamr   r   r   rf   rg   rh   	functoolspartialrO   r   r   r   r   r   s              r2   
_agenerateTongyi._agenerateQ  sH     >>7|a !OPP48J#}}WQZUfU (e%!&J'J &*%<%<%Q$%Q&%QF!#*#;#;#=#M#M%%+7;/XQW/X$ 
 ""N$"A"A*"MNO " #doo
 	
'(U
 ))) 9 9* EFGs8   AD2	DDDA,D2=D0>AD2D)D2c           	   +  
  #    U R                   " SUSS.UD6n[        [        U 4SU0UD65       HO  u  pg[        S0 U R	                  Xg5      D6nU(       a%  UR                  UR                  UU R                  S9  Uv   MQ     g 7fNT)r(   streamr   )rx   verboserC   )r   r   rU   r   r   on_llm_new_tokentextr   	r]   r   r(   r   rM   r   stream_respis_last_chunkrx   s	            r2   r   Tongyi._streamw  s      "&!8!8 "
d"
&,"
 +J&tEFEfE+
&K $ 11+ME ,,JJ LL - 
 K+
s   BBc           	    .  #    U R                   " SUSS.UD6n[        [        U 4SU0UD65        S h  vN u  pg[        S0 U R	                  Xg5      D6nU(       a-  UR                  UR                  UU R                  S9I S h  vN   U7v   M`   N[ N
 g 7fr   )r   r   ry   r   r   r   r   r   r   s	            r2   r   Tongyi._astream  s      "&!8!8 "
d"
&,"
 1Q'FVFvF1
 	,+ $ 11+ME !22JJ LL 3   
 K	1
s8   -BBBBABBBBBBc                j    0 U R                   EUEnUb  XS'   UR                  S5      (       a  SUS'   U$ )Nr(   r   Tincremental_output)r   get)r]   r(   rM   r   s       r2   r   Tongyi._invocation_params  sM    
""

 !6N::h+/F'(r4   c                    U(       a.  [        U S   S   [        U S   S   U S   [        U S   5      S9S9$ [        U S   S   S9$ )	Noutputr   finish_reasonr8   usage)r   r8   token_usager   generation_info)r   )dict)r=   r   s     r2   r   !Tongyi._generation_from_qwen_resp  s^     (^F+ $"&x."A#L1 $T'] 3!  T(^F344r4   c                >    [        U R                  U R                  S9$ )Nr   )r   r   r   )rx   s    r2   r   Tongyi._chunk_to_generation  s    !11
 	
r4   rC   )rK   zDict[str, str])rK   r   )r   r   rK   r   )rK   r   )rK   zMapping[str, Any])NN)
r   	List[str]r(   Optional[List[str]]r   "Optional[CallbackManagerForLLMRun]rM   r   rK   r   )
r   r   r(   r   r   'Optional[AsyncCallbackManagerForLLMRun]rM   r   rK   r   )
r   r   r(   r   r   r   rM   r   rK   zIterator[GenerationChunk])
r   r   r(   r   r   r   rM   r   rK   zAsyncIterator[GenerationChunk])r(   r   rM   r   rK   r   )T)r=   r   r   r   rK   r   )rx   r   rK   r   ) rr   rs   rt   ru   __doc__propertyr   rE   __annotations__r   r   r   r   r   r   r   r+   r   r   r   r   r   r   r   r   r   r   staticmethodr   r   rv   __classcell__)r   s   @r2   r    r       s   JX : : FCKw?J?#(#>L.>E5D',T'K}K5It/K<   . 6 6 N N %):>	

 "
 8	

 
 

H %)?C	$
$
 "$
 =	$

 $
 
$
R %):>	 " 8	
  
#6 %)?C	 " =	
  
(0	 )-55"&5	5 5, 
 
r4   )r/   r    rK   zCallable[[Any], Any])r=   r   rK   r   )r/   r    rM   r   rK   r   )r}   zIterable[T]rK   zIterator[Tuple[T, bool]])r}   zAsyncIterable[T]rK   zAsyncIterator[Tuple[T, bool]])4
__future__r   rf   r   r-   typingr   r   r   r   r   r	   r
   r   r   r   r   r   langchain_core.callbacksr   r   #langchain_core.language_models.llmsr   langchain_core.outputsr   r   r   langchain_core.utilsr   r   pydanticr   requests.exceptionsr   tenacityr   r   r   r   r   	getLoggerrr   r,   r   r3   r>   rO   rU   ry   r   r   r    rC   r4   r2   <module>r      s    "       8 I I ?  )  
		8	$CL
$	*
1@" m
W m
r4   