§
    ™Štj�#  ã                   ó:  — d Z ddlmZmZ ddlmZmZ ddlmZm	Z	m
Z
mZ ddlmZ ddlmZ ddlmZmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZ ddlmZ ddlmZ ddlm Z  de!de
de"e         e"e         z  de#fd„Z$ e de¬¦  «         G d„ de¦  «        ¦   «         Z%dS )aº  This module provides a ValidationNode class that can be used to validate tool calls
in a langchain graph. It applies a pydantic schema to tool_calls in the models' outputs,
and returns a ToolMessage with the validated content. If the schema is not valid, it
returns a ToolMessage with the error message. The ValidationNode can be used in a
StateGraph with a "messages" key. If multiple tool calls are requested, they will be run in parallel.
é    )ÚCallableÚSequence)ÚAnyÚcast)Ú	AIMessageÚ
AnyMessageÚToolCallÚToolMessage)ÚRunnableConfig)Úget_executor_for_config)ÚBaseToolÚcreate_schema_from_function)Úis_basemodel_subclass)ÚRunnableCallable)ÚLangGraphDeprecatedSinceV10)Ú	BaseModelÚValidationError)r   )r   )Ú
deprecatedÚerrorÚcallÚschemaÚreturnc                 ó&   — t          | ¦  «        › d�S )z"Default error formatting function.z-

Respond after fixing all validation errors.)Úrepr)r   r   r   s      ú_/var/www/html/CA-Chatbot/venv/lib/python3.11/site-packages/langgraph/prebuilt/tool_validator.pyÚ_default_format_errorr   "   s   € õ �5‰kŒkÐJÐJÐJÐJó    zpValidationNode is deprecated. Please use `create_agent` from `langchain.agents` with custom tool error handling.)Úcategoryc                   ó  ‡ — e Zd ZdZddddœdeeee         z  ez           dee	e
ee         gef         dz  dedee         dz  d	df
ˆ fd
„Zdee         eeef         z  d	eeef         fd„Zdee         eeef         z  ded	efd„Zˆ xZS )ÚValidationNodeaþ	  A node that validates all tools requests from the last `AIMessage`.

    It can be used either in `StateGraph` with a `'messages'` key.

    !!! note

        This node does not actually **run** the tools, it only validates the tool calls,
        which is useful for extraction and other use cases where you need to generate
        structured output that conforms to a complex schema without losing the original
        messages and tool IDs (for use in multi-turn conversations).

    Returns:
        (Union[Dict[str, List[ToolMessage]], Sequence[ToolMessage]]): A list of
            `ToolMessage` objects with the validated content or error messages.

    Example:
        ```python title="Example usage for re-prompting the model to generate a valid response:"
        from typing import Literal, Annotated
        from typing_extensions import TypedDict

        from langchain_anthropic import ChatAnthropic
        from pydantic import BaseModel, field_validator

        from langgraph.graph import END, START, StateGraph
        from langgraph.prebuilt import ValidationNode
        from langgraph.graph.message import add_messages

        class SelectNumber(BaseModel):
            a: int

            @field_validator("a")
            def a_must_be_meaningful(cls, v):
                if v != 37:
                    raise ValueError("Only 37 is allowed")
                return v

        builder = StateGraph(Annotated[list, add_messages])
        llm = ChatAnthropic(model="claude-3-5-haiku-latest").bind_tools([SelectNumber])
        builder.add_node("model", llm)
        builder.add_node("validation", ValidationNode([SelectNumber]))
        builder.add_edge(START, "model")

        def should_validate(state: list) -> Literal["validation", "__end__"]:
            if state[-1].tool_calls:
                return "validation"
            return END

        builder.add_conditional_edges("model", should_validate)

        def should_reprompt(state: list) -> Literal["model", "__end__"]:
            for msg in state[::-1]:
                # None of the tool calls were errors
                if msg.type == "ai":
                    return END
                if msg.additional_kwargs.get("is_error"):
                    return "model"
            return END

        builder.add_conditional_edges("validation", should_reprompt)

        graph = builder.compile()
        res = graph.invoke(("user", "Select a number, any number"))
        # Show the retry logic
        for msg in res:
            msg.pretty_print()
        ```
    NÚ
validation)Úformat_errorÚnameÚtagsÚschemasr"   r#   r$   r   c                ó  •— t          ¦   «                              | j        d||d¬¦  «         |pt          | _        i | _        |D �]G}t          |t          ¦  «        r‚|j        €t          d|j
        › d�¦  «        ‚t          |j        t          ¦  «        rt          |j        ¦  «        s t          d|j
        › d|j        › d�¦  «        ‚|j        | j        |j
        <   Œšt          |t          ¦  «        rJt          |t          t          f¦  «        r.t!          t          t                   |¦  «        | j        |j        <   Œùt%          |¦  «        r!t'          d	|¦  «        }|| j        |j        <   �Œ)t          d
