o
    Zh;                     @  s<  d dl mZ d dlZd dlZd dlZd dlmZmZmZm	Z	m
Z
mZ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 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%m&Z&m'Z' e(e)Z*edZ+d'ddZ,d(ddZ-d)ddZ.d)ddZ/d)ddZ0d*d d!Z1d+d$d%Z2G d&d deZ3dS ),    )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llmTongyireturnCallable[[Any], Any]c                 C  s6   d}d}t dt| jtd||dtttttj	dS )N      T)
multiplierminmax)reraisestopwaitr   before_sleep)
r   r   max_retriesr   r   r   r   loggerloggingWARNING)r   Zmin_secondsZmax_seconds r0   V/var/www/html/lang_env/lib/python3.10/site-packages/langchain_community/llms/tongyi.py_create_retry_decorator*   s   
r2   respr   c              
   C  sv   | d dkr| S | d dv r&t d| d  d| d  d| d  d	| d
  td| d  d| d  d	| d
  | d)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   )r3   r0   r0   r1   check_response8   s(   r;   kwargsc                   (   t  }|d fdd}|di |S )	*Use tenacity to retry the completion call._kwargsr   r!   c                    s    j jdi | }t|S Nr0   clientcallr;   )r?   r3   r   r0   r1   _generate_with_retryN   s   z1generate_with_retry.<locals>._generate_with_retryNr?   r   r!   r   r0   r2   )r   r<   retry_decoratorrE   r0   rD   r1   generate_with_retryJ   s   rI   c                   r=   )	r>   r?   r   r!   c                  ;  s,     j jdi | }|D ]}t|V  qd S r@   rA   )r?   	responsesr3   rD   r0   r1   _stream_generate_with_retryZ   s
   z?stream_generate_with_retry.<locals>._stream_generate_with_retryNrF   r0   rG   )r   r<   rH   rK   r0   rD   r1   stream_generate_with_retryV   s   rL   c                 K s:   G dd d}|| fi |2 z	3 dH W }|V  q6 dS )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                   @  s4   e Zd ZdddZdd	d
ZdddZdddZdS )z8astream_generate_with_retry.<locals>._AioTongyiGenerator_llmr    r?   r   c                 [  s   t |fi || _d S N)rL   	generator)selfrM   r?   r0   r0   r1   __init__j   s   zAastream_generate_with_retry.<locals>._AioTongyiGenerator.__init__r!   AsyncIterator[Any]c                 S  s   | S rN   r0   rP   r0   r0   r1   	__aiter__m   s   zBastream_generate_with_retry.<locals>._AioTongyiGenerator.__aiter__c                   s*   t  d | jI d H }|d ur|S trN   )asyncioget_running_looprun_in_executor
_safe_nextStopAsyncIteration)rP   valuer0   r0   r1   	__anext__p   s   
zBastream_generate_with_retry.<locals>._AioTongyiGenerator.__anext__c                 S  s"   zt | jW S  ty   Y d S w rN   )nextrO   StopIterationrS   r0   r0   r1   rX   y   s
   zCastream_generate_with_retry.<locals>._AioTongyiGenerator._safe_nextN)rM   r    r?   r   )r!   rR   )r!   r   )__name__
__module____qualname__rQ   rT   r[   rX   r0   r0   r0   r1   _AioTongyiGeneratori   s
    


	ra   Nr0   )r   r<   ra   chunkr0   r0   r1   astream_generate_with_retryc   s
   rc   iterableIterable[T]Iterator[Tuple[T, bool]]c                 c  sR    t | }zt|}W n
 ty   Y dS w |D ]	}|dfV  |}q|dfV  dS )z[Generate elements from an iterable,
    and a boolean indicating if it is the last element.NFT)iterr\   r]   rd   iteratoritemZ	next_itemr0   r0   r1   generate_with_last_element_mark   s   
rk   AsyncIterable[T]AsyncIterator[Tuple[T, bool]]c                 C sb   |   }z	| I dH }W n
 ty   Y dS w |2 z3 dH W }|dfV  |}q6 |dfV  dS )zaGenerate elements from an async iterable,
    and a boolean indicating if it is the last element.NFT)rT   r[   rY   rh   r0   r0   r1    agenerate_with_last_element_mark   s   
rn   c                      s>  e Zd ZU dZedHddZdZded< ed	d
dZ	ded< 	 ee
dZded< dZded< 	 edddZded< 	 dZded< 	 dZded< 	 edIddZedJd!d"ZedKd#d$ZedL fd&d'Z		dMdNd0d1Z		dMdOd3d4Z		dMdPd7d8Z		dMdQd:d;ZdRd<d=Ze	>dSdTdAdBZedUdFdGZ  ZS )Vr    uP	  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

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

    r!   Dict[str, str]c                 C  s   ddiS )Ndashscope_api_keyDASHSCOPE_API_KEYr0   rS   r0   r0   r1   
