
    Ng{                       d dl mZ d dlZd dlZd dlZd dlZd dlm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 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(m)Z) d d	l*m+Z+ d d
l,m-Z-m.Z.m/Z/m0Z0 d dl1m2Z2m3Z3m4Z4 d dl5m6Z6m7Z7m8Z8 d dl9m:Z: d dl;m<Z<m=Z=m>Z> d dl?m@Z@ d dlAmBZB d dlCmDZDmEZEmFZFmGZG d dlHmIZI d dlJmKZKmLZLmMZMmNZNmOZO d dlPmQZQmRZRmSZS  ejT        eU          ZV	 d)d*dZWd+d ZXd,d#ZYd-d'ZZ G d( d%e          Z[dS ).    )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_markF_dictMapping[str, Any]is_chunkboolreturn$Union[BaseMessage, BaseMessageChunk]c           
        | d         }| d         }|dk    r"|rt          |          nt          |          S |dk    rOg }g }d| v r	d| d         i}t          | d                   D ]\  }}|rq	 |                    |d                             d          |d                             d	          |                    d
          |d           h# t
          $ r Y tw xY w	 t          |d          }	|	r|                    |	           # t          $ r:}
|                    t          |t          |
                               Y d}
~
d}
~
ww xY wni }|r&t          ||||                     d
                    nt          ||||          S |dk    r"|rt          |          nt          |          S |dk    ri }d| v r| d         |d<   |r9t          |                     dd          |                     d          |          n8t          |                     dd          |                     d          |          S |rt!          ||          nt#          ||          S )zConvert a dict to a message.rolecontentuser)rI   	assistant
tool_callsfunctionname	argumentsid)rN   argsrP   indexT)	return_idN)rI   additional_kwargstool_call_chunksrP   )rI   rT   rL   invalid_tool_callssystemtool tool_call_id)rI   rZ   rT   rH   rI   )r   r   	enumerateappendgetKeyErrorr&   	Exceptionr%   strr   r   r   r   r!   r    r   r   )rA   rC   rH   rI   rL   rV   rT   rR   valueparsed_tooles              b/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/chat_models/tongyi.pyconvert_dict_to_messagerf   U   sG    =DIGv~~ /g....g...	

 
		
5  !-u\/B C )%*= > > Y Yu Y"))(-j(9(=(=f(E(E(-j(9(=(=k(J(J&+iioo */ 	 	 	 	 $   Y&5et&L&L&L& ;&--k:::$ Y Y Y*112HPSTUPVPV2W2WXXXXXXXXY)Y. !# N"3!+99T??	    "3%#5	  	
 
		 0w////w///	

 
U??(-ff% 
		)R00"YY~66"3    		)R00"YY~66"3  	
  9$8888$888	
s+   0AC
CC!(D


E0E		Emessage_chunkr   r   c                   t          | t                    s| S dgt          | t                    r                    d            | j        j        d         di fd| j                                        D             S )z}Convert a message chunk to a message.

    Args:
        chunk: Message chunk to convert.

    Returns:
        Message.
    typerU      c                $    i | ]\  }}|v	||S  rl   ).0kvignore_keyss      re   
<dictcomp>z4convert_message_chunk_to_message.<locals>.<dictcomp>   s)    
S
S
SDAqa{>R>R1a>R>R>R    rl   )
isinstancer   r   r]   	__class____mro____dict__items)rg   rp   s    @re    convert_message_chunk_to_messagerx      s     m%566 (K-00 /-...-="*1-  
S
S
S
SM288::
S
S
S  rr   messagedictc                @   t          | t                    r| j        | j        d}nt          | t                    rd| j        d}nt          | t
                    r$d| j        d}d| j        v r| j        d         |d<   nt          | t                    rd| j        d}nt          | t                    r1d| j	        | j        | j
        p| j                            d          d}n9t          | t                    rdd	| j        | j
        d}nt          d
|            |S )zConvert a message to a dict.r[   rJ   rK   rL   rW   rX   rN   )rH   rZ   rI   rN   rY   zGot unknown type )rs   r   rH   rI   r   r   rT   r   r    rZ   rN   r^   r   	TypeError)ry   message_dicts     re   convert_message_to_dictr~      sK    ';'' 7 'II	G\	*	* 7 &7?CC	GY	'	' 7 +HH7444)0)B<)PL&	G]	+	+ 7 (W_EE	G[	)	) 7#0LIG$=$A$A&$I$I	
 
 
G_	-	- 7L	
 
 5G55666rr   llm
ChatTongyiCallable[[Any], Any]c           
         d}d}t          dt          | j                  t          d||          t	          t
                    t          t          t          j	                            S )Nrj      T)
multiplierminmax)reraisestopwaitr:   before_sleep)
r:   r<   max_retriesr=   r;   r8   r9   loggerloggingWARNING)r   min_secondsmax_secondss      re   _create_retry_decoratorr      sa    KK 00MMM&y11%fgo>>   rr   c                      e Zd ZU dZedOd            ZdZded<    edd	
          Z	ded<   	  ee
          Zded<   dZded<   	  edd          Zded<   	 dZded<   	 dZded<   	  ed          ZedPd            ZedQd"            ZedRd#            ZdSd%ZdSd&ZdTd)ZdSd*Z	 	 dUdVd2Z	 	 dUdWd4Z	 	 dUdXd6Z	 	 dUdYd8ZdZd9Zd[d=Ze 	 d\d]d@            Z!e d^dD            Z"d_ fdHZ#ddId`dNZ$ xZ%S )ar   ui  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
                }
            }

    rE   Dict[str, str]c                
    ddiS )Ndashscope_api_keyDASHSCOPE_API_KEYrl   selfs    re   
lc_secretszChatTongyi.lc_secrets  s    #%899rr   Nr   clientz
qwen-turbomodel)defaultaliasra   
model_name)default_factoryDict[str, Any]model_kwargsg?floattop_papi_key)r   zOptional[SecretStr]r   FrD   	streaming
   intr   T)populate_by_namec                    dS )zReturn type of llm.tongyirl   r   s    re   	_llm_typezChatTongyi._llm_type  s	     xrr   valuesr   c                b   t          t          |dd                    |d<   	 ddl}n# t          $ r t          d          w xY wg d}|d         |v s
d|d         v r)	 |j        |d	<   nF# t
          $ r t          d
          w xY w	 |j        |d	<   n# t
          $ r t          d          w xY w|S )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-vl-v1zqwen-vl-chat-v1zqwen-audio-turbozqwen-vl-pluszqwen-vl-maxr   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)clsr   r   dashscope_multimodal_modelss       re   validate_environmentzChatTongyi.validate_environment  s<    '< )<>QRR'
 '
"#	 	 	 	L  	
'
 '
 '
# < $???vl+++#,#Cx  !    K  #,#7x  !    >   s!   ( A
A) )B
B B,c                    | j         | j        t          t          | j                                                  dd| j        S )z7Get the default parameters for calling Tongyi Qwen API.ry   )r   r   r   result_format)r   r   r   r7   r   get_secret_valuer   r   s    re   _default_paramszChatTongyi._default_params  sI     _ZIt'=>>OOQQ&	
 

 
 	
rr   kwargsc                N     t                     }|d fd            } |di |S )*Use tenacity to retry the completion call._kwargsr   rE   c                 F     j         j        di | }t          |          S )Nrl   )r   callr?   )r   respr   s     re   _completion_with_retryz@ChatTongyi.completion_with_retry.<locals>._completion_with_retry  s+    #4;#..g..D!$'''rr   r   r   rE   r   rl   r   )r   r   retry_decoratorr   s   `   re   completion_with_retryz ChatTongyi.completion_with_retry  sQ    1$77		( 	( 	( 	( 	( 
	( &%/////rr   c                N     t                     }|d fd            } |di |S )r   r   r   rE   c               ;    K    j         j        di | }d }|D ]m}|                     d          rE|                     dd          s/||}n                    ||          }|}t	          |          V  \t	          |          V  nd S )Nstreamincremental_outputFrl   )r   r   r^   subtract_client_responser?   )r   	responses	prev_respr   
delta_respr   s        re   _stream_completion_with_retryzNChatTongyi.stream_completion_with_retry.<locals>._stream_completion_with_retry  s      ((33733II! / / ;;x(( 
/(%2 2 
/ !(%)

%)%B%B4%S%S
 $I(444444(....../ /rr   r   rl   r   )r   r   r   r   s   `   re   stream_completion_with_retryz'ChatTongyi.stream_completion_with_retry  sQ    1$77		/ 	/ 	/ 	/ 	/ 
	/& -,66v666rr   r   r   c                   t          j        t          j        |                    }|d         d         d         }|d         }t          j        t          j        |                    }|d         d         d         }|d         }|d                             |d         d          |d<   |                    d          rt          |d                   D ]\  }	}
|
d         }|                    d          r^|d         |	         d         }|d	                             |d	         d          |d	<   |d
                             |d
         d          |d
<   |S )zvSubtract prev response from curr response.

        Useful when streaming without `incremental_output = True`
        outputchoicesr   ry   rI   rY   rL   rM   rN   rO   )jsonloadsdumpsreplacer^   r\   )r   r   r   	resp_copychoicery   prev_resp_copyprev_choiceprev_messagerR   	tool_callrM   prev_functions                re   r   z#ChatTongyi.subtract_client_response1  s]    Jtz$//00	8$Y/2#DJy$9$9::$X.y9!<"9-$Y/77Y8OQSTT	;;|$$ 	$-gl.C$D$D   y$Z0##L11 $0$>u$Ej$QM'/'7'?'?%f-r( (HV$ -5[,A,I,I%k2B- -H[) rr   c               n   K    G d d          } | | j         di |          2 3 d{V }|W V  6 dS )z}Because the dashscope SDK doesn't provide an async API,
        we wrap `stream_generate_with_retry` with an async generator.c                  .    e Zd Zd
dZddZddZddZd	S )EChatTongyi.astream_completion_with_retry.<locals>._AioTongyiGenerator	generatorr   c                    || _         d S Nr   )r   r   s     re   __init__zNChatTongyi.astream_completion_with_retry.<locals>._AioTongyiGenerator.__init__V  s    !*rr   rE   AsyncIterator[Any]c                    | S r   rl   r   s    re   	__aiter__zOChatTongyi.astream_completion_with_retry.<locals>._AioTongyiGenerator.__aiter__Y  s    rr   c                   K   t          j                                        d | j                   d {V }||S t          r   )asyncioget_running_looprun_in_executor
_safe_nextStopAsyncIteration)r   rb   s     re   	__anext__zOChatTongyi.astream_completion_with_retry.<locals>._AioTongyiGenerator.__anext__\  s\      %688HH$/        $ L,,rr   c                N    	 t          | j                  S # t          $ r Y d S w xY wr   )nextr   StopIterationr   s    re   r   zPChatTongyi.astream_completion_with_retry.<locals>._AioTongyiGenerator._safe_nexte  s9     ///$      44 s    
$$N)r   r   )rE   r   )rE   r   )__name__
__module____qualname__r   r   r   r   rl   rr   re   _AioTongyiGeneratorr   U  sd        + + + +   - - - -           rr   r   r   Nrl   )r   )r   r   r   chunks       re   astream_completion_with_retryz(ChatTongyi.astream_completion_with_retryQ  s      	  	  	  	  	  	  	  	 , /.7d7AA&AA
 
 
 	 	 	 	 	 	 	% KKKKK
 
 
s   4messagesList[BaseMessage]r   Optional[List[str]]run_manager"Optional[CallbackManagerForLLMRun]r)   c           	     |   g }| j         rMd } | j        |f||d|D ]}||}||z  }|J |                    |                     |                     nO | j        d||d|} | j        di |}	|                    t          di |                     |	                     t          |d| j	        i          S N)r   r   )r   r   r   )generations
llm_outputrl   )
r   _streamr]   _chunk_to_generation_invocation_paramsr   r'   _chat_generation_from_qwen_respr)   r   )
r   r   r   r   r   r  generation_chunkr   paramsr   s
             re   	_generatezChatTongyi._generatep  sE    > 	>B%# @F  . . $+',$$$-$$#///t889IJJKKKK%<T%< &!& &06& &F .4-7777DLL!E!Ed!K!KLL   #do
 
 
 	
rr   'Optional[AsyncCallbackManagerForLLMRun]c           	       K   g }| j         rSd } | j        |f||d|2 3 d {V }||}||z  }6 |J |                    |                     |                     n | j        d||d|}t          j                                        d t          j	        | j
        fi |           d {V }	|                    t          di |                     |	                     t          |d| j        i          S r  )r   _astreamr]   r  r  r   r   r   	functoolspartialr   r'   r  r)   r   )
r   r   r   r   r   r  
generationr   r	  r   s
             re   
_ageneratezChatTongyi._agenerate  s      > 	8<J,t} #   @F    ( ( ( ( ( ( (e %!&JJ%'JJ  )))t88DDEEEE%<T%< &!& &06& &F !133CC!$"<GGGG       D LL!E!Ed!K!KLL   #do
 
 
 	
s   1Iterator[ChatGenerationChunk]c           
   +  f  K    | j         d||dd|}t           | j        di |          D ]\  }}|d         d         d         }|d         }	|d         dk    r|	d	         d
k    rd|	vr>t          di |                     |d|          }
|r|                    |
j        |
           |
V  d S )NTr   r   r   r   r   r   ry   finish_reasonnullrI   rY   rL   rC   is_last_chunkr   rl   )r  r@   r   r(   r  on_llm_new_tokentext)r   r   r   r   r   r	  stream_respr  r   ry   r   s              re   r  zChatTongyi._stream  s-      "9!8 "
D"
 "
9?"
 "
 +J-D-7777+
 +
 	 	&K !*95a8FY'G'611I&",, //'  66$m 7   E
  F,,UZu,EEEKKKK'	 	rr   "AsyncIterator[ChatGenerationChunk]c           
      K    | j         d||dd|}t           | j        di |          2 3 d {V \  }}t          di |                     |d|          }|r"|                    |j        |           d {V  |W V  V6 d S )NTr  r  r  rl   )r  r>   r   r(   r  r  r  )	r   r   r   r   r   r	  r  r  r   s	            re   r  zChatTongyi._astream  s      "9!8 "
D"
 "
9?"
 "
 1Q.D.88881
 1
 
	 
	 
	 
	 
	 
	 
	,+} (  66$m 7   E
  L!225:U2KKKKKKKKKKKKKK1
 1
 1
s   Bc                |   i | j         |}|||d<   |                    d          r|                    d          sd|d<   d |D             }d t          |          D             }t          |          dk    r|d	         d	k    rt	          d
          t          |          dk    rt	          d          ||d<   |S )Nr   r   toolsTr   c                ,    g | ]}t          |          S rl   )r~   )rm   ms     re   
<listcomp>z1ChatTongyi._invocation_params.<locals>.<listcomp>  s!    FFF033FFFrr   c                0    g | ]\  }}|d          dk    |S )rH   rW   rl   )rm   ir"  s      re   r#  z1ChatTongyi._invocation_params.<locals>.<listcomp>  s1     "
 "
 "
!Qai86K6KA6K6K6Krr   rj   r   z-System message can only be the first message.z-There can be only one system message at most.r   )r   r^   r\   lenr   )r   r   r   r   r	  message_dictssystem_message_indicess          re   r  zChatTongyi._invocation_params  s     4D(3F3!F6N ::h 	0

7(;(; 	0+/F'(FFXFFF"
 "
#M22"
 "
 "
 %&&!++0Fq0IQ0N0NLMMM'((1,,LMMM*zrr   llm_outputsList[Optional[dict]]rz   c                &    |d         i S |d         S )Nr   rl   )r   r)  s     re   _combine_llm_outputszChatTongyi._combine_llm_outputs  s    q>!I1~rr   rC   r  c                    | d         d         d         }t          |d         |          }|r@t          |t          |d         | d         t          | d                   	          
          S t          |          S )Nr   r   r   ry   )rC   r  
request_idusage)r  r.  token_usagery   generation_info)ry   )rf   rz   )r   rC   r  r   ry   s        re   r  z*ChatTongyi._chat_generation_from_qwen_resp  s     h	*1-)&*;hOOO 
	) $"("9#L1 $T'] 3 3! ! !    ((((rr   r   r(   r'   c                R    t          t          | j                  | j                  S )Nr1  )r'   rx   ry   r2  r  s    re   r  zChatTongyi._chunk_to_generation%  s,    4U]CC!1
 
 
 	
rr   r   DSequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]])Runnable[LanguageModelInput, BaseMessage]c                R    d |D             } t                      j        dd|i|S )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.
        c                ,    g | ]}t          |          S rl   r1   )rm   rX   s     re   r#  z)ChatTongyi.bind_tools.<locals>.<listcomp><  s!    JJJD1$77JJJrr   r   rl   )superbind)r   r   r   formatted_toolsrt   s       re   
bind_toolszChatTongyi.bind_tools,  s:      KJEJJJuww|<</<V<<<rr   )include_rawschemaUnion[Dict, Type[BaseModel]]r<  4Runnable[LanguageModelInput, Union[Dict, BaseModel]]c                  |rt          d|           t          |t                    ot          |          }|                     |g          }|rt          |gd          }n,t          |          d         d         }t          |d          }|rht          j	        t          d          |z  d 	          }t          j	        d
           }	|                    |	gd          }
t          |          |
z  S ||z  S )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_onlyrM   rN   )key_namerA  rawc                    d S r   rl   _s    re   <lambda>z3ChatTongyi.with_structured_output.<locals>.<lambda>x  s    RV rr   )parsedparsing_errorc                    d S r   rl   rE  s    re   rG  z3ChatTongyi.with_structured_output.<locals>.<lambda>z  s    d rr   )rH  rI  )exception_key)rC  )r   rs   ri   r3   r;  r$   r2   r#   r,   assignr   with_fallbacksr+   )r   r=  r<  r   is_pydantic_schemar   output_parserrB  parser_assignparser_noneparser_with_fallbacks              re   with_structured_outputz!ChatTongyi.with_structured_output?  sB   P  	IGvGGHHH'55W:OPV:W:Woovh'' 		.Ah $/ / /MM
 .f55jA&IH4!4  M  
	'/6!%((=8  M .4NNKKKK#0#?#?_ $@ $ $  3'''*>>>&&rr   )rE   r   )rE   ra   )r   r   rE   r   )rE   r   )r   r   rE   r   )r   r   r   r   rE   r   )NN)
r   r   r   r   r   r   r   r   rE   r)   )
r   r   r   r   r   r  r   r   rE   r)   )
r   r   r   r   r   r   r   r   rE   r  )
r   r   r   r   r   r  r   r   rE   r  )r   r   r   r   r   r   rE   r   )r)  r*  rE   rz   )FT)r   r   rC   rD   r  rD   rE   r   )r   r(   rE   r'   )r   r4  r   r   rE   r5  )r=  r>  r<  rD   r   r   rE   r?  )&r   r   r   __doc__propertyr   r   __annotations__r6   r   rz   r   r   r   r   r   r5   model_configr   r0   r   r   r   r   r   r   r
  r  r  r  r  r,  staticmethodr  r  r;  rS  __classcell__)rt   s   @re   r   r      s        | || : : : X: FeL@@@J@@@@ $)5#>#>#>L>>>>ED-2U4y-I-I-IIIII5I/K<:  L    X ( ( ( X(T 
 
 
 X
	0 	0 	0 	07 7 7 74   @   D %):>	 
  
  
  
  
J %)?C	#
 #
 #
 #
 #
P %):>	    F %)?C	    ,   4   
 AE) ) ) ) \)0 
 
 
 \
= = = = = =. "	A' A' A' A' A' A' A' A' A' A'rr   )F)rA   rB   rC   rD   rE   rF   )rg   r   rE   r   )ry   r   rE   rz   )r   r   rE   r   )\
__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_callingr2   langchain_core.utils.pydanticr3   pydanticr4   r5   r6   r7   requests.exceptionsr8   tenacityr9   r:   r;   r<   r=   langchain_community.llms.tongyir>   r?   r@   	getLoggerr   r   rf   rx   r~   r   r   rl   rr   re   <module>rn     s3   " " " " " "                                                > = = = = = D D D D D D                              @ ? ? ? ? ?                    
 P O O O O O O O O O ) ) ) ) ) ) V V V V V V V V V V H H H H H H ? ? ? ? ? ?            * ) ) ) ) )                       
	8	$	$ 05W
 W
 W
 W
 W
t   (   B   N
' N
' N
' N
' N
' N
' N
' N
' N
' N
'rr   