
    f3fi                         d Z ddlmZ ddlmZ ddl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 ddlmZ erdd	lmZmZ d
a G d de      Zy)z'Callback Handler that writes to a file.    )annotations)Path)TYPE_CHECKINGAnyTextIOcast)Selfoverride)warn_deprecated)BaseCallbackHandler)
print_text)AgentActionAgentFinishFc                  J   e Zd ZdZ	 d	 	 	 	 	 	 	 ddZddZ	 	 	 	 	 	 	 	 ddZddZddZ	 	 d	 	 	 	 	 	 	 ddZ	e
	 	 	 	 	 	 	 	 dd	       Ze
dd
       Ze
	 d	 	 	 	 	 	 	 dd       Ze
	 	 	 d	 	 	 	 	 	 	 	 	 	 	 dd       Ze
	 d	 	 	 	 	 	 	 	 	 dd       Ze
	 d	 	 	 	 	 	 	 dd       Zy)FileCallbackHandlera  Callback Handler that writes to a file.

    This handler supports both context manager usage (recommended) and direct
    instantiation (deprecated) for backwards compatibility.

    Examples:
        Using as a context manager (recommended):

        ```python
        with FileCallbackHandler("output.txt") as handler:
            # Use handler with your chain/agent
            chain.invoke(inputs, config={"callbacks": [handler]})
        ```

        Direct instantiation (deprecated):

        ```python
        handler = FileCallbackHandler("output.txt")
        # File remains open until handler is garbage collected
        try:
            chain.invoke(inputs, config={"callbacks": [handler]})
        finally:
            handler.close()  # Explicit cleanup recommended
        ```

    Args:
        filename: The file path to write to.
        mode: The file open mode. Defaults to `'a'` (append).
        color: Default color for text output.

    !!! note
        When not used as a context manager, a deprecation warning will be issued
        on first use. The file will be opened immediately in `__init__` and closed
        in `__del__` or when `close()` is called explicitly.

    Nc                    || _         || _        || _        d| _        t	        dt        | j                         j                  | j                  d            | _        y)zInitialize the file callback handler.

        Args:
            filename: Path to the output file.
            mode: File open mode (e.g., `'w'`, `'a'`, `'x'`). Defaults to `'a'`.
            color: Default text color for output.

        Fr   zutf-8)encodingN)filenamemodecolor_file_opened_in_contextr   r   openfile)selfr   r   r   s       [/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_core/callbacks/file.py__init__zFileCallbackHandler.__init__;   sP     !	
',$ $$TYY$A
	    c                    d| _         | S )a   Enter the context manager.

        Returns:
            The FileCallbackHandler instance.

        !!! note
            The file is already opened in `__init__`, so this just marks that
            the handler is being used as a context manager.

        T)r   r   s    r   	__enter__zFileCallbackHandler.__enter__P   s     (,$r   c                $    | j                          y)a  Exit the context manager and close the file.

        Args:
            exc_type: Exception type if an exception occurred.
            exc_val: Exception value if an exception occurred.
            exc_tb: Exception traceback if an exception occurred.

        Nclose)r   exc_typeexc_valexc_tbs       r   __exit__zFileCallbackHandler.__exit__^   s     	

r   c                $    | j                          y)z Destructor to cleanup when done.Nr"   r   s    r   __del__zFileCallbackHandler.__del__n   s    

r   c                    t        | d      r?| j                  r2| j                  j                  s| j                  j                          yyyy)zClose the file if it's open.

        This method is safe to call multiple times and will only close
        the file if it's currently open.

        r   N)hasattrr   closedr#   r   s    r   r#   zFileCallbackHandler.closer   s9     4 TYYtyy7G7GIIOO 8HY r   c                    | j                   st        st        ddd       dat        | d      r"| j                  | j                  j
                  rd}t        |      t        || j                  ||       y)	a  Write text to the file with deprecation warning if needed.

        Args:
            text: The text to write to the file.
            color: Optional color for the text. Defaults to `self.color`.
            end: String appended after the text.
            file: Optional file to write to. Defaults to `self.file`.

        Raises:
            RuntimeError: If the file is closed or not available.

        z0.3.67Tz{Using FileCallbackHandler without a context manager is deprecated. Use 'with FileCallbackHandler(...) as handler:' instead.)sincependingmessager   Nz?File is not open. Use FileCallbackHandler as a context manager.)r   r   end)r   _GLOBAL_DEPRECATION_WARNEDr   r+   r   r,   RuntimeErrorr   )r   textr   r1   msgs        r   _writezFileCallbackHandler._write|   sl    & ++4N)	 *.&tV$		(9TYY=M=MSCs##4diiu#>r   c                    |j                  d      xs* |j                  d|j                  ddg      d         xs d}| j                  d| dd       y	)
zPrint that we are entering a chain.

        Args:
            serialized: The serialized chain information.
            inputs: The inputs to the chain.
            **kwargs: Additional keyword arguments that may contain `'name'`.

        nameidz	<unknown>z

> Entering new z	 chain...
r1   N)getr6   )r   
serializedinputskwargsr8   s        r   on_chain_startz"FileCallbackHandler.on_chain_start   s^     JJv ~~fjnnTK=&I"&MN 	
 	)$y9tDr   c                *    | j                  dd       y)zPrint that we finished a chain.

        Args:
            outputs: The outputs of the chain.
            **kwargs: Additional keyword arguments.

        z