t          |¦  «        › d�¦  «        ‚dS )aÔ  Initialize the ValidationNode.

        Args:
            schemas: A list of schemas to validate the tool calls with. These can be
                any of the following:
                - A pydantic BaseModel class
                - A BaseTool instance (the args_schema will be used)
                - A function (a schema will be created from the function signature)
            format_error: A function that takes an exception, a ToolCall, and a schema
                and returns a formatted error string. By default, it returns the
                exception repr and a message to respond after fixing validation errors.
            name: The name of the node.
            tags: A list of tags to add to the node.
        NF)r#   r$   ÚtracezTool z& does not have an args_schema defined.zVValidation node only works with tools that have a pydantic BaseModel args_schema. Got z with args_schema: ú.Ú
ValidationzPUnsupported input to ValidationNode. Expected BaseModel, tool or function. Got: )ÚsuperÚ__init__Ú_funcr   Ú_format_errorÚschemas_by_nameÚ
isinstancer   Úargs_schemaÚ
ValueErrorr#   Útyper   Ú
issubclassr   ÚBaseModelV1r   Ú__name__Úcallabler   )Úselfr%   r"   r#   r$   r   Ú
base_modelÚ	__class__s          €r   r+   zValidationNode.__init__t   sÉ  ø€ õ. 	‰Œ×Ò˜œ T°¸4ÀuÐÑMÔMÐMØ)ÐBÕ-BˆÔØ;=ˆÔØð 	ñ 	ˆFÝ˜&¥(Ñ+Ô+ð ØÔ%Ð-Ý$ØS ¤ÐSÐSÐSñô ð õ $ØÔ&­ñô ð å.¨vÔ/AÑBÔBðõ %ðUØ%œ{ðUð UØ?EÔ?QðUð Uð Uñô ð ð 5;Ô4F�Ô$ V¤[Ñ1Ð1Ý˜F¥DÑ)Ô)ð 
­jØ�¥KÐ0ñ/ô /ð 
õ 9=½TÅ)¼_ÈfÑ8UÔ8U�Ô$ V¤_Ñ5Ð5Ý˜&Ñ!Ô!ð Ý8¸ÀvÑNÔN�
Ø8B�Ô$ V¤_Ñ5Ñ5å ØvÕgkÐlrÑgsÔgsÐvÐvÐvñô ð ð-	ð 	r   Úinputc                 óê   — t          |t          ¦  «        rd}|}n*|                     dg ¦  «        x}rd}nt          d¦  «        ‚|d         }t          |t          ¦  «        st          d¦  «        ‚||fS )z*Extract the last AIMessage from the input.ÚlistÚmessagesÚdictzNo message found in inputéÿÿÿÿz Last message is not an AIMessage)r/   r<   Úgetr1   r   )r7   r:   Úoutput_typer=   Úmessages        r   Ú_get_messagezValidationNode._get_message¨   s‰   € õ �e�TÑ"Ô"ð 	:Ø ˆKØ"ˆHˆHØŸš :¨rÑ2Ô2Ð2ˆXð 	:Ø ˆKˆKåÐ8Ñ9Ô9Ð9Ø& rœlˆÝ˜'¥9Ñ-Ô-ð 	AÝÐ?Ñ@Ô@Ð@Ø˜GÐ#Ð#r   Úconfigc                 ó  ‡ — ‰                       |¦  «        \  }}dt          dt          fˆ fd„}t          |¦  «        5 }g |                     ||j        ¦  «        ¢}|dk    r|cddd¦  «         S d|icddd¦  «         S # 1 swxY w Y   dS )z*Validate and run tool calls synchronously.r   r   c           
      ó°  •— ‰j         | d                  }	 t          |t          ¦  «        r0|                     | d         ¦  «        }|                     ¦   «         }net          |t
          ¦  «        r0|                     | d         ¦  «        }|                     ¦   «         }n t          dt          |¦  «        › d�¦  «        ‚t          || d         t          t          | d         ¦  «        ¬¦  «        S # t          t          f$ rS}t          ‰                     || |¦  «        | d         t          t          | d         ¦  «        ddi¬	¦  «        cY d }~S d }~ww xY w)
Nr#   ÚargszUnsupported schema type: z$. Expected BaseModel or BaseModelV1.Úid)Úcontentr#   Útool_call_idÚis_errorT)rI   r#   rJ   Úadditional_kwargs)r.   r3   r   Úmodel_validateÚmodel_dump_jsonr4   ÚvalidateÚjsonr1   r2   r
   r   Ústrr   ÚValidationErrorV1r-   )r   r   ÚoutputrI   Úer7   s        €r   Úrun_onez%ValidationNode._func.<locals>.run_one¾   sq  ø€ ØÔ)¨$¨v¬,Ô7ˆFðÝ˜f¥iÑ0Ô0ð 	Ø#×2Ò2°4¸´<Ñ@Ô@�FØ$×4Ò4Ñ6Ô6�G�GÝ ­Ñ4Ô4ð Ø#Ÿ_š_¨T°&¬\Ñ:Ô:�FØ$Ÿkšk™mœm�G�Gå$ØfµD¸±L´LÐfÐfÐfñô ð õ #Ø#Ø˜fœÝ!%¥c¨4°¬:Ñ!6Ô!6ðñ ô ð øõ
 $Õ%6Ð7ð ð ð Ý"Ø ×.Ò.¨q°$¸Ñ?Ô?Ø˜fœÝ!%¥c¨4°¬:Ñ!6Ô!6Ø'1°4Ð&8ð	ñ ô ð ð ð ð ð ð øøøøðøøøs   –CC1 Ã1EÄAEÅ
EÅEr<   Nr=   )rC   r	   r
   r   ÚmapÚ
tool_calls)r7   r:   rD   rA   rB   rU   ÚexecutorÚoutputss   `       r   r,   zValidationNode._func¸   s  ø€ ð  $×0Ò0°Ñ7Ô7Ñˆ�Wð	�(ð 	¥{ð 	ð 	ð 	ð 	ð 	ð 	õ4 % VÑ,Ô,ð 	-°ØB˜Ÿš W¨gÔ.@ÑAÔAÐBˆGØ˜fÒ$Ð$Øð	-ð 	-ð 	-ð 	-ñ 	-ô 	-ð 	-ð 	-ð
 # GÐ,ð	-ð 	-ð 	-ð 	-ñ 	-ô 	-ð 	-ð 	-ð 	-ð 	-ð 	-ð 	-øøøð 	-ð 	-ð 	-ð 	-ð 	-ð 	-s   ½%A?Á/A?Á?BÂB)r5   Ú
__module__Ú__qualname__Ú__doc__r   r   r2   r   r   ÚBaseExceptionr	   rQ   r<   r+   r   r>   r   Útupler   rC   r   r,   Ú__classcell__)r9   s   @r   r    r    +   sF  ø€ € € € € ð
Bð BðR Ø Ø!%ð2ð 2ð 2à˜( T¨)¤_Ñ4°xÑ?Ô@ð2ð  ¨x¸¸i¼ÐIÈ3ÐNÔOØ
ñð	2ð ð2ð �3Œi˜$Ñð2ð 
ð2ð 2ð 2ð 2ð 2ð 2ðh$Ø˜*Ô%¨¨S°#¨X¬Ñ6ð$à	ˆs�Iˆ~Ô	ð$ð $ð $ð $ð %-Ø˜*Ô%¨¨S°#¨X¬Ñ6ð%-Ø@Nð%-à	ð%-ð %-ð %-ð %-ð %-ð %-ð %-ð %-r   r    N)&r\   Úcollections.abcr   r   Útypingr   r   Úlangchain_core.messagesr   r   r	   r
   Úlangchain_core.runnablesr   Úlangchain_core.runnables.configr   Úlangchain_core.toolsr   r   Úlangchain_core.utils.pydanticr   Úlanggraph._internal._runnabler   Úlanggraph.warningsr   Úpydanticr   r   Úpydantic.v1r4   rR   Útyping_extensionsr   r]   r2   rQ   r   r    © r   r   ú<module>rm      s  ððð ð /Ð .Ð .Ð .Ð .Ð .Ð .Ð .ðð ð ð ð ð ð ð ð
ð ð ð ð ð ð ð ð ð ð ð ðð ð ð ð ð ð DÐ CÐ CÐ CÐ CÐ CØ FÐ FÐ FÐ FÐ FÐ FÐ FÐ FØ ?Ð ?Ð ?Ð ?Ð ?Ð ?Ø :Ð :Ð :Ð :Ð :Ð :Ø :Ð :Ð :Ð :Ð :Ð :Ø /Ð /Ð /Ð /Ð /Ð /Ð /Ð /Ø 0Ð 0Ð 0Ð 0Ð 0Ð 0Ø <Ð <Ð <Ð <Ð <Ð <Ø (Ð (Ð (Ð (Ð (Ð (ðKØðKà
ðKð �ŒO˜d ;Ô/Ñ/ðKð 	ð	Kð Kð Kð Kð €ØvØ(ðñ ô ðn-ð n-ð n-ð n-ð n-Ð%ñ n-ô n-ñ	ô ðn-ð n-ð n-r   