Ë
    òÏj�#  ã                   ó  — 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%y)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/gaurav-v2/venv/lib/python3.12/site-packages/langgraph/prebuilt/tool_validator.pyÚ_default_format_errorr   "   s   € ô �5‹kˆ]ÐIÐ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¬«       |xs t        | _        i | _        |D �]O  }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        «      rFt        |t        t        f«      r0t!        t        t           |«      | j
                  |j"                  <   �Œt%        |«      r't'        d	|«      }|| j
                  |j"                  <   �Œ:t        d
t        |«      › d�«      ‚ y)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   sl  ø€ ô. 	‰Ñ˜Ÿ™ T°¸4ÀuÐÔMØ)ÒBÔ-BˆÔØ;=ˆÔÜˆFÜ˜&¤(Ô+Ø×%Ñ%Ð-Ü$Ø §¡˜}Ð,RÐSóð ô $Ø×&Ñ&¬ôä.¨v×/AÑ/AÔBÜ$ðØ%Ÿ{™{˜mÐ+>¸v×?QÑ?QÐ>RÐRSðUóð ð 5;×4FÑ4F�×$Ñ$ V§[¡[Ò1Ü˜F¤DÔ)¬jØœ¤KÐ0ô/ô 9=¼TÄ)¹_ÈfÓ8U�×$Ñ$ V§_¡_Ó5Ü˜&Ô!Ü8¸ÀvÓN�
Ø8B�×$Ñ$ V§_¡_Ó5ä ØfÔgkÐlrÓgsÐftÐtuÐvóð ñ- r   Úinputc                 ó¸   — t        |t        «      rd}|}n"|j                  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¨   si   € ô �eœTÔ"Ø ˆKØ"‰HØŸ™ :¨rÓ2Ð2ˆXÐ2Ø ‰KäÐ8Ó9Ð9Ø& r™lˆÜ˜'¤9Ô-ÜÐ?Ó@Ð@Ø˜GÐ#Ð#r   Úconfigc                 óö   ‡ — ‰ j                  |«      \  }}dt        dt        fˆ fd„}t        |«      5 }g |j	                  ||j
                  «      ¢}|dk(  r|cddd«       S d|icddd«       S # 1 sw Y   yxY w)z*Validate and run tool calls synchronously.r   r   c           
      ó  •— ‰j                   | d      }	 t        |t        «      r%|j                  | d   «      }|j	                  «       }nMt        |t
        «      r%|j                  | d   «      }|j                  «       }nt        dt        |«      › d�«      ‚t        || d   t        t        | d   «      ¬«      S # t        t        f$ r@}t        ‰j                  || |«      | 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¾   s  ø€ Ø×)Ñ)¨$¨v©,Ñ7ˆFðÜ˜f¤iÔ0Ø#×2Ñ2°4¸±<Ó@�FØ$×4Ñ4Ó6‘GÜ ¬Ô4Ø#Ÿ_™_¨T°&©\Ó:�FØ$Ÿk™k›m‘Gä$Ø3´D¸³L°>ÐAeÐfóð ô #Ø#Ø˜f™Ü!%¤c¨4°©:Ó!6ôð øô
 $Ô%6Ð7ò Ü"Ø ×.Ñ.¨q°$¸Ó?Ø˜f™Ü!%¤c¨4°©:Ó!6Ø'1°4Ð&8ô	õ ûðús   •B#B9 Â9DÃ5DÃ=DÄD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Ñˆ�Wð	œ(ð 	¤{õ 	ô4 % VÔ,°ØB˜Ÿ™ W¨g×.@Ñ.@ÓAÐBˆGØ˜fÒ$Ø÷ -Ñ,ð
 # GÐ,÷ -×,Ò,ús   ³%A/Á"A/Á/A8)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    +   sã   ø„ ñ
BðR Ø Ø!%ò2à˜( T¨)¡_Ñ4°xÑ?Ñ@ð2ð  ¨x¸¸i¹ÐIÈ3ÐNÑOØ
ñð	2ð ð2ð �3‰i˜$Ñð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ß FÝ ?Ý :Ý :ß /Ý 0Ý <Ý (ðKØðKà
ðKð �‰O˜d ;Ñ/Ñ/ðKð 	ó	Kñ ØvØ(ôôn-Ð%ó n-ó	ñn-r   