§
    œŠtj´   ã                  óH  — d Z ddlmZ ddlmZ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 erXd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 eeegeee         z  dz  f         Z	 eeegeeee         z  dz           f         Z	  G d„ deee         eef         ¦  «        ZdS )z!Tool error middleware for agents.é    )Úannotations)ÚTYPE_CHECKINGÚAnyÚcast)ÚToolMessage)ÚGraphBubbleUp)ÚAgentMiddlewareÚ
AgentStateÚContextTÚ	ResponseT)Ú	AwaitableÚCallable)ÚContentBlock)ÚCommand)ÚToolCallRequest)ÚBaseToolNc                  óH   ‡ — e Zd ZdZ	 ddddœdˆ fd„Zdd„Zdd„Zdd„Zˆ xZS )ÚToolErrorMiddlewareus  Return selected tool-execution exceptions to the model as error `ToolMessage`s.

    `on_error` is called for each exception raised by tool execution. Return content
    (a `str` or a list of content blocks) to convert the exception into a
    `ToolMessage(status="error")`; return `None` â€” or simply don't return â€” to let the
    exception propagate (halting the run). Handling is therefore opt-in â€” exceptions you
    do not return content for propagate unchanged, so arbitrary internal exceptions are
    never serialized to the model or end user unless you choose to surface them.

    Langgraph control-flow signals (interrupts, parent commands) always propagate and
    never reach `on_error`.

    Prefer returning content that names the exception type over the raw exception message,
    which may carry sensitive or internal detail.

    Provide at least one of `on_error` or `aon_error`. `aon_error` handles errors on the
    async execution path (falling back to `on_error` when omitted); the sync path only
    ever calls `on_error`. For async-only usage, pass `aon_error` alone â€” running such a
    middleware on the sync path raises, since the async handler cannot be awaited there.

    This middleware does not retry. For retries, compose with `ToolRetryMiddleware`
    placed *inner* and configured with `on_failure="error"` so exceptions reach this
    middleware.

    This middleware only sees exceptions raised by tool *execution*. Argument-binding
    and validation errors are handled upstream by `ToolNode` (converted to an error
    `ToolMessage` before the tool runs), so they do not reach `on_error`.

    Example:
        ```python
        from langchain.agents import create_agent
        from langchain.agents.middleware import ToolErrorMiddleware


        def on_error(exc: Exception, request: ToolCallRequest) -> str | None:
            if isinstance(exc, ValueError):
                return f"`{request.tool_call['name']}` failed; fix the input and retry."
            return None  # propagate everything else


        agent = create_agent(model, tools=[...], middleware=[ToolErrorMiddleware(on_error)])
        ```
    N)Ú	aon_errorÚtoolsÚon_errorúOnError | Noner   úAOnError | Noner   úlist[BaseTool | str] | NoneÚreturnÚNonec               óÖ   •— t          ¦   «                              ¦   «          |€|€d}t          |¦  «        ‚|| _        || _        |  |�d„ |D ¦   «         | _        nd| _        g | _        dS )u   Initialize `ToolErrorMiddleware`.

        Args:
            on_error: Handler called for each exception raised by tool execution. Return
                content (`str` or list of content blocks) to convert the exception into an
                error `ToolMessage`. Return `None` â€” or simply don't return â€” to let the
                exception propagate. Falling through without a return therefore re-raises,
                so handle only the exceptions you mean to. Receives the exception and the
                tool call request (tool name, args, call id). Used on the sync path and,
                unless `aon_error` is given, on the async path.
            aon_error: Optional async handler, used on the async execution path. Falls back
                to `on_error` when not provided.
            tools: Optional list of tools or tool names to apply handling to. If `None`,
                applies to all tools.

        Raises:
            ValueError: If neither `on_error` nor `aon_error` is provided.
        Nz;ToolErrorMiddleware requires `on_error` and/or `aon_error`.c                óJ   — g | ] }t          |t          ¦  «        s|j        n|‘Œ!S © )Ú
isinstanceÚstrÚname)Ú.0Útools     úd/var/www/html/CA-Chatbot/venv/lib/python3.11/site-packages/langchain/agents/middleware/tool_error.pyú
<listcomp>z0ToolErrorMiddleware.__init__.<locals>.<listcomp>p   s.   € Ð dÐ dÐ dÐVZµ*¸TÅ3Ñ2GÔ2GÐ!Q ¤ ÈTÐ dÐ dÐ dó    )ÚsuperÚ__init__Ú
ValueErrorr   r   Ú_tool_filterr   )Úselfr   r   r   ÚmsgÚ	__class__s        €r%   r)   zToolErrorMiddleware.__init__K   s€   ø€ õ2 	‰Œ×ÒÑÔÐàÐ 	Ð 1ØOˆCÝ˜S‘/”/Ð!à ˆŒØ"ˆŒð 	Ð+ØÐØ dÐ dÐ^cÐ dÑ dÔ dˆDÔÐà $ˆDÔàˆŒ
ˆ
ˆ
r'   Ú	tool_namer!   Úboolc                ó&   — | j         €dS || j         v S )z2Check if error handling should apply to this tool.NT)r+   )r,   r/   s     r%   Ú_should_handle_toolz'ToolErrorMiddleware._should_handle_toolv   s   € àÔÐ$Ø�4Ø˜DÔ-Ð-Ð-r'   Úrequestr   Úhandlerú7Callable[[ToolCallRequest], ToolMessage | Command[Any]]úToolMessage | Command[Any]c                ó˜  — |j         r|j         j        n|j        d         }|                      |¦  «        s ||¦  «        S 	  ||¦  «        S # t          $ r ‚ t
          $ rh}| j        €d}t          |¦  «        |‚|                      ||¦  «        }|€‚ t          t          d|¦  «        |j        d         |d¬¦  «        cY d}~S d}~ww xY w)a9  Intercept tool execution and convert handled exceptions to error messages.

        Args:
            request: Tool call request with call dict, `BaseTool`, state, and runtime.
            handler: Callable to execute the tool.

        Returns:
            `ToolMessage` or `Command` (the final result).
        r"   Nz^ToolErrorMiddleware has no sync `on_error`; run async (ainvoke/astream) or provide `on_error`.ú str | list[str | dict[Any, Any]]ÚidÚerror©ÚcontentÚtool_call_idr"   Ústatus)
