ó
    ýÞ j�#  ã                   ó  • S r SSKJrJr  SSKJrJr  SSKJrJ	r	J
r
Jr  SSKJr  SSKJr  SSKJrJr  SSKJr  SS	KJr  SS
KJr  SSKJrJr  SSKJr  SSKJr  SSKJ r   S\!S\
S\"\   \"\   -  S\#4S jr$\ " S\S9 " S S\5      5       r%g)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                 ó   • [        U 5       S3$ )z"Default error formatting function.z-

Respond after fixing all validation errors.)Úrepr)r   r   r   s      Ú[/var/www/html/gaurav/venv/lib/python3.13/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                   óî   ^ • \ rS rSrSrSSSS.S\\\\   -  \	-     S\	\
\\\   /\4   S-  S\S	\\   S-  S
S4
U 4S jjjrS\\   \\\4   -  S
\\\4   4S jrS\\   \\\4   -  S\S
\4S jrSrU =r$ )ÚValidationNodeé+   a2	  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U ]  U R                  SX4SS9  U=(       d    [        U l        0 U l        U GHp  n[        U[        5      (       aª  UR                  c  [        SUR                   S35      e[        UR                  [        5      (       a  [        UR                  5      (       d&  [        SUR                   SUR                   S35      eUR                  U R
                  UR                  '   MÃ  [        U[        5      (       aL  [        U[        [        45      (       a1  [!        [        [           U5      U R
                  UR"                  '   GM$  [%        U5      (       a'  ['        S	U5      nX`R
                  UR"                  '   GM[  [        S
[        U5       S35      e   g)at  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,   ÚValidationNode.__init__t   s~  ø€ ô. 	‰Ñ˜Ÿ™ T°ÀuÐÑMØ)×BÔ-BˆÔØ;=ˆÔÜˆFÜ˜&¤(×+Ñ+Ø×%Ñ%Ñ-Ü$Ø §¡˜}Ð,RÐSóð ô $Ø×&Ñ&¬÷ñ ä.¨v×/AÑ/A×BÑ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                 óÔ   • [        U[        5      (       a  SnUnO'UR                  S/ 5      =n(       a  SnO[        S5      eUS   n[        U[        5      (       d  [        S5      eX$4$ )z*Extract the last AIMessage from the input.ÚlistÚmessagesÚdictzNo message found in inputéÿÿÿÿz Last message is not an AIMessage)r0   r>   Úgetr2   r   )r8   r<   Úoutput_typer?   Úmessages        r   Ú_get_messageÚValidationNode._get_message¨   sm   € ô �eœT×"Ñ"Ø ˆKØ"‰HØŸ™ :¨rÓ2Ð2ˆXÕ2Ø ‰KäÐ8Ó9Ð9Ø& r™lˆÜ˜'¤9×-Ñ-ÜÐ?Ó@Ð@ØÐ#Ð#r   Úconfigc                 ó  ^ • T R                  U5      u  p4S[        S[        4U 4S jjn[        U5       n/ UR	                  XTR
                  5      QnUS:X  a  UsSSS5        $ SU0sSSS5        $ ! , (       d  f       g= f)z*Validate and run tool calls synchronously.r   r   c           
      ó  >• TR                   U S      n [        U[        5      (       a%  UR                  U S   5      nUR	                  5       nOR[        U[
        5      (       a%  UR                  U S   5      nUR                  5       nO[        S[        U5       S35      e[        UU S   [        [        U S   5      S9$ ! [        [        4 a<  n[        TR                  X@U5      U S   [        [        U S   5      SS0S	9s S nA$ S nAff = f)
Nr$   ÚargszUnsupported schema type: z$. Expected BaseModel or BaseModelV1.Úid)Úcontentr$   Útool_call_idÚis_errorT)rL   r$   rM   Úadditional_kwargs)r/   r4   r   Úmodel_validateÚmodel_dump_jsonr5   ÚvalidateÚjsonr2   r3   r
   r   Ústrr   ÚValidationErrorV1r.   )r   r   ÚoutputrL   Úer8   s        €r   Úrun_oneÚ%ValidationNode._func.<locals>.run_one¾   s  ø€ Ø×)Ñ)¨$¨v©,Ñ7ˆFðÜ˜f¤i×0Ñ0Ø#×2Ñ2°4¸±<Ó@�FØ$×4Ñ4Ó6‘GÜ ¬×4Ñ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*C  Ã DÃ1DÄDÄDr>   Nr?   )rE   r	   r
   r   ÚmapÚ
tool_calls)r8   r<   rG   rC   rD   rX   ÚexecutorÚoutputss   `       r   r-   ÚValidationNode._func¸   sy   ø€ ð  $×0Ñ0°Ó7Ñˆð	œ(ð 	¤{÷ 	ô4 % VÔ,°ØB˜Ÿ™ W×.@Ñ.@ÓAÐBˆGØ˜fÓ$Ø÷ -Ñ,ð
 # GÐ,÷ -×,×,ús   ´%A0Á#A0Á0
A>)r.   r/   )r6   Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__r   r   r3   r   r   ÚBaseExceptionr	   rT   r>   r,   r   r@   r   Útupler   rE   r   r-   Ú__static_attributes__Ú__classcell__)r:   s   @r   r    r    +   sí   ø† ñ
BðR Ø Ø!%ò2à˜( T¨)¡_Ñ4°xÑ?Ñ@ð2ð  ¨x¸¸i¹ÐIÈ3ÐNÑOØ
ñð	2ð ð2ð �3‰i˜$Ñð2ð 
÷2ð 2ðh$Ø˜*Ñ%¨¨S°#¨X©Ñ6ð$à	ˆs�Iˆ~Ñ	ô$ð %-Ø˜*Ñ%¨¨S°#¨X©Ñ6ð%-Ø@Nð%-à	÷%-ò %-r   r    N)&rb   Ú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.v1r5   rU   Útyping_extensionsr   rc   r3   rT   r   r    © r   r   Ú<module>rt      s§   ðñ÷ /÷÷
ó õõ Dß FÝ ?Ý :Ý :ß /Ý 0Ý <Ý (ðKØðKà
ðKð �‰O˜d ;Ñ/Ñ/ðKð 	ô	Kñ ØvØ(ñôn-Ð%ó n-ó	ñn-r   