lc_secrets   s   zTongyi.lc_secretsNr   rB   z	qwen-plusmodel)defaultaliasstr
model_name)default_factoryDict[str, Any]model_kwargsg?floattop_papi_keyzOptional[str]rp   Fbool	streaming
   intr,   c                 C  s   dS )zReturn type of llm.Ztongyir0   rS   r0   r0   r1   	_llm_type  s   zTongyi._llm_typevaluesr   c                 C  s`   t |ddgd|d< zddl}W n ty   tdw z|j|d< W |S  ty/   tdw )	z?Validate that api key and python package exists in environment.rp   r}   rq   r   NzZCould not import dashscope python package. Please install it with `pip install dashscope`.rB   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:   )clsr   r   r0   r0   r1   validate_environment	  s$   
zTongyi.validate_environmentc                 C  s    | j | j| jd}i || jS )z7Get the default parameters for calling Tongyi Qwen API.)rs   r|   r}   )rw   r|   rp   rz   )rP   Znormal_paramsr0   r0   r1   _default_params!  s
   zTongyi._default_paramsMapping[str, Any]c                   s   d| j it jS )Nrw   )rw   super_identifying_paramsrS   	__class__r0   r1   r   ,  s   zTongyi._identifying_paramsprompts	List[str]r)   Optional[List[str]]run_manager"Optional[CallbackManagerForLLMRun]r<   r   c              	   K  s   g }| j r<t|dkrtdd }| j|d ||fi |D ]}|d u r'|}q||7 }q|d us2J || |g n'| jdd|i|}|D ]}	t| fd|	i|}
|tdi | 	|
g qHt
|d| jidS )	Nr#   ,Cannot stream results with multiple prompts.r   r)   promptrw   generationsZ
llm_outputr0   )r   lenr:   _streamappend_chunk_to_generation_invocation_paramsrI   r   _generation_from_qwen_respr   rw   rP   r   r)   r   r<   r   Z
generationrb   paramsr   
completionr0   r0   r1   	_generate0  s,   
zTongyi._generate'Optional[AsyncCallbackManagerForLLMRun]c              
     s   g }| j rBt|dkrtdd }| j|d ||fi |2 z3 d H W }|d u r,|}q||7 }q6 |d us8J || |g n4| jdd|i|}|D ]'}	t 	d t
jtfi | |	d|I d H }
|tdi | |
g qNt|d| jidS )	Nr#   r   r   r)   )r   r   rw   r   r0   )r   r   r:   _astreamr   r   r   rU   rV   rW   	functoolspartialrI   r   r   r   rw   r   r0   r0   r1   
_agenerateQ  s>   &

zTongyi._agenerater   Iterator[GenerationChunk]c           	      k  sr    | j d|dd|}tt| fd|i|D ]\}}tdi | ||}|r3|j|j|| jd |V  qd S NT)r)   streamr   )rb   verboser0   )r   rk   rL   r   r   on_llm_new_tokentextr   	rP   r   r)   r   r<   r   Zstream_respis_last_chunkrb   r0   r0   r1   r   w  s(   
zTongyi._streamAsyncIterator[GenerationChunk]c           	      K s   | j d|dd|}tt| fd|i|2 z%3 d H W \}}tdi | ||}|r:|j|j|| jdI d H  |V  q6 d S r   )r   rn   rc   r   r   r   r   r   r   r0   r0   r1   r     s(   
zTongyi._astreamc                 K  s4   i | j |}|d ur||d< |drd|d< |S )Nr)   r   TZincremental_output)r   get)rP   r)   r<   r   r0   r0   r1   r     s   
zTongyi._invocation_paramsTr3   r   c                 C  sH   |rt | d d t | d d | d t | d ddS t | d d dS )	Noutputr   finish_reasonr6   usage)r   r6   Ztoken_usager   generation_info)r   )dict)r3   r   r0   r0   r1   r     s   


	z!Tongyi._generation_from_qwen_resprb   r   r   c                 C  s   t | j| jdS )Nr   )r   r   r   )rb   r0   r0   r1   r     s   zTongyi._chunk_to_generation)r!   ro   )r!   rv   )r   r   r!   r   )r!   ry   )r!   r   )NN)
r   r   r)   r   r   r   r<   r   r!   r   )
r   r   r)   r   r   r   r<   r   r!   r   )
r   rv   r)   r   r   r   r<   r   r!   r   )
r   rv   r)   r   r   r   r<   r   r!   r   )r)   r   r<   r   r!   ry   )T)r3   r   r   r~   r!   ry   )rb   r   r!   r   )r^   r_   r`   __doc__propertyrr   rB   __annotations__r   rw   r   rz   r|   rp   r   r,   r   r   r   r   r   r   r   r   r   r   staticmethodr   r   __classcell__r0   r0   r   r1   r       sT   
 L
$)
)r   r    r!   r"   )r3   r   r!   r   )r   r    r<   r   r!   r   )rd   re   r!   rf   )rd   rl   r!   rm   )4
__future__r   rU   r   r.   typingr   r   r   r   r   r   r	   r
   r   r   r   r   Zlangchain_core.callbacksr   r   Z#langchain_core.language_models.llmsr   Zlangchain_core.outputsr   r   r   Zlangchain_core.utilsr   r   Zpydanticr   Zrequests.exceptionsr   tenacityr   r   r   r   r   	getLoggerr^   r-   r   r2   r;   rI   rL   rc   rk   rn   r    r0   r0   r0   r1   <module>   s,    8






 