r$   r"   Ú	tool_callr2   r   Ú	Exceptionr   ÚRuntimeErrorr   r   )r,   r3   r4   r/   Úexcr-   r<   s          r%   Úwrap_tool_callz"ToolErrorMiddleware.wrap_tool_call|   s  € ð *1¬ÐT�G”LÔ%Ð%¸7Ô;LÈVÔ;Tˆ	à×'Ò'¨	Ñ2Ô2ð 	$Ø�7˜7Ñ#Ô#Ð#ð	Ø�7˜7Ñ#Ô#Ð#øÝð 	ð 	ð 	àÝð 	ð 	ð 	ØŒ}Ð$ð?ð õ # 3Ñ'Ô'¨SÐ0Ø—m’m C¨Ñ1Ô1ˆGØˆØÝÝÐ?ÀÑIÔIØ$Ô.¨tÔ4ØØð	ñ ô ð ð ð ð ð ð øøøøð	øøøs   Á
A ÁC	Á!ACÂ>C	ÃC	úBCallable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]]c              ƒ  óÜ  K  — |j         r|j         j        n|j        d         }|                      |¦  «        s ||¦  «        ƒ d{V —†S 	  ||¦  «        ƒ d{V —†S # t          $ r ‚ t
          $ r|}| j        �|                      ||¦  «        ƒ d{V —†}n| j        �|                      ||¦  «        }n‚ |€‚ t          t          d|¦  «        |j        d         |d¬¦  «        cY d}~S d}~ww xY w)z•Async version of `wrap_tool_call`.

        Uses `aon_error` if provided, otherwise the sync `on_error`. The sync path never
        awaits.
        r"   Nr8   r9   r:   r;   )
r$   r"   r?   r2   r   r@   r   r   r   r   )r,   r3   r4   r/   rB   r<   s         r%   Úawrap_tool_callz#ToolErrorMiddleware.awrap_tool_call¦   s_  è è € ð *1¬ÐT�G”LÔ%Ð%¸7Ô;LÈVÔ;Tˆ	à×'Ò'¨	Ñ2Ô2ð 	*Ø ˜ Ñ)Ô)Ð)Ð)Ð)Ð)Ð)Ð)Ð)ð	Ø ˜ Ñ)Ô)Ð)Ð)Ð)Ð)Ð)Ð)Ð)øÝð 	ð 	ð 	àÝð 	ð 	ð 	ØŒ~Ð)Ø $§¢¨s°GÑ <Ô <Ð<Ð<Ð<Ð<Ð<Ð<��Ø”Ð*ØŸ-š-¨¨WÑ5Ô5��àØˆØÝÝÐ?ÀÑIÔIØ$Ô.¨tÔ4ØØð	ñ ô ð ð ð ð ð ð øøøøð	øøøs   Á
A ÁC+Á/A1C&Ã C+Ã&C+)N)r   r   r   r   r   r   r   r   )r/   r!   r   r0   )r3   r   r4   r5   r   r6   )r3   r   r4   rD   r   r6   )	Ú__name__Ú
__module__Ú__qualname__Ú__doc__r)   r2   rC   rF   Ú__classcell__)r.   s   @r%   r   r      s¢   ø€ € € € € ð*ð *ð\ $(ð)ð &*Ø-1ð)ð )ð )ð )ð )ð )ð )ð )ðV.ð .ð .ð .ð(ð (ð (ð (ðT"ð "ð "ð "ð "ð "ð "ð "r'   r   )rJ   Ú
__future__r   Útypingr   r   r   Úlangchain_core.messagesr   Úlanggraph.errorsr   Ú!langchain.agents.middleware.typesr	   r
   r   r   Úcollections.abcr   r   r   Úlanggraph.typesr   r   Úlangchain.toolsr   r@   r!   ÚlistÚOnErrorÚAOnErrorr   r   r'   r%   ú<module>rW      s“  ðØ 'Ð 'à "Ð "Ð "Ð "Ð "Ð "à +Ð +Ð +Ð +Ð +Ð +Ð +Ð +Ð +Ð +à /Ð /Ð /Ð /Ð /Ð /Ø *Ð *Ð *Ð *Ð *Ð *à ^Ð ^Ð ^Ð ^Ð ^Ð ^Ð ^Ð ^Ð ^Ð ^Ð ^Ð ^àð ;Ø3Ð3Ð3Ð3Ð3Ð3Ð3Ð3à4Ð4Ð4Ð4Ð4Ð4Ø'Ð'Ð'Ð'Ð'Ð'àAÐAÐAÐAÐAÐAØ(Ð(Ð(Ð(Ð(Ð(à˜	 ?Ð3°S¸4ÀÔ;MÑ5MÐPTÑ5TÐTÔU€Gð;ð ˜ OÐ4°iÀÀdÈ<ÔFXÑ@XÐ[_Ñ@_Ô6`Ð`Ôa€Hð;ðjð jð jð jð j˜/¨*°YÔ*?ÀÈ9Ð*TÔUñ jô jð jð jð jr'   