> Finished chain.r;   r<   Nr6   )r   outputsr@   s      r   on_chain_endz FileCallbackHandler.on_chain_end   s     	)t4r   c                Z    | j                  |j                  |xs | j                         y)a'  Handle agent action by writing the action log.

        Args:
            action: The agent action containing the log to write.
            color: Color override for this specific output. If `None`, uses
                `self.color`.
            **kwargs: Additional keyword arguments.

        )r   Nr6   logr   )r   actionr   r@   s       r   on_agent_actionz#FileCallbackHandler.on_agent_action   s!     	FJJe&9tzz:r   c                    || j                  d|        | j                  |       || j                  d|        yy)a  Handle tool end by writing the output with optional prefixes.

        Args:
            output: The tool output to write.
            color: Color override for this specific output. If `None`, uses
                `self.color`.
            observation_prefix: Optional prefix to write before the output.
            llm_prefix: Optional prefix to write after the output.
            **kwargs: Additional keyword arguments.

        Nr;   rC   )r   outputr   observation_prefix
llm_prefixr@   s         r   on_tool_endzFileCallbackHandler.on_tool_end   sI    ( )KK"/012F!KK"ZL)* "r   c                H    | j                  ||xs | j                  |       y)a   Handle text output.

        Args:
            text: The text to write.
            color: Color override for this specific output. If `None`, uses
                `self.color`.
            end: String appended after the text.
            **kwargs: Additional keyword arguments.

        r   r1   N)r6   r   )r   r4   r   r1   r@   s        r   on_textzFileCallbackHandler.on_text   s     	D 3=r   c                \    | j                  |j                  |xs | j                  d       y)a.  Handle agent finish by writing the finish log.

        Args:
            finish: The agent finish object containing the log to write.
            color: Color override for this specific output. If `None`, uses
                `self.color`.
            **kwargs: Additional keyword arguments.

        r;   rQ   NrG   )r   finishr   r@   s       r   on_agent_finishz#FileCallbackHandler.on_agent_finish   s#     	FJJe&9tzztDr   )aN)r   strr   rW   r   
str | NonereturnNone)rY   r	   )r$   ztype[BaseException] | Noner%   zBaseException | Noner&   objectrY   rZ   )rY   rZ   )N )r4   rW   r   rX   r1   rW   rY   rZ   )r>   dict[str, Any]r?   r]   r@   r   rY   rZ   )rD   r]   r@   r   rY   rZ   )N)rI   r   r   rX   r@   r   rY   r   )NNN)rL   rW   r   rX   rM   rX   rN   rX   r@   r   rY   rZ   )
r4   rW   r   rX   r1   rW   r@   r   rY   rZ   )rT   r   r   rX   r@   r   rY   rZ   )__name__
__module____qualname____doc__r   r    r'   r)   r#   r6   r
   rA   rE   rJ   rO   rR   rU    r   r   r   r      s   #L CG

#&
5?
	
*, & 	
 
  !	#?#? #? 	#?
 
#?J E(E2@ELOE	E E$ 5 5 7;;!;*4;GJ;	; ;  !)-!%++ + '	+
 + + 
+ +2 >@>> *>8;>LO>	> > 7;E!E*4EGJE	E Er   r   N)ra   
__future__r   pathlibr   typingr   r   r   r   typing_extensionsr	   r
   langchain_core._apir   langchain_core.callbacksr   langchain_core.utils.inputr   langchain_core.agentsr   r   r2   r   rb   r   r   <module>rk      s?    - "  3 3 , / 8 1> # pE- pEr   