
    dh                    "   S SK Jr  S SKrS SKrS SKrS SKrS SKJ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  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(J)r)  S S	K*J+r+  S S
K,J-r-J.r.J/r/J0r0  S SK1J2r2J3r3J4r4  S SK5J6r6J7r7J8r8  S SK9J:r:  S SK;J<r<J=r=J>r>  S SK?J@r@  S SKAJBrB  S SKCJDrDJErEJFrFJGrG  S SKHJIrI  S SKJJKrKJLrLJMrMJNrNJOrO  S SKPJQrQJRrRJSrS  \R                  " \U5      rV S     SS jjrWSS jrXSS jrYSS jrZ " S S\5      r[g)     )annotationsN)
itemgetter)AnyAsyncIteratorCallableDictIteratorListMappingOptionalSequenceTypeUnioncast)AsyncCallbackManagerForLLMRunCallbackManagerForLLMRun)LanguageModelInput)BaseChatModel)	AIMessageAIMessageChunkBaseMessageBaseMessageChunkChatMessageChatMessageChunkFunctionMessageHumanMessageHumanMessageChunkSystemMessageSystemMessageChunkToolMessageToolMessageChunk)OutputParserLike)JsonOutputKeyToolsParserPydanticToolsParsermake_invalid_tool_callparse_tool_call)ChatGenerationChatGenerationChunk
ChatResult)RunnableRunnableMapRunnablePassthrough)BaseTool)convert_to_secret_strget_from_dict_or_envpre_init)convert_to_openai_tool)is_basemodel_subclass)	BaseModel
ConfigDictField	SecretStr)	HTTPError)before_sleep_logretryretry_if_exception_typestop_after_attemptwait_exponential) agenerate_with_last_element_markcheck_responsegenerate_with_last_element_markc           
     \   U S   nU S   nUS:X  a  U(       a	  [        US9$ [        US9$ US:X  Ga  / n/ nSU ;   a  SU S   0n[        U S   5       H}  u  pxU(       aL   UR                  US   R	                  S5      US   R	                  S	5      UR	                  S
5      US.5        MX   [        USS9n	U	(       a  UR                  U	5        M}  M     O6SU ;   a  SU S   0nO(SU ;   a   [        U S   [        5      (       a  SU S   0nO0 nU(       a  [        UUUU R	                  S
5      S9$ [        UUUUS9$ US:X  a  U(       a	  [        US9$ [        US9$ US:X  ak  0 nSU ;   a  U S   US'   U(       a*  [!        U R	                  SS5      U R	                  S5      US9$ [#        U R	                  SS5      U R	                  S5      US9$ U(       a	  [%        X#S9$ ['        X#S9$ ! [
         a     GM  f = f! [         a0  n
UR                  [        U[        U
5      5      5         Sn
A
GM  Sn
A
ff = f)zConvert a dict to a message.rolecontentuser)rB   	assistant
tool_callsfunctionname	argumentsid)rG   argsrI   indexT)	return_idNreasoning_contentpartial)rB   additional_kwargstool_call_chunksrI   )rB   rO   rE   invalid_tool_callssystemtool tool_call_id)rB   rU   rO   rA   rB   )r   r   	enumerateappendgetKeyErrorr&   	Exceptionr%   str
isinstanceboolr   r   r   r   r!   r    r   r   )_dictis_chunkrA   rB   rE   rQ   rO   rK   valueparsed_tooles              ^/var/www/html/shao/venv/lib/python3.13/site-packages/langchain_community/chat_models/tongyi.pyconvert_dict_to_messagere   U   s    =DIGv~  g.	
 g.	

 
	
5 !-u\/B C )%*= >"))(-j(9(=(=f(E(-j(9(=(=k(J&+iio */	Y&5et&L&&--k: '% !?, !E)!4e<O6P Q%JuY/?$F$F!*E),< = "  "3!+99T?		
 "3%#5		
 
	  w/	
 w/	

 
U?(-ff%  		)R0"YY~6"3	
 		)R0"YY~6"3	
   $8	
 $8	
o $  % Y*112HPSTUPV2WXXYs+   A	G)"G1
G.-G.1
H+;$H&&H+c           
     2   [        U [        5      (       d  U $ S/n[        U [        5      (       a  UR                  S5        U R                  R
                  S   " S0 U R                  R                  5        VVs0 sH  u  p#X!;  d  M  X#_M     snnD6$ s  snnf )ziConvert a message chunk to a message.

Args:
    chunk: Message chunk to convert.

Returns:
    Message.
typerP       )r]   r   r   rX   	__class____mro____dict__items)message_chunkignore_keyskvs       rd    convert_message_chunk_to_messagerr      s     m%566(K-00-.""**1- )2288:
S:DAa>R414:
S 
Ss   9
BBc                
   [        U [        5      (       a  U R                  U R                  S.nU$ [        U [        5      (       a  SU R                  S.nU$ [        U [
        5      (       aU  SU R                  S.nSU R                  ;   a  U R                  S   US'   SU R                  ;   a  U R                  S   US'   U$ [        U [        5      (       a  SU R                  S.nU$ [        U [        5      (       aI  SU R                  U R                  U R                  =(       d    U R                  R                  S5      S	.nU$ [        U [        5      (       a  SS
U R                  U R                  S	.nU$ [        SU  35      e)zConvert a message to a dict.rV   rC   rD   rE   rN   rR   rS   rG   )rA   rU   rB   rG   rT   zGot unknown type )r]   r   rA   rB   r   r   rO   r   r    rU   rG   rY   r   	TypeError)messagemessage_dicts     rd   convert_message_to_dictrw      su    ';'' 'I8 7 
G\	*	* &7??C4 3 
GY	'	' +H7444)0)B)B<)PL&111&-&?&?	&JL#& % 
G]	+	+ (W__E" ! 
G[	)	)#00LLIG$=$=$A$A&$I	
  
G_	-	-LL	
  +G9566    
ChatTongyic           
         SnSn[        S[        U R                  5      [        SXS9[	        [
        5      [        [        [        R                  5      S9$ )Nrh      T)
multiplierminmax)reraisestopwaitr9   before_sleep)
r9   r;   max_retriesr<   r:   r7   r8   loggerloggingWARNING)llmmin_secondsmax_secondss      rd   _create_retry_decoratorr      sJ    KK 0M&y1%fgoo> rx   c                  Z  ^  \ rS rSr% Sr\S1S 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9r\S2S j5       r\S3S j5       r\S4S  j5       rS5S! jrS5S" jrS6S# jrS5S$ jr  S7         S8S% jjr  S7         S9S& jjr  S7         S:S' jjr  S7         S;S( jjr        S<S) jrS=S* jr \! S>       S?S+ jj5       r"\!S@S, j5       r#      SAU 4S- jjr$SS..       SBS/ jjr%S0r&U =r'$ )Cry      u9  Alibaba Tongyi Qwen chat 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 Qianfan 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.chat_models import ChatTongyi

        tongyi_chat = ChatTongyi(
            model="qwen-max",
            # top_p="...",
            # api_key="...",
            # other params...
        )

Invoke:
    .. code-block:: python

        messages = [
            ("system", "你是一名专业的翻译家，可以将用户的中文翻译为英文。"),
            ("human", "我喜欢编程。"),
        ]
        tongyi_chat.invoke(messages)

    .. code-block:: python

        AIMessage(
            content='I enjoy programming.',
            response_metadata={
                'model_name': 'qwen-max',
                'finish_reason': 'stop',
                'request_id': '0bd14853-4abc-9593-8642-8dbb915bd4df',
                'token_usage': {
                    'input_tokens': 30,
                    'output_tokens': 4,
                    'total_tokens': 34
                }
            },
            id='run-533b3688-d12b-40c6-a2f7-52f291f8fa0a-0'
        )

Stream:
    .. code-block:: python

        for chunk in tongyi_chat.stream(messages):
            print(chunk)

    .. code-block:: python

        content='I' id='run-8fbcce63-42fc-4208-9399-da46ac40c967'
        content=' enjoy' id='run-8fbcce63-42fc-4208-9399-da46ac40c967'
        content=' programming' id='run-8fbcce63-42fc-4208-9399-da46ac40c967'
        content='.' response_metadata={'finish_reason': 'stop', 'request_id': '67aec2b5-72bf-96a4-ae29-5bfebd2e7305', 'token_usage': {'input_tokens': 30, 'output_tokens': 4, 'total_tokens': 34}} id='run-8fbcce63-42fc-4208-9399-da46ac40c967'

Async:
    .. code-block:: python

        await tongyi_chat.ainvoke(messages)

        # stream:
        # async for chunk in tongyi_chat.astream(messages):
        #    print(chunk)

        # batch:
        # await tongyi_chat.abatch([messages])

    .. code-block:: python

        AIMessage(
            content='I enjoy programming.',
            response_metadata={
                'model_name': 'qwen-max',
                'finish_reason': 'stop',
                'request_id': 'a55a2d6c-a876-9789-9dd9-7b52bf8adde0',
                'token_usage': {
                    'input_tokens': 30,
                    'output_tokens': 4,
                    'total_tokens': 34
                }
            },
            id='run-3bffa3ec-e8d9-4043-b57d-348e047d64de-0'
        )

Tool calling:
    .. code-block:: python

        from pydantic import BaseModel, Field


        class GetWeather(BaseModel):
            '''Get the current weather in a given location'''

            location: str = Field(
                ..., description="The city and state, e.g. San Francisco, CA"
            )


        class GetPopulation(BaseModel):
            '''Get the current population in a given location'''

            location: str = Field(
                ..., description="The city and state, e.g. San Francisco, CA"
            )

        chat_with_tools = tongyi_chat.bind_tools([GetWeather, GetPopulation])
        ai_msg = chat_with_tools.invoke(
            "Which city is hotter today and which is bigger: LA or NY?"
        )
        ai_msg.tool_calls

    .. code-block:: python
        [
            {
                'name': 'GetWeather',
                'args': {'location': 'Los Angeles, CA'},
                'id': ''
            }
        ]

Structured output:
    .. code-block:: python

        from typing import Optional

        from pydantic import BaseModel, Field


        class Joke(BaseModel):
            '''Joke to tell user.'''

            setup: str = Field(description="The setup of the joke")
            punchline: str = Field(description="The punchline to the joke")
            rating: Optional[int] = Field(description="How funny the joke is, from 1 to 10")


        structured_chat = tongyi_chat.with_structured_output(Joke)
        structured_chat.invoke("Tell me a joke about cats")

    .. code-block:: python

        Joke(
            setup='Why did the cat join the band?',
            punchline='Because it wanted to be a solo purr-sonality!',
            rating=None
        )

Response metadata
    .. code-block:: python

        ai_msg = tongyi_chat.invoke(messages)
        ai_msg.response_metadata

    .. code-block:: python

        {
            'model_name': 'qwen-max',
            'finish_reason': 'stop',
            'request_id': '32a13e4c-370e-99cb-8f9b-4c999d98c57d',
            'token_usage': {
                'input_tokens': 30,
                'output_tokens': 4,
                'total_tokens': 34
            }
        }

c                
    SS0$ )Ndashscope_api_keyDASHSCOPE_API_KEYri   selfs    rd   
lc_secretsChatTongyi.lc_secrets  s    #%899rx   Nr   clientz
qwen-turbomodel)defaultaliasr\   
model_name)default_factoryDict[str, Any]model_kwargsg?floattop_papi_key)r   zOptional[SecretStr]r   Fr^   	streaming
   intr   T)populate_by_namec                    g)zReturn type of llm.tongyiri   r   s    rd   	_llm_typeChatTongyi._llm_type  s     rx   c                H   [        [        USS5      5      US'    SSKn/ SQnUS   U;   d	  SUS   ;   a   UR                  US	'   U$  UR                  US	'   U$ ! [         a    [        S5      ef = f! [
         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   NzdCould not import dashscope python package. Please install it with `pip install dashscope --upgrade`.)zqwen-audio-turbozqwen-audio-turbo-latestzqwen-vl-pluszqwen-vl-plus-latestzqwen-vl-maxzqwen-vl-max-latestr   vlr   z`dashscope` has no `MultiModalConversation` attribute, this is likely due to an old version of the dashscope package. Try upgrading it with `pip install --upgrade dashscope`.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.   r/   	dashscopeImportErrorMultiModalConversationAttributeError
ValueError
Generation)clsvaluesr   dashscope_multimodal_modelss       rd   validate_environmentChatTongyi.validate_environment  s     '< )<>QR'
"#	'
# < $??vl++#,#C#Cx   #,#7#7x  E  	L 	& "  K  "  > s"   A A2 B A/2BB!c                    U R                   U R                  [        [        U R                  5      R                  5       SS.U R                  E$ )z7Get the default parameters for calling Tongyi Qwen API.ru   )r   r   r   result_format)r   r   r   r6   r   get_secret_valuer   r   s    rd   _default_paramsChatTongyi._default_params  sH     __ZZIt'='=>OOQ&	

 
 	
rx   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      $ )Nri   )r   callr>   )_kwargsrespr   s     rd   _completion_with_retry@ChatTongyi.completion_with_retry.<locals>._completion_with_retry  s%    ;;##.g.D!$''rx   r   r   returnr   ri   r   )r   kwargsretry_decoratorr   s   `   rd   completion_with_retry ChatTongyi.completion_with_retry  s/    1$7		( 
	( &///rx   c                D   ^  [        T 5      nUSU 4S jj5       nU" S0 UD6$ )r   c               ;    >#    T	R                   R                  " S0 U D6nS nU GH  nU R                  S5      (       a  U R                  SS5      (       d  [        R                  " [        R
                  " U5      5      nUR                  S5      (       an  US   R                  S5      (       aU  US   S   S   nUS   n[        UR                  S5      [        5      (       a  S	R                  S
 US    5       5      nXvS'   UnUc  UnOT	R                  X25      nUn[        U5      v   GM  [        U5      v   GM     g 7f)Nstreamincremental_outputFoutputchoicesr   ru   rB   rT   c              3  r   #    U H.  n[        U[        5      (       d  M  UR                  S S5      v   M0     g7f)textrT   N)r]   dictrY   ).0items     rd   	<genexpr>aChatTongyi.stream_completion_with_retry.<locals>._stream_completion_with_retry.<locals>.<genexpr>3  s1      3,>D#-dD#9 !5 4 4,>s   77ri   )r   r   rY   jsonloadsdumpsr]   listjoinsubtract_client_responser>   )
r   	responses	prev_respr   	resp_copychoiceru   content_text
delta_respr   s
            rd   _stream_completion_with_retryNChatTongyi.stream_completion_with_retry.<locals>._stream_completion_with_retry"  s(    ((373II! ;;x(((%2 2 !%

4::d+; <I }}X..9X3F3J3J93U3U!*8!4Y!?!B"("3%gkk)&<dCC+-77 3,3I,>3 ,L
 2>I.( (%)
%)%B%B4%S
 $I(44(..5 "s   D<D?r   ri   r   )r   r   r   r   s   `   rd   stream_completion_with_retry'ChatTongyi.stream_completion_with_retry  s0    1$7		/ 
	/@ -6v66rx   c                V   [         R                  " [         R                  " U5      5      nUS   S   S   nUS   n[         R                  " [         R                  " U5      5      nUS   S   S   nUS   nUS   R                  US   S5      US'   UR	                  S5      (       a  [        US   5       Hq  u  pU
S   nUR	                  S5      (       d  M"  US   U	   S   nS	U;   a  US	   R                  US	   S5      US	'   S
U;   d  MV  US
   R                  US
   S5      US
'   Ms     U$ )zfSubtract prev response from curr response.

Useful when streaming without `incremental_output = True`
r   r   r   ru   rB   rT   rE   rF   rG   rH   )r   r   r   replacerY   rW   )r   r   r   r   r   ru   prev_resp_copyprev_choiceprev_messagerK   	tool_callrF   prev_functions                rd   r   #ChatTongyi.subtract_client_responseE  sH    JJtzz$/0	8$Y/2#DJJy$9:$X.y9!<"9-$Y/77Y8OQST	;;|$$$-gl.C$D $Z0##L11$0$>u$Ej$QM)+3F+;+C+C)&12,( #h.080E0M0M)+61- %E rx   c               r   #     " S S5      nU" U R                   " S0 UD6S9  Sh  vN nU7v   M   N
 g7f)zuBecause 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)EChatTongyi.astream_completion_with_retry.<locals>._AioTongyiGeneratorik  c                    Xl         g N	generator)r   r   s     rd   __init__NChatTongyi.astream_completion_with_retry.<locals>._AioTongyiGenerator.__init__l  s    !*rx   c                    U $ r   ri   r   s    rd   	__aiter__OChatTongyi.astream_completion_with_retry.<locals>._AioTongyiGenerator.__aiter__o  s    rx   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   ra   s     rd   	__anext__OChatTongyi.astream_completion_with_retry.<locals>._AioTongyiGenerator.__anext__r  sD     %668HH$//  $ L,,s   3AAAc                N     [        U R                  5      $ ! [         a     g f = fr   )nextr   StopIterationr   s    rd   r   PChatTongyi.astream_completion_with_retry.<locals>._AioTongyiGenerator._safe_next{  s(     //$   s    
$$r   N)r   r   )r   zAsyncIterator[Any])r   r   )	__name__
__module____qualname____firstlineno__r   r   r   r   __static_attributes__ri   rx   rd   _AioTongyiGeneratorr   k  s    +- rx   r
  r   Nri   )r   )r   r   r
  chunks       rd   astream_completion_with_retry(ChatTongyi.astream_completion_with_retryg  sB     	  	 , /77A&A
 	% K	 
s   !7535757c           	        / nU R                   (       aO  S nU R                  " U4X#S.UD6 H  nUc  UnM
  Xg-  nM     Uc   eUR                  U R                  U5      5        OOU R                  " SXS.UD6nU R
                  " S0 UD6n	UR                  [        S0 U R                  U	5      D65        [        USU R                  0S9$ N)r   run_manager)messagesr   r   )generations
llm_outputri   )
r   _streamrX   _chunk_to_generation_invocation_paramsr   r'   _chat_generation_from_qwen_respr)   r   )
r   r  r   r  r   r  generation_chunkr  paramsr   s
             rd   	_generateChatTongyi._generate  s     >>>B#@F $+',$$-$ $///t889IJK%)%<%< &!&06&F --77DL!E!Ed!KL #doo
 	
rx   c           	       #    / nU R                   (       a-  S nU R                  " U4X#S.UD6  S h  vN nUc  UnM  Xg-  nM  U R                  " SXS.UD6n[
        R                  " 5       R                  S [        R                  " U R                  40 UD65      I S h  vN n	UR                  [        S0 U R                  U	5      D65        [        USU R                  0S9$  N
 Uc   eUR                  U R                  U5      5        N? Nl7fr  )r   _astreamrX   r  r  r   r   r   	functoolsrN   r   r'   r  r)   r   )
r   r  r   r  r   r  
generationr  r  r   s
             rd   
_agenerateChatTongyi._agenerate  s-     >>8<J#}} # @F  (e %!&J'J &*%<%< &!&06&F !113CC!!$"<"<GG D L!E!Ed!KL #doo
 	
)(   )))t88DE
s3   +DC$C"C$A)DDAD"C$$(Dc              +  |  #    U R                   " SXSS.UD6n[        U R                  " S0 UD65       H  u  pgUS   S   S   nUS   n	US   S:X  a'  U	S	   S
:X  a  U	R                  SS
5      S
:X  a  SU	;  a  ME  [	        S0 U R                  USUS9D6n
U(       a  UR                  U
R                  U
S9  U
v   M     g 7f)NTr  r   r   r   r   r   ru   finish_reasonnullrB   rT   rM   rE   r`   is_last_chunkr  ri   )r  r?   r   rY   r(   r  on_llm_new_tokenr   )r   r  r   r  r   r  stream_respr'  r   ru   r  s              rd   r  ChatTongyi._stream  s      "&!8!8 "
"
9?"
 +J--77+
&K !*95a8FY'G'61I&",KK 3R8B> /' 66$m 7 E
 ,,UZZu,EK)+
s   B:B<c                  #    U R                   " SXSS.UD6n[        U R                  " S0 UD65        S h  vN u  pg[        S0 U R	                  USUS9D6nU(       a"  UR                  UR                  US9I S h  vN   U7v   MU   NP N
 g 7f)NTr#  r&  r(  ri   )r  r=   r  r(   r  r)  r   )	r   r  r   r  r   r  r*  r'  r  s	            rd   r  ChatTongyi._astream  s      "&!8!8 "
"
9?"
 1Q..881
 
	,+ ( 66$m 7 E
 !225::U2KKKK
	 L1
s8   1BBBBAB<B
=BB
BBc                   0 U R                   EUEnUb  X$S'   UR                  S5      (       a  UR                  S5      (       d  SUS'   U Vs/ sH  n[        U5      PM     nn[        U5       VVs/ sH  u  puUS   S:X  d  M  UPM     nnn[	        U5      S:X  a  US	   S	:w  a  [        S
5      eXdS'   U$ s  snf s  snnf )Nr   r   toolsTr   rA   rR   rh   r   z-System message can only be the first message.r  )r   rY   rw   rW   lenr   )	r   r  r   r   r  mmessage_dictsisystem_message_indicess	            rd   r  ChatTongyi._invocation_params  s     4D((3F3!6N ::h

7(;(;+/F'(=EFX03XF $M2"
2$!ai86KA2 	 "
 %&!+0Fq0IQ0NLMM*z G"
s   B51B:B:c                    US   c  0 $ US   $ )Nr   ri   )r   llm_outputss     rd   _combine_llm_outputsChatTongyi._combine_llm_outputs  s    q>!I1~rx   c                    U S   S   S   n[        US   US9nU(       a%  [        U[        US   U S   [        U S   5      S	9S
9$ [        US9$ )Nr   r   r   ru   )r`   r$  
request_idusage)r$  r;  token_usageru   generation_info)ru   )re   r   )r   r`   r'  r   ru   s        rd   r  *ChatTongyi._chat_generation_from_qwen_resp!  sl     h	*1-)&*;hO $"("9#L1 $T'] 3!  ((rx   c                P    [        [        U R                  5      U R                  S9$ )Nr>  )r'   rr   ru   r?  r(  s    rd   r  ChatTongyi._chunk_to_generation:  s$    4U]]C!11
 	
rx   c                f   > U Vs/ sH  n[        U5      PM     nn[        TU ]  " SSU0UD6$ s  snf )a  Bind tool-like objects to this chat model.

Args:
    tools: A list of tool definitions to bind to this chat model.
        Can be  a dictionary, pydantic model, callable, or BaseTool. Pydantic
        models, callables, and BaseTools will be automatically converted to
        their schema dictionary representation.
    **kwargs: Any additional parameters to pass to the
        :class:`~langchain.runnable.Runnable` constructor.
r/  ri   )r1   superbind)r   r/  r   rS   formatted_toolsrj   s        rd   
bind_toolsChatTongyi.bind_toolsA  s>      EJJED1$7EJw|</<V<< Ks   .)include_rawc                  U(       a  [        SU 35      e[        U[        5      =(       a    [        U5      nU R	                  U/5      nU(       a  [        U/SS9nO[        U5      S   S   n[        USS9nU(       aT  [        R                  " [        S5      U-  S S	9n[        R                  " S
 S9n	UR                  U	/SS9n
[        US9U
-  $ XV-  $ )a  Model wrapper that returns outputs formatted to match the given schema.

Args:
    schema: The output schema as a dict or a Pydantic class. If a Pydantic class
        then the model output will be an object of that class. If a dict then
        the model output will be a dict. With a Pydantic class the returned
        attributes will be validated, whereas with a dict they will not be. If
        `method` is "function_calling" and `schema` is a dict, then the dict
        must match the OpenAI function-calling spec.
    include_raw: If False then only the parsed structured output is returned. If
        an error occurs during model output parsing it will be raised. If True
        then both the raw model response (a BaseMessage) and the parsed model
        response will be returned. If an error occurs during output parsing it
        will be caught and returned as well. The final output is always a dict
        with keys "raw", "parsed", and "parsing_error".

Returns:
    A Runnable that takes any ChatModel input and returns as output:

        If include_raw is True then a dict with keys:
            raw: BaseMessage
            parsed: Optional[_DictOrPydantic]
            parsing_error: Optional[BaseException]

        If include_raw is False then just _DictOrPydantic is returned,
        where _DictOrPydantic depends on the schema:

        If schema is a Pydantic class then _DictOrPydantic is the Pydantic
            class.

        If schema is a dict then _DictOrPydantic is a dict.

zReceived unsupported arguments T)r/  first_tool_onlyrF   rG   )key_namerK  rawc                    g r   ri   _s    rd   <lambda>3ChatTongyi.with_structured_output.<locals>.<lambda>  s    RVrx   )parsedparsing_errorc                    g r   ri   rO  s    rd   rQ  rR    s    drx   )rS  rT  )exception_key)rM  )r   r]   rg   r2   rG  r$   r1   r#   r,   assignr   with_fallbacksr+   )r   schemarI  r   is_pydantic_schemar   output_parserrL  parser_assignparser_noneparser_with_fallbacks              rd   with_structured_output!ChatTongyi.with_structured_outputT  s    P >vhGHH'5W:OPV:Woovh'.Ah $/M
 .f5jA&IH4!4M /66!%(=8M .44NKK#0#?#?_ $@ $  3'*>>>&&rx   ri   )r   zDict[str, str])r   r\   )r   r   r   r   )r   r   )r   r   r   r   )r   r   r   r   r   r   )NN)
r  List[BaseMessage]r   Optional[List[str]]r  "Optional[CallbackManagerForLLMRun]r   r   r   r)   )
r  ra  r   rb  r  'Optional[AsyncCallbackManagerForLLMRun]r   r   r   r)   )
r  ra  r   rb  r  rc  r   r   r   zIterator[ChatGenerationChunk])
r  ra  r   rb  r  rd  r   r   r   z"AsyncIterator[ChatGenerationChunk])r  ra  r   r   r   r   r   r   )r7  zList[Optional[dict]]r   r   )FT)r   r   r`   r^   r'  r^   r   r   )r  r(   r   r'   )r/  zDSequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]]r   r   r   z)Runnable[LanguageModelInput, BaseMessage])rY  zUnion[Dict, Type[BaseModel]]rI  r^   r   r   r   z4Runnable[LanguageModelInput, Union[Dict, BaseModel]])(r  r  r  r  __doc__propertyr   r   __annotations__r5   r   r   r   r   r   r   r   r4   model_configr   r0   r   r   r   r   r   r  r  r   r  r  r  r8  staticmethodr  r  rG  r_  r	  __classcell__)rj   s   @rd   ry   ry      s   || : : FCL@J@ $)#>L.>E5D-24y-I*I5It/K<L   ) )V 
 
	0%7N DD %):>	 
# 
 " 
 8	 

  
 
 
J %)?C	#
##
 "#
 =	#

 #
 
#
P %):>	# " 8	
  
'H %)?C	# " =	
  
,,)14@C	0
 AE))!):>)	) )0 
 
=S= = 
3	=. "	A',A' 	A'
 A' 
>A' A'rx   )F)r_   zMapping[str, Any]r`   r^   r   z$Union[BaseMessage, BaseMessageChunk])rn   r   r   r   )ru   r   r   r   )r   ry   r   zCallable[[Any], Any])\
__future__r   r   r  r   r   operatorr   typingr   r   r   r   r	   r
   r   r   r   r   r   r   langchain_core.callbacksr   r   langchain_core.language_modelsr   *langchain_core.language_models.chat_modelsr   langchain_core.messagesr   r   r   r   r   r   r   r   r   r   r   r    r!   "langchain_core.output_parsers.baser"   *langchain_core.output_parsers.openai_toolsr#   r$   r%   r&   langchain_core.outputsr'   r(   r)   langchain_core.runnablesr*   r+   r,   langchain_core.toolsr-   langchain_core.utilsr.   r/   r0   %langchain_core.utils.function_callingr1   langchain_core.utils.pydanticr2   pydanticr3   r4   r5   r6   requests.exceptionsr7   tenacityr8   r9   r:   r;   r<   langchain_community.llms.tongyir=   r>   r?   	getLoggerr  r   re   rr   rw   r   ry   ri   rx   rd   <module>r     s    "         > D    @  
 P O ) V V H ?  *   
		8	$ 05Z
Z
(,Z
)Z
z(!H]
' ]
'rx   