
    D_i                         S r SSKJr  SSKJr  SSKJrJrJrJ	r	  SSK
JrJr  SSKJr  SSKJr  SSKJr  \(       a  SS	KJrJr  S
q " S S\5      rg)z'Callback Handler that writes to a file.    )annotations)Path)TYPE_CHECKINGAnyTextIOcast)Selfoverride)warn_deprecated)BaseCallbackHandler)
print_text)AgentActionAgentFinishFc                  v   \ rS rSrSr S       SS jjrSS jr        SS jrSS jrSS jr	  S       SS	 jjr
\        SS
 j5       r\SS j5       r\ S       SS jj5       r\   S           SS jj5       r\ S         SS jj5       r\ S       SS jj5       rSrg) FileCallbackHandler   aF  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                    Xl         X l        X0l        SU l        [	        S[        U R                   5      R                  U R                  SS95      U l        g)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       W/home/james-whalen/.local/lib/python3.13/site-packages/langchain_core/callbacks/file.py__init__FileCallbackHandler.__init__;   sJ     !	
',$ $$TYY$A
	    c                    SU l         U $ )zEnter 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__FileCallbackHandler.__enter__P   s     (,$r   c                $    U R                  5         g)zExit 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__FileCallbackHandler.__exit__^   s     	

r   c                $    U R                  5         g)z Destructor to cleanup when done.Nr%   r!   s    r   __del__FileCallbackHandler.__del__n   s    

r   c                    [        U S5      (       aI  U R                  (       a7  U R                  R                  (       d  U R                  R                  5         gggg)zClose 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&   FileCallbackHandler.closer   s<     4  TYYtyy7G7GIIOO 8HY r   c                
   U R                   (       d  [        (       d  [        SSSS9  Sq[        U S5      (       a(  U R                  b  U R                  R
                  (       a  Sn[        U5      e[        XR                  X#S9  g)	aX  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   r0   r   r1   RuntimeErrorr   )r   textr   r7   msgs        r   _writeFileCallbackHandler._write|   sn    & ++4N4N)	 *.&tV$$		(9TYY=M=MSCs##4iiu>r   c                    UR                  S5      =(       d/    UR                  SUR                  SS/5      S   5      =(       d    SnU R                  SU S3SS9  g	)
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...
r7   N)getr<   )r   
serializedinputskwargsr?   s        r   on_chain_start"FileCallbackHandler.on_chain_start   s^     JJv ~~fjnnTK=&I"&MN 	
 	)$y9tDr   c                $    U R                  SSS9  g)z{Print that we finished a chain.

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

z
> Finished chain.rB   rC   Nr<   )r   outputsrG   s      r   on_chain_end FileCallbackHandler.on_chain_end   s     	)t4r   c                ^    U R                  UR                  U=(       d    U R                  S9  g)zHandle 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r<   logr   )r   actionr   rG   s       r   on_agent_action#FileCallbackHandler.on_agent_action   s!     	FJJe&9tzz:r   c                    Ub  U R                  SU 35        U R                  U5        Ub  U R                  SU 35        gg)aq  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.

NrB   rK   )r   outputr   observation_prefix
llm_prefixrG   s         r   on_tool_endFileCallbackHandler.on_tool_end   sI    ( )KK"/012F!KK"ZL)* "r   c                J    U R                  X=(       d    U R                  US9  g)zHandle 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   r7   N)r<   r   )r   r:   r   r7   rG   s        r   on_textFileCallbackHandler.on_text   s     	D 3=r   c                `    U R                  UR                  U=(       d    U R                  SS9  g)zHandle 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.

rB   r\   NrP   )r   finishr   rG   s       r   on_agent_finish#FileCallbackHandler.on_agent_finish   s#     	FJJe&9tzztDr   )r   r   r   r   r   )aN)r   strr   rd   r   
str | NonereturnNone)rf   r	   )r'   ztype[BaseException] | Noner(   zBaseException | Noner)   objectrf   rg   )rf   rg   )N )r:   rd   r   re   r7   rd   rf   rg   )rE   dict[str, Any]rF   rj   rG   r   rf   rg   )rL   rj   rG   r   rf   rg   )N)rR   r   r   re   rG   r   rf   r   )NNN)rV   rd   r   re   rW   re   rX   re   rG   r   rf   rg   )
r:   rd   r   re   r7   rd   rG   r   rf   rg   )r`   r   r   re   rG   r   rf   rg   )__name__
__module____qualname____firstlineno____doc__r   r"   r*   r-   r&   r<   r
   rH   rM   rS   rY   r]   ra   __static_attributes__ 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)ro   
__future__r   pathlibr   typingr   r   r   r   typing_extensionsr	   r
   langchain_core._apir   langchain_core.callbacksr   langchain_core.utils.inputr   langchain_core.agentsr   r   r8   r   rq   r   r   <module>rz      s?    - "  3 3 , / 8 1> # pE- pEr   