§
    šŠtj…  ã                  ó  — d Z ddlmZ ddlZddlZddlZddl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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$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l0m1Z1m2Z2 ddl3m4Z4m5Z5m6Z6 ddl7m8Z8m9Z9m:Z: ddl;m<Z< ddl=m>Z> ddl?m@Z@ ddlAmBZBmCZCmDZDmEZE  ejF        eG¦  «        ZHdZIdZJd5d„ZKed6d!„¦   «         ZLe
d7d#„¦   «         ZMd8d%„ZNd9d)„ZOd:d+„ZPd;d/„ZQd<d2„ZR G d3„ d4e¦  «        ZSdS )=zZhipuAI chat models wrapper.é    )ÚannotationsN)ÚAsyncIteratorÚIterator)ÚasynccontextmanagerÚcontextmanager)Ú
itemgetter)
ÚAnyÚCallableÚDictÚListÚLiteralÚOptionalÚSequenceÚTupleÚTypeÚUnion)ÚAsyncCallbackManagerForLLMRunÚCallbackManagerForLLMRun)ÚLanguageModelInput)ÚBaseChatModelÚagenerate_from_streamÚgenerate_from_stream)Ú	AIMessageÚAIMessageChunkÚBaseMessageÚBaseMessageChunkÚChatMessageÚChatMessageChunkÚHumanMessageÚHumanMessageChunkÚSystemMessageÚSystemMessageChunkÚToolMessage)ÚOutputParserLike)ÚJsonOutputKeyToolsParserÚPydanticToolsParser)ÚChatGenerationÚChatGenerationChunkÚ
ChatResult)ÚRunnableÚRunnableMapÚRunnablePassthrough)ÚBaseTool)Úget_from_dict_or_env©Úconvert_to_openai_tool)Ú	BaseModelÚ
ConfigDictÚFieldÚmodel_validatoré´   z5https://open.bigmodel.cn/api/paas/v4/chat/completionsÚobjr	   ÚreturnÚboolc                óV   — t          | t          ¦  «        ot          | t          ¦  «        S ©N)Ú
isinstanceÚtypeÚ
issubclassr1   )r6   s    úe/var/www/html/CA-Chatbot/venv/lib/python3.11/site-packages/langchain_community/chat_models/zhipuai.pyÚ_is_pydantic_classr?   A   s!   € Ý�c�4Ñ Ô Ð?¥Z°µYÑ%?Ô%?Ð?ó    ÚclientÚmethodÚstrÚurlÚkwargsr   c              +  ó€   K  — ddl m}  | j        ||fi |¤Ž5 } ||¦  «        V — ddd¦  «         dS # 1 swxY w Y   dS )zíContext manager for connecting to an SSE stream.

    Args:
        client: The HTTP client.
        method: The HTTP method.
        url: The URL.
        kwargs: Additional keyword arguments.

    Yields:
        The event source.
    r   ©ÚEventSourceN©Ú	httpx_sserH   Ústream©rA   rB   rD   rE   rH   Úresponses         r>   Úconnect_sserN   E   s­   è è € ð &Ð%Ð%Ð%Ð%Ð%à	ˆŒ�v˜sÐ	-Ð	- fÐ	-Ð	-ð $°Øˆk˜(Ñ#Ô#Ð#Ð#Ð#ð$ð $ð $ñ $ô $ð $ð $ð $ð $ð $ð $ð $øøøð $ð $ð $ð $ð $ð $s   ˜3³7º7r   c               ó¦   K  — ddl m}  | j        ||fi |¤Ž4 ƒd{V —†} ||¦  «        W V — ddd¦  «        ƒd{V —† dS # 1 ƒd{V —†swxY w Y   dS )zóAsync context manager for connecting to an SSE stream.

    Args:
        client: The HTTP client.
        method: The HTTP method.
        url: The URL.
        kwargs: Additional keyword arguments.

    Yields:
        The event source.
    r   rG   NrI   rL   s         r>   Úaconnect_sserP   X   s
  è è € ð &Ð%Ð%Ð%Ð%Ð%àˆvŒ}˜V SÐ3Ð3¨FÐ3Ð3ð $ð $ð $ð $ð $ð $ð $°xØˆk˜(Ñ#Ô#Ð#Ð#Ð#Ð#ð$ð $ð $ñ $ô $ð $ð $ð $ð $ð $ð $ð $ð $ð $ð $ð $ð $ð $ð $ð $ð $ð $ð $ð $øøøð $ð $ð $ð $ð $ð $s   žA Á 
A
ÁA
Úapi_keyc                óØ  — 	 ddl }n# t          $ r t          d¦  «        ‚w xY w	 |                      d¦  «        \  }}n%# t          $ r}t          d| › �¦  «        |‚d}~ww xY w|t	          t          t          j        ¦   «         dz  ¦  «        ¦  «        t          dz  z   t	          t          t          j        ¦   «         dz  ¦  «        ¦  «        dœ}|                     ||ddd	d
œ¬¦  «        S )zµGets JWT token for ZhipuAI API.

    See 'https://open.bigmodel.cn/dev/api#nosdk'.

    Args:
        api_key: The API key for ZhipuAI API.

    Returns:
        The JWT token.
    r   Nz@jwt package not found, please install it with`pip install pyjwt`ú.zInvalid API key: iè  )rQ   ÚexpÚ	timestampÚHS256ÚSIGN)ÚalgÚ	sign_type)Ú	algorithmÚheaders)	ÚjwtÚImportErrorÚsplitÚ
ValueErrorÚintÚroundÚtimeÚAPI_TOKEN_TTL_SECONDSÚencode)rQ   r\   ÚidÚsecretÚerrÚpayloads         r>   Ú_get_jwt_tokenri   m   s$  € ð
Øˆ
ˆ
ˆ
ˆ
øÝð 
ð 
ð 
ÝØNñ
ô 
ð 	
ð
øøøð
AØ—]’] 3Ñ'Ô'‰
ˆˆFˆFøÝð Að Að AÝÐ6¨WÐ6Ð6Ñ7Ô7¸SÐ@øøøøðAøøøð Ý•5�œ™œ tÑ+Ñ,Ô,Ñ-Ô-Õ0EÈÑ0LÑLÝ��tœy™{œ{¨TÑ1Ñ2Ô2Ñ3Ô3ðð €Gð �:Š:ØØØØ¨fÐ5Ð5ð	 ñ ô ð s   ‚ ‡!¥> ¾
A ÁAÁA ÚdctúDict[str, Any]r   c                ó¶  — |                       d¦  «        }|                       dd¦  «        }|dk    rt          |¬¦  «        S |dk    rt          |¬¦  «        S |dk    r0i }|                       dd ¦  «        }|�||d<   t          ||¬	¦  «        S |d
k    r6i }d| v r| d         |d<   t	          ||                       d¦  «        |¬¦  «        S t          ||¬¦  «        S )NÚroleÚcontentÚ Úsystem©rn   ÚuserÚ	assistantÚ
tool_calls©rn   Úadditional_kwargsÚtoolÚnameÚtool_call_id)rn   ry   rv   ©rm   rn   )Úgetr!   r   r   r#   r   )rj   rm   rn   rv   rt   s        r>   Ú_convert_dict_to_messager|   ’   s  € Ø�7Š7�6‰?Œ?€DØ�gŠg�i Ñ$Ô$€GØˆxÒÐÝ WÐ-Ñ-Ô-Ð-Øˆv‚~€~Ý GÐ,Ñ,Ô,Ð,Øˆ{ÒÐØÐØ—W’W˜\¨4Ñ0Ô0ˆ
ØÐ!Ø.8Ð˜lÑ+Ý Ð<MÐNÑNÔNÐNØˆv‚~€~ØÐØ�Sˆ=ˆ=Ø(+¨F¬Ð˜fÑ%ÝØØŸš Ñ0Ô0Ø/ð
ñ 
ô 
ð 	
õ
 ˜D¨'Ð2Ñ2Ô2Ð2r@   Úmessagec                óÖ  — t          | t          ¦  «        r| j        | j        dœ}nÃt          | t          ¦  «        rd| j        dœ}n£t          | t
          ¦  «        rd| j        dœ}nƒt          | t          ¦  «        rd| j        dœ}nct          | t          ¦  «        r1d| j        | j        | j	        p| j
                             d¦  «        dœ}nt          d| j        j        › d	�¦  «        ‚|S )
zŠConvert a LangChain message to a dictionary.

    Args:
        message: The LangChain message.

    Returns:
        The dictionary.
    rz   rp   rr   rs   rw   rx   )rm   rn   ry   rx   zGot unknown type 'z'.)r;   r   rm   rn   r!   r   r   r#   ry   rx   rv   r{   Ú	TypeErrorÚ	__class__Ú__name__)r}   Úmessage_dicts     r>   Ú_convert_message_to_dictrƒ   «   s  € õ �'�;Ñ'Ô'ð MØ '¤¸¼ÐIÐIˆˆÝ	�G�]Ñ	+Ô	+ð MØ (°W´_ÐEÐEˆˆÝ	�G�\Ñ	*Ô	*ð MØ &°7´?ÐCÐCˆˆÝ	�G�YÑ	'Ô	'ð 
MØ +¸¼ÐHÐHˆˆÝ	�G�[Ñ	)Ô	)ð MàØ”Ø#Ô0Ø”LÐI GÔ$=×$AÒ$AÀ&Ñ$IÔ$Ið	
ð 
ˆˆõ ÐK¨WÔ->Ô-GÐKÐKÐKÑLÔLÐLØÐr@   Údefault_classúType[BaseMessageChunk]r   c                ó²  — |                       d¦  «        }|                       dd¦  «        }i }|                       dd ¦  «        }|�||d<   |dk    s|t          k    rt          |¬¦  «        S |dk    s|t          k    rt          |¬¦  «        S |dk    s|t          k    rt          ||¬	¦  «        S |s|t          k    rt	          ||¬
¦  «        S  ||¬¦  «        S )Nrm   rn   ro   rt   rp   rq   rr   rs   ru   )rn   rm   )r{   r"   r    r   r   )rj   r„   rm   rn   rv   rt   s         r>   Ú_convert_delta_to_message_chunkr‡   É   sþ   € ð �7Š7�6‰?Œ?€DØ�gŠg�i Ñ$Ô$€GØÐØ—’˜ tÑ,Ô,€JØÐØ*4Ð˜,Ñ'àˆxÒÐ˜=Õ,>Ò>Ð>Ý!¨'Ð2Ñ2Ô2Ð2Øˆv‚~€~˜Õ*;Ò;Ð;Ý ¨Ð1Ñ1Ô1Ð1Øˆ{ÒÐ˜m­~Ò=Ð=Ý gÐARÐSÑSÔSÐSØð <ˆ}Õ 0Ò0Ð0Ý¨°dÐ;Ñ;Ô;Ð;Øˆ= Ð)Ñ)Ô)Ð)r@   rh   ÚNonec                óê   — |                       d¦  «        }|                       d¦  «        }|�!t          dt          d|¦  «        ¦  «        | d<   |�#t          dt          d|¦  «        ¦  «        | d<   dS dS )z¹Truncate temperature and top_p parameters between [0.01, 0.99].

    ZhipuAI only support temperature / top_p between (0, 1) open interval,
    so we truncate them to [0.01, 0.99].
    ÚtemperatureÚtop_pNg{®Gáz„?g®Gáz®ï?)r{   ÚmaxÚmin)rh   rŠ   r‹   s      r>   Ú_truncate_paramsrŽ   Þ   s|   € ð —+’+˜mÑ,Ô,€KØ�KŠK˜Ñ Ô €EØÐÝ!$ T­3¨t°[Ñ+AÔ+AÑ!BÔ!Bˆ�ÑØÐÝ˜t¥S¨¨uÑ%5Ô%5Ñ6Ô6ˆ�ÑÐÐð Ðr@   c                  ó   — e Zd ZU dZedMd„¦   «         ZedNd„¦   «         ZedOd„¦   «         ZedPd
„¦   «         Z	edOd„¦   «         Z
 edd¬¦  «        Zde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<   	 dZded<   	 dZded<   	  ed ¬!¦  «        Z ed"¬#¦  «        edQd&„¦   «         ¦   «         ZdRd,„ZdSd0„Z	 	 	 dTdUd6„Z	 	 dVdWd8„Z	 	 	 dTdXd:„Z	 	 dVdYd<„Zdd=œdZdC„Z	 d[dDddEœd\dL„ZdS )]ÚChatZhipuAIu”  ZhipuAI chat model integration.

    Setup:
        Install ``PyJWT`` and set environment variable ``ZHIPUAI_API_KEY``

        .. code-block:: bash

            pip install pyjwt
            export ZHIPUAI_API_KEY="your-api-key"

    Key init args â€” completion params:
        model: Optional[str]
            Name of ZhipuAI model to use.
        temperature: float
            Sampling temperature.
        max_tokens: Optional[int]
            Max number of tokens to generate.

    Key init args â€” client params:
        api_key: Optional[str]
            ZhipuAI API key. If not passed in will be read from env var ZHIPUAI_API_KEY.
        api_base: Optional[str]
            Base URL for API requests.

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

    Instantiate:
        .. code-block:: python

            from langchain_community.chat_models import ChatZhipuAI

            zhipuai_chat = ChatZhipuAI(
                temperature=0.5,
                api_key="your-api-key",
                model="glm-4",
                # api_base="...",
                # other params...
            )

    Invoke:
        .. code-block:: python

            messages = [
                ("system", "ä½ æ˜¯ä¸€å��ä¸“ä¸šçš„ç¿»è¯‘å®¶ï¼Œå�¯ä»¥å°†ç”¨æˆ·çš„ä¸­æ–‡ç¿»è¯‘ä¸ºè‹±æ–‡ã€‚"),
                ("human", "æˆ‘å–œæ¬¢ç¼–ç¨‹ã€‚"),
            ]
            zhipuai_chat.invoke(messages)

        .. code-block:: python

            AIMessage(content='I enjoy programming.', response_metadata={'token_usage': {'completion_tokens': 6, 'prompt_tokens': 23, 'total_tokens': 29}, 'model_name': 'glm-4', 'finish_reason': 'stop'}, id='run-c5d9af91-55c6-470e-9545-02b2fa0d7f9d-0')

    Stream:
        .. code-block:: python

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

        .. code-block:: python

            content='I' id='run-4df71729-618f-4e2b-a4ff-884682723082'
            content=' enjoy' id='run-4df71729-618f-4e2b-a4ff-884682723082'
            content=' programming' id='run-4df71729-618f-4e2b-a4ff-884682723082'
            content='.' id='run-4df71729-618f-4e2b-a4ff-884682723082'
            content='' response_metadata={'finish_reason': 'stop'} id='run-4df71729-618f-4e2b-a4ff-884682723082'

        .. code-block:: python

            stream = zhipuai_chat.stream(messages)
            full = next(stream)
            for chunk in stream:
                full += chunk
            full

        .. code-block::

            AIMessageChunk(content='I enjoy programming.', response_metadata={'finish_reason': 'stop'}, id='run-20b05040-a0b4-4715-8fdc-b39dba9bfb53')

    Async:
        .. code-block:: python

            await zhipuai_chat.ainvoke(messages)

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

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

        .. code-block:: python

            [AIMessage(content='I enjoy programming.', response_metadata={'token_usage': {'completion_tokens': 6, 'prompt_tokens': 23, 'total_tokens': 29}, 'model_name': 'glm-4', 'finish_reason': 'stop'}, id='run-ba06af9d-4baa-40b2-9298-be9c62aa0849-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 = zhipuai_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': 'call_202408222146464ea49ec8731145a9',
                    'type': 'tool_call'
                }
            ]

    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 = zhipuai_chat.with_structured_output(Joke)
            structured_chat.invoke("Tell me a joke about cats")

        .. code-block:: python

            Joke(setup='What do cats like to eat for breakfast?', punchline='Mice Krispies!', rating=None)

    Response metadata
        .. code-block:: python

            ai_msg = zhipuai_chat.invoke(messages)
            ai_msg.response_metadata

        .. code-block:: python

            {'token_usage': {'completion_tokens': 6,
              'prompt_tokens': 23,
              'total_tokens': 29},
              'model_name': 'glm-4',
              'finish_reason': 'stop'}

    r7   úDict[str, str]c                ó
   — ddiS )NÚzhipuai_api_keyÚZHIPUAI_API_KEY© ©Úselfs    r>   Ú
lc_secretszChatZhipuAI.lc_secrets˜  s   € à!Ð#4Ð5Ð5r@   ú	List[str]c                ó
   — g d¢S )z*Get the namespace of the langchain object.)Ú	langchainÚchat_modelsÚzhipuair•   )Úclss    r>   Úget_lc_namespacezChatZhipuAI.get_lc_namespaceœ  s   € ð 7Ð6Ð6Ð6r@   rk   c                ó,   — i }| j         r
| j         |d<   |S )NÚzhipuai_api_base)r¡   )r—   Ú
attributess     r>   Úlc_attributeszChatZhipuAI.lc_attributes¡  s'   € à%'ˆ
àÔ ð 	CØ-1Ô-BˆJÐ)Ñ*àÐr@   rC   c                ó   — dS )zReturn the type of chat model.zzhipuai-chatr•   r–   s    r>   Ú	_llm_typezChatZhipuAI._llm_typeª  s	   € ð ˆ~r@   c                óR   — | j         | j        | j        dœ}| j        �
| j        |d<   |S )z2Get the default parameters for calling OpenAI API.)ÚmodelrK   rŠ   NÚ
max_tokens)Ú
model_nameÚ	streamingrŠ   r¨   )r—   Úparamss     r>   Ú_default_paramszChatZhipuAI._default_params¯  s;   € ð ”_Ø”nØÔ+ð
ð 
ˆð
 Œ?Ð&Ø#'¤?ˆF�<Ñ Øˆr@   NrQ   )ÚdefaultÚaliaszOptional[str]r“   Úapi_baser¡   zglm-4r§   r©   gffffffî?ÚfloatrŠ   gffffffæ?r‹   Fr8   rª   zOptional[int]r¨   T)Úpopulate_by_nameÚbefore)ÚmodeÚvaluesr	   c                óh   — t          |ddgd¦  «        |d<   t          |ddt          ¬¦  «        |d<   |S )Nr“   rQ   r”   r¡   ÚZHIPUAI_API_BASE)r­   )r.   r¶   )rž   r´   s     r>   Úvalidate_environmentz ChatZhipuAI.validate_environmentç  sV   € õ %9ØÐ&¨	Ð2Ð4Eñ%
ô %
ˆÐ Ñ!õ &:ØÐ&Ð(:ÕDTð&
ñ &
ô &
ˆÐ!Ñ"ð ˆr@   ÚmessagesúList[BaseMessage]ÚstopúOptional[List[str]]ú+Tuple[List[Dict[str, Any]], Dict[str, Any]]c                ó>   — | j         }|�||d<   d„ |D ¦   «         }||fS )Nrº   c                ó,   — g | ]}t          |¦  «        ‘ŒS r•   )rƒ   )Ú.0Úms     r>   ú
<listcomp>z5ChatZhipuAI._create_message_dicts.<locals>.<listcomp>ù  s!   € ÐGÐGÐG¸Õ1°!Ñ4Ô4ÐGÐGÐGr@   )r¬   )r—   r¸   rº   r«   Úmessage_dictss        r>   Ú_create_message_dictsz!ChatZhipuAI._create_message_dictsó  s9   € ð Ô%ˆØÐØ!ˆF�6‰NØGÐG¸hÐGÑGÔGˆØ˜fÐ$Ð$r@   rM   úUnion[dict, BaseModel]r)   c                óˆ  — g }t          |t          ¦  «        s|                     ¦   «         }|d         D ]^}t          |d         ¦  «        }t          |                     d¦  «        ¬¦  «        }|                     t          ||¬¦  «        ¦  «         Œ_|                     di ¦  «        }|| j        dœ}t          ||¬¦  «        S )	NÚchoicesr}   Úfinish_reason)rÇ   ©r}   Úgeneration_infoÚusage)Útoken_usager©   )ÚgenerationsÚ
llm_output)r;   Údictr|   r{   Úappendr'   r©   r)   )r—   rM   rÌ   Úresr}   rÉ   rË   rÍ   s           r>   Ú_create_chat_resultzChatZhipuAI._create_chat_resultü  sÒ   € ØˆÝ˜(¥DÑ)Ô)ð 	'Ø—}’}‘”ˆHØ˜IÔ&ð 	ð 	ˆCÝ.¨s°9¬~Ñ>Ô>ˆGÝ"°·²¸Ñ1IÔ1IÐJÑJÔJˆOØ×ÒÝ wÀÐPÑPÔPñô ð ð ð —l’l 7¨BÑ/Ô/ˆà&Øœ/ð
ð 
ˆ
õ  k¸jÐIÑIÔIÐIr@   Úrun_managerú"Optional[CallbackManagerForLLMRun]rK   úOptional[bool]rE   c                ó0  — |�|n| j         }|r  | j        |f||dœ|¤Ž}t          |¦  «        S | j        €t	          d¦  «        ‚|                      ||¦  «        \  }}	i |	¥|¥|ddœ¥}
t          |
¦  «         t          | j        ¦  «        ddœ}ddl}| 	                    |d	¬
¦  «        5 }| 
                    | j        |
¬¦  «        }|                     ¦   «          ddd¦  «         n# 1 swxY w Y   |                      |                     ¦   «         ¦  «        S )zGenerate a chat response.N©rº   rÒ   úDid not find zhipuai_api_key.F©r¸   rK   úapplication/json©ÚAuthorizationÚAcceptr   é<   ©r[   Útimeout©Újson)rª   Ú_streamr   r“   r_   rÃ   rŽ   ri   ÚhttpxÚClientÚpostr¡   Úraise_for_statusrÑ   rá   ©r—   r¸   rº   rÒ   rK   rE   Úshould_streamÚstream_iterrÂ   r«   rh   r[   rã   rA   rM   s                  r>   Ú	_generatezChatZhipuAI._generate  s¡  € ð #)Ð"4˜˜¸$¼.ˆØð 	5Ø&˜$œ,ØðØ#°ðð Ø@Fðð ˆKõ (¨Ñ4Ô4Ð4àÔÐ'ÝÐ<Ñ=Ô=Ð=Ø $× :Ò :¸8ÀTÑ JÔ JÑˆ�vð
Øð
àð
ð &Øð	
ð 
ð 
ˆõ 	˜Ñ!Ô!Ð!å+¨DÔ,@ÑAÔAØ(ð
ð 
ˆð 	ˆˆˆà�\Š\ '°2ˆ\Ñ6Ô6ð 	(¸&Ø—{’{ 4Ô#8¸w�{ÑGÔGˆHØ×%Ò%Ñ'Ô'Ð'ð	(ð 	(ð 	(ñ 	(ô 	(ð 	(ð 	(ð 	(ð 	(ð 	(ð 	(øøøð 	(ð 	(ð 	(ð 	(ð ×'Ò'¨¯ª©¬Ñ8Ô8Ð8s   Â)1C&Ã&C*Ã-C*úIterator[ChatGenerationChunk]c              +  ó®  K  — | j         €t          d¦  «        ‚| j        €t          d¦  «        ‚|                      ||¦  «        \  }}i |¥|¥|ddœ¥}t	          |¦  «         t          | j         ¦  «        ddœ}t          }	ddl}
|
                     |d	¬
¦  «        5 }t          |d| j        |¬¦  «        5 }| 
                    ¦   «         D ]Ü}t          j        |j        ¦  «        }t          |d         ¦  «        dk    rŒ5|d         d         }|                     dd¦  «        }|                     dd¦  «        }t!          |d         |	¦  «        }|                     dd¦  «        }|�|||dœnd}t#          ||¬¦  «        }|r|                     |j        |¬¦  «         |V — |� nŒÝddd¦  «         n# 1 swxY w Y   ddd¦  «         dS # 1 swxY w Y   dS )z#Stream the chat response in chunks.Nr×   úDid not find zhipu_api_base.TrØ   rÙ   rÚ   r   rÝ   rÞ   ÚPOSTrà   rÆ   rÊ   r§   ro   ÚdeltarÇ   ©rÇ   rË   r©   rÈ   ©Úchunk)r“   r_   r¡   rÃ   rŽ   ri   r   rã   rä   rN   Úiter_sserá   ÚloadsÚdataÚlenr{   r‡   r(   Úon_llm_new_tokenÚtext©r—   r¸   rº   rÒ   rE   rÂ   r«   rh   r[   Údefault_chunk_classrã   rA   Úevent_sourceÚsserò   ÚchoicerÊ   r©   rÇ   rÉ   s                       r>   râ   zChatZhipuAI._stream2  sÅ  è è € ð ÔÐ'ÝÐ<Ñ=Ô=Ð=ØÔ Ð(ÝÐ;Ñ<Ô<Ð<Ø $× :Ò :¸8ÀTÑ JÔ JÑˆ�vØQ�VÐQ˜vÐQ°=ÈDÐQÐQÐQˆÝ˜Ñ!Ô!Ð!å+¨DÔ,@ÑAÔAØ(ð
ð 
ˆõ
 -ÐØˆˆˆà�\Š\ '°2ˆ\Ñ6Ô6ð !	¸&ÝØ˜ Ô 5¸Gðñ ô ð  àØ'×0Ò0Ñ2Ô2ð ð �CÝ œJ s¤xÑ0Ô0�EÝ˜5 Ô+Ñ,Ô,°Ò1Ð1Ø Ø" 9Ô-¨aÔ0�FØ!ŸIšI g¨tÑ4Ô4�EØ!&§¢¨7°BÑ!7Ô!7�JÝ;Ø˜wœÐ)<ñô �Eð %+§J¢J¨ÀÑ$EÔ$E�Mð )Ð4ð	 .;Ø+0Ø*4ðð ð ð "ð $õ 0Ø %°ðñ ô �Eð #ð NØ#×4Ò4°U´ZÀuÐ4ÑMÔMÐMØ�K�K�Kà$Ð0Ø˜ð 1ð? ð  ð  ñ  ô  ð  ð  ð  ð  ð  ð  øøøð  ð  ð  ð  ð!	ð !	ð !	ñ !	ô !	ð !	ð !	ð !	ð !	ð !	ð !	ð !	øøøð !	ð !	ð !	ð !	ð !	ð !	s7   ÂG
Â4C2F2Æ&G
Æ2F6	Æ6G
Æ9F6	Æ:G
Ç
GÇGú'Optional[AsyncCallbackManagerForLLMRun]c              ‹  óp  K  — |�|n| j         }|r& | j        |f||dœ|¤Ž}t          |¦  «        ƒ d {V —†S | j        €t	          d¦  «        ‚|                      ||¦  «        \  }}	i |	¥|¥|ddœ¥}
t          |
¦  «         t          | j        ¦  «        ddœ}dd l}| 	                    |d¬	¦  «        4 ƒd {V —†}| 
                    | j        |
¬
¦  «        ƒ d {V —†}|                     ¦   «          d d d ¦  «        ƒd {V —† n# 1 ƒd {V —†swxY w Y   |                      |                     ¦   «         ¦  «        S )NrÖ   r×   FrØ   rÙ   rÚ   r   rÝ   rÞ   rà   )rª   Ú_astreamr   r“   r_   rÃ   rŽ   ri   rã   ÚAsyncClientrå   r¡   ræ   rÑ   rá   rç   s                  r>   Ú
_ageneratezChatZhipuAI._ageneratel  s&  è è € ð #)Ð"4˜˜¸$¼.ˆØð 	<Ø'˜$œ-ØðØ#°ðð Ø@Fðð ˆKõ /¨{Ñ;Ô;Ð;Ð;Ð;Ð;Ð;Ð;Ð;àÔÐ'ÝÐ<Ñ=Ô=Ð=Ø $× :Ò :¸8ÀTÑ JÔ JÑˆ�vð
Øð
àð
ð &Øð	
ð 
ð 
ˆõ 	˜Ñ!Ô!Ð!å+¨DÔ,@ÑAÔAØ(ð
ð 
ˆð 	ˆˆˆà×$Ò$¨W¸bÐ$ÑAÔAð 	(ð 	(ð 	(ð 	(ð 	(ð 	(ð 	(ÀVØ#Ÿ[š[¨Ô)>ÀW˜[ÑMÔMÐMÐMÐMÐMÐMÐMˆHØ×%Ò%Ñ'Ô'Ð'ð	(ð 	(ð 	(ñ 	(ô 	(ð 	(ð 	(ð 	(ð 	(ð 	(ð 	(ð 	(ð 	(ð 	(ð 	(ð 	(ð 	(ð 	(ð 	(ð 	(ð 	(ð 	(ð 	(øøøð 	(ð 	(ð 	(ð 	(ð ×'Ò'¨¯ª©¬Ñ8Ô8Ð8s   Â77D Ä 
D
ÄD
ú"AsyncIterator[ChatGenerationChunk]c               ó  K  — | j         €t          d¦  «        ‚| j        €t          d¦  «        ‚|                      ||¦  «        \  }}i |¥|¥|ddœ¥}t	          |¦  «         t          | j         ¦  «        ddœ}t          }	dd l}
|
                     |d¬	¦  «        4 ƒd {V —†}t          |d
| j        |¬¦  «        4 ƒd {V —†	 }| 
                    ¦   «         2 3 d {V —†}t          j        |j        ¦  «        }t          |d         ¦  «        dk    rŒ:|d         d         }|                     dd ¦  «        }|                     dd¦  «        }t!          |d         |	¦  «        }|                     dd ¦  «        }|�|||dœnd }t#          ||¬¦  «        }|r"|                     |j        |¬¦  «        ƒ d {V —† |W V — |� nŒé6 	 d d d ¦  «        ƒd {V —† n# 1 ƒd {V —†swxY w Y   d d d ¦  «        ƒd {V —† d S # 1 ƒd {V —†swxY w Y   d S )Nr×   rí   TrØ   rÙ   rÚ   r   rÝ   rÞ   rî   rà   rÆ   rÊ   r§   ro   rï   rÇ   rð   rÈ   rñ   )r“   r_   r¡   rÃ   rŽ   ri   r   rã   r  rP   Ú	aiter_sserá   rô   rõ   rö   r{   r‡   r(   r÷   rø   rù   s                       r>   r   zChatZhipuAI._astream�  s¶  è è € ð ÔÐ'ÝÐ<Ñ=Ô=Ð=ØÔ Ð(ÝÐ;Ñ<Ô<Ð<Ø $× :Ò :¸8ÀTÑ JÔ JÑˆ�vØQ�VÐQ˜vÐQ°=ÈDÐQÐQÐQˆÝ˜Ñ!Ô!Ð!å+¨DÔ,@ÑAÔAØ(ð
ð 
ˆõ
 -ÐØˆˆˆà×$Ò$¨W¸bÐ$ÑAÔAð !	ð !	ð !	ð !	ð !	ð !	ð !	ÀVÝ#Ø˜ Ô 5¸Gðñ ô ð  ð  ð  ð  ð  ð  ð  ð  àØ!-×!7Ò!7Ñ!9Ô!9ð ð ð ð ð ð ð ˜#Ý œJ s¤xÑ0Ô0�EÝ˜5 Ô+Ñ,Ô,°Ò1Ð1Ø Ø" 9Ô-¨aÔ0�FØ!ŸIšI g¨tÑ4Ô4�EØ!&§¢¨7°BÑ!7Ô!7�JÝ;Ø˜wœÐ)<ñô �Eð %+§J¢J¨ÀÑ$EÔ$E�Mð )Ð4ð	 .;Ø+0Ø*4ðð ð ð "ð $õ 0Ø %°ðñ ô �Eð #ð TØ)×:Ò:¸5¼:ÈUÐ:ÑSÔSÐSÐSÐSÐSÐSÐSÐSØ�K�K�K�Kà$Ð0Ø˜ð 1ð9 ":Ð!9ð ð  ð  ñ  ô  ð  ð  ð  ð  ð  ð  ð  ð  ð  ð  ð  ð  ð  ð  ð  ð  ð  ð  øøøð  ð  ð  ð  ð!	ð !	ð !	ñ !	ô !	ð !	ð !	ð !	ð !	ð !	ð !	ð !	ð !	ð !	ð !	ð !	ð !	ð !	ð !	ð !	ð !	ð !	ð !	ð !	øøøð !	ð !	ð !	ð !	ð !	ð !	sC   Â!G7ÃGÃF?ÃC$GÇG7Ç
G	ÇG7Ç G	Ç!G7Ç7
HÈH©Útool_choiceÚtoolsúDSequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]]r  ú@Optional[Union[dict, str, Literal['auto', 'any', 'none'], bool]]ú'Runnable[LanguageModelInput, AIMessage]c               ó´   — | j         dk    rt          d¦  «        ‚d„ |D ¦   «         }|r|dk    rt          d¦  «        ‚|r|dk    r||d<    | 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.
            tool_choice: Currently this can only be auto for this chat model.
            **kwargs: Any additional parameters to pass to the
                :class:`~langchain.runnable.Runnable` constructor.
        zglm-4vz.glm-4v currently does not support tool callingc                ó,   — g | ]}t          |¦  «        ‘ŒS r•   r/   )r¿   rw   s     r>   rÁ   z*ChatZhipuAI.bind_tools.<locals>.<listcomp>ß  s!   € ÐJÐJÐJ¸DÕ1°$Ñ7Ô7ÐJÐJÐJr@   Úautoz6ChatZhipuAI currently only supports `auto` tool choicer  r  r•   )r©   r_   Úbind)r—   r  r  rE   Úformatted_toolss        r>   Ú
bind_toolszChatZhipuAI.bind_toolsÉ  s�   € ð& Œ?˜hÒ&Ð&ÝÐMÑNÔNÐNàJÐJÀEÐJÑJÔJˆØð 	0˜;¨&Ò0Ð0ÝÐUÑVÔVÐVØð 	0˜[¨FÒ2Ð2Ø$/ˆF�=Ñ!ØˆtŒyÐ9Ð9˜Ð9°&Ð9Ð9Ð9r@   Úfunction_calling)rB   Úinclude_rawÚschemaú&Optional[Union[Dict, Type[BaseModel]]]rB   ú(Literal['function_calling', 'json_mode']r  ú4Runnable[LanguageModelInput, Union[Dict, BaseModel]]c               ó.  — |rt          d|› �¦  «        ‚t          |¦  «        }|dk    rk|€t          d¦  «        ‚t          |¦  «        d         d         }|                      |gd¬¦  «        }|rt	          |gd	¬
¦  «        }n%t          |d	¬¦  «        }nt          d|› d�¦  «        ‚|rht          j        t          d¦  «        |z  d„ ¬¦  «        }	t          j        d„ ¬¦  «        }
|	 	                    |
gd¬¦  «        }t          |¬¦  «        |z  S ||z  S )a7  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.
            method: The method for steering model generation, either "function_calling"
                or "json_mode". ZhipuAI only supports "function_calling" which
                converts the schema to a OpenAI function and the model will make use of the
                function-calling API.
            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.

        Example: Function-calling, Pydantic schema (method="function_calling", include_raw=False):
            .. code-block:: python

                from langchain_community.chat_models import ChatZhipuAI
                from pydantic import BaseModel

                class AnswerWithJustification(BaseModel):
                    '''An answer to the user question along with justification for the answer.'''
                    answer: str
                    justification: str

                llm = ChatZhipuAI(temperature=0)
                structured_llm = llm.with_structured_output(AnswerWithJustification)

                structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers")
                # -> AnswerWithJustification(
                #     answer='A pound of bricks and a pound of feathers weigh the same.'
                #     justification="Both a pound of bricks and a pound of feathers have been defined to have the same weight. The 'pound' is a unit of weight, so any two things that are described as weighing a pound will weigh the same."
                # )

        Example: Function-calling, Pydantic schema (method="function_calling", include_raw=True):
            .. code-block:: python

                from langchain_community.chat_models import ChatZhipuAI
                from pydantic import BaseModel

                class AnswerWithJustification(BaseModel):
                    '''An answer to the user question along with justification for the answer.'''
                    answer: str
                    justification: str

                llm = ChatZhipuAI(temperature=0)
                structured_llm = llm.with_structured_output(AnswerWithJustification, include_raw=True)

                structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers")
                # -> {
                #     'raw': AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_01htjn3cspevxbqc1d7nkk8wab', 'function': {'arguments': '{"answer": "A pound of bricks and a pound of feathers weigh the same.", "justification": "Both a pound of bricks and a pound of feathers have been defined to have the same weight. The 'pound' is a unit of weight, so any two things that are described as weighing a pound will weigh the same.", "unit": "pounds"}', 'name': 'AnswerWithJustification'}, 'type': 'function'}]}, id='run-456beee6-65f6-4e80-88af-a6065480822c-0'),
                #     'parsed': AnswerWithJustification(answer='A pound of bricks and a pound of feathers weigh the same.', justification="Both a pound of bricks and a pound of feathers have been defined to have the same weight. The 'pound' is a unit of weight, so any two things that are described as weighing a pound will weigh the same."),
                #     'parsing_error': None
                # }

        Example: Function-calling, dict schema (method="function_calling", include_raw=False):
            .. code-block:: python

                from langchain_community.chat_models import ChatZhipuAI
                from pydantic import BaseModel
                from langchain_core.utils.function_calling import convert_to_openai_tool

                class AnswerWithJustification(BaseModel):
                    '''An answer to the user question along with justification for the answer.'''
                    answer: str
                    justification: str

                dict_schema = convert_to_openai_tool(AnswerWithJustification)
                llm = ChatZhipuAI(temperature=0)
                structured_llm = llm.with_structured_output(dict_schema)

                structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers")
                # -> {
                #     'answer': 'A pound of bricks and a pound of feathers weigh the same.',
                #     'justification': "Both a pound of bricks and a pound of feathers have been defined to have the same weight. The 'pound' is a unit of weight, so any two things that are described as weighing a pound will weigh the same.", 'unit': 'pounds'}
                # }

        zReceived unsupported arguments r  NzJschema must be specified when method is 'function_calling'. Received None.Úfunctionrx   r  r  T)r  Úfirst_tool_only)Úkey_namer  zVUnrecognized method argument. Expected 'function_calling'.
                Received: 'ú'Úrawc                ó   — d S r:   r•   ©Ú_s    r>   ú<lambda>z4ChatZhipuAI.with_structured_output.<locals>.<lambda>u  s   € ÐRV€ r@   )ÚparsedÚparsing_errorc                ó   — d S r:   r•   r  s    r>   r!  z4ChatZhipuAI.with_structured_output.<locals>.<lambda>w  s   € Àd€ r@   )r"  r#  )Úexception_key)r  )r_   r?   r0   r  r&   r%   r,   Úassignr   Úwith_fallbacksr+   )r—   r  rB   r  rE   Úis_pydantic_schemaÚ	tool_nameÚllmÚoutput_parserÚparser_assignÚparser_noneÚparser_with_fallbacks               r>   Úwith_structured_outputz"ChatZhipuAI.with_structured_outputæ  sŒ  € ðf ð 	IÝÐG¸vÐGÐGÑHÔHÐHÝ/°Ñ7Ô7ÐØÐ'Ò'Ð'Øˆ~Ý ð%ñô ð õ /¨vÑ6Ô6°zÔBÀ6ÔJˆIØ—/’/ 6 (¸�/Ñ?Ô?ˆCØ!ð Ý2EØ!˜(Ø$(ð3ñ 3ô 3��õ
 !9Ø&¸ð!ñ !ô !��õ ð(Ø"ð(ð (ð (ñô ð ð
 ð 
	'Ý/Ô6Ý! %Ñ(Ô(¨=Ñ8ÈÈðñ ô ˆMõ .Ô4¸N¸NÐKÑKÔKˆKØ#0×#?Ò#?Ø�¨_ð $@ñ $ô $Ð õ  3Ð'Ñ'Ô'Ð*>Ñ>Ð>à˜Ñ&Ð&r@   )r7   r‘   )r7   r™   )r7   rk   )r7   rC   )r´   rk   r7   r	   )r¸   r¹   rº   r»   r7   r¼   )rM   rÄ   r7   r)   )NNN)r¸   r¹   rº   r»   rÒ   rÓ   rK   rÔ   rE   r	   r7   r)   )NN)
r¸   r¹   rº   r»   rÒ   rÓ   rE   r	   r7   rë   )r¸   r¹   rº   r»   rÒ   rþ   rK   rÔ   rE   r	   r7   r)   )
r¸   r¹   rº   r»   rÒ   rþ   rE   r	   r7   r  )r  r	  r  r
  rE   r	   r7   r  r:   )
r  r  rB   r  r  r8   rE   r	   r7   r  ) r�   Ú
__module__Ú__qualname__Ú__doc__Úpropertyr˜   ÚclassmethodrŸ   r£   r¥   r¬   r3   r“   Ú__annotations__r¡   r©   rŠ   r‹   rª   r¨   r2   Úmodel_configr4   r·   rÃ   rÑ   rê   râ   r  r   r  r/  r•   r@   r>   r�   r�   ì   s÷  € € € € € € ðið iðV ð6ð 6ð 6ñ „Xð6ð ð7ð 7ð 7ñ „[ð7ð ðð ð ñ „Xðð ðð ð ñ „Xðð ð	ð 	ð 	ñ „Xð	ð &+ U°4¸yÐ%IÑ%IÔ%I€OÐIÐIÐIÑIØPØ&+ e°DÀ
Ð&KÑ&KÔ&KÐÐKÐKÐKÑKðð !& ¨g¸WÐ EÑ EÔ E€JÐEÐEÐEÑEðð
 €KÐÐÐÑðð €EÐÐÐÑðð €IÐÐÐÑØ/Ø $€JÐ$Ð$Ð$Ñ$Ø/à�:Øðñ ô €Lð €_˜(Ð#Ñ#Ô#Øðð ð ñ „[ñ $Ô#ðð%ð %ð %ð %ðJð Jð Jð Jð( %)Ø:>Ø!%ð#9ð #9ð #9ð #9ð #9ðP %)Ø:>ð	8ð 8ð 8ð 8ð 8ðz %)Ø?CØ!%ð"9ð "9ð "9ð "9ð "9ðN %)Ø?Cð	7ð 7ð 7ð 7ð 7ð~ ð:ð :ð :ð :ð :ð :ð> :>ðW'ð <NØ!ðW'ð W'ð W'ð W'ð W'ð W'ð W'ð W'r@   r�   )r6   r	   r7   r8   )
rA   r	   rB   rC   rD   rC   rE   r	   r7   r   )
rA   r	   rB   rC   rD   rC   rE   r	   r7   r   )rQ   rC   r7   rC   )rj   rk   r7   r   )r}   r   r7   rk   )rj   rk   r„   r…   r7   r   )rh   rk   r7   rˆ   )Tr2  Ú
__future__r   rá   Úloggingrb   Úcollections.abcr   r   Ú
contextlibr   r   Úoperatorr   Útypingr	   r
   r   r   r   r   r   r   r   r   Úlangchain_core.callbacksr   r   Úlangchain_core.language_modelsr   Ú*langchain_core.language_models.chat_modelsr   r   r   Úlangchain_core.messagesr   r   r   r   r   r   r   r    r!   r"   r#   Ú"langchain_core.output_parsers.baser$   Ú*langchain_core.output_parsers.openai_toolsr%   r&   Úlangchain_core.outputsr'   r(   r)   Úlangchain_core.runnablesr*   r+   r,   Úlangchain_core.toolsr-   Úlangchain_core.utilsr.   Ú%langchain_core.utils.function_callingr0   Úpydanticr1   r2   r3   r4   Ú	getLoggerr�   Úloggerrc   r¶   r?   rN   rP   ri   r|   rƒ   r‡   rŽ   r�   r•   r@   r>   ú<module>rK     sÒ  ðØ "Ð "à "Ð "Ð "Ð "Ð "Ð "à €€€Ø €€€Ø €€€Ø 3Ð 3Ð 3Ð 3Ð 3Ð 3Ð 3Ð 3Ø :Ð :Ð :Ð :Ð :Ð :Ð :Ð :Ø Ð Ð Ð Ð Ð ðð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ðð ð ð ð ð ð ð ð >Ð =Ð =Ð =Ð =Ð =ðð ð ð ð ð ð ð ð ð ð
ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð @Ð ?Ð ?Ð ?Ð ?Ð ?ðð ð ð ð ð ð ð ð SÐ RÐ RÐ RÐ RÐ RÐ RÐ RÐ RÐ RØ OÐ OÐ OÐ OÐ OÐ OÐ OÐ OÐ OÐ OØ )Ð )Ð )Ð )Ð )Ð )Ø 5Ð 5Ð 5Ð 5Ð 5Ð 5Ø HÐ HÐ HÐ HÐ HÐ HØ BÐ BÐ BÐ BÐ BÐ BÐ BÐ BÐ BÐ BÐ BÐ Bà	ˆÔ	˜8Ñ	$Ô	$€àÐ ØJÐ ð@ð @ð @ð @ð ð$ð $ð $ñ „ð$ð$ ð$ð $ð $ñ Ôð$ð("ð "ð "ð "ðJ3ð 3ð 3ð 3ð2ð ð ð ð<*ð *ð *ð *ð*7ð 7ð 7ð 7ðQ
'ð Q
'ð Q
'ð Q
'ð Q
'�-ñ Q
'ô Q
'ð Q
'ð Q
'ð Q
'r@   