a
    ”˜ëjT!  ã                   @  s˜   d Z ddlmZ ddlmZ ddlmZ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„ deƒZdS )z'Callback Handler that writes to a file.é    )Úannotations)ÚPath)ÚTYPE_CHECKINGÚAnyÚOptionalÚTextIOÚcast)ÚSelfÚoverride)Úwarn_deprecated)ÚBaseCallbackHandler)Ú
print_text)ÚAgentActionÚAgentFinishFc                	   @  s  e Zd ZdZd2dddddœdd	„Zd
dœdd„Zdddddœdd„Zddœdd„Zddœdd„Zd3dddddœdd„Z	e
dddddœdd „ƒZe
dddd!œd"d#„ƒZe
d4d$dddd%œd&d'„ƒZe
d5ddddddd(œd)d*„ƒZe
d6dddddd+œd,d-„ƒZe
d7d.dddd/œd0d1„ƒZdS )8Ú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):

        .. code-block:: python

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

        Direct instantiation (deprecated):

        .. code-block:: 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. Defaults to ``None``.

    .. 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.

    ÚaNÚstrzOptional[str]ÚNone)ÚfilenameÚmodeÚcolorÚreturnc                 C  s:   || _ || _|| _d| _tdt| j ƒj| jdd�ƒ| _dS )a  Initialize 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. Defaults to ``None``.

        Fr   zutf-8)ÚencodingN)r   r   r   Ú_file_opened_in_contextr   r   ÚopenÚfile)Úselfr   r   r   © r   ú\/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langchain_core/callbacks/file.pyÚ__init__;   s    ýzFileCallbackHandler.__init__r	   )r   c                 C  s
   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   r   r   r   Ú	__enter__P   s    zFileCallbackHandler.__enter__ztype[BaseException] | NonezBaseException | NoneÚobject)Úexc_typeÚexc_valÚexc_tbr   c                 C  s   |   ¡  dS )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   r#   r$   r%   r   r   r   Ú__exit__^   s    zFileCallbackHandler.__exit__c                 C  s   |   ¡  dS )z Destructor to cleanup when done.Nr&   r    r   r   r   Ú__del__n   s    zFileCallbackHandler.__del__c                 C  s&   t | dƒr"| jr"| jjs"| j ¡  dS )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    r   r   r   r'   r   s    zFileCallbackHandler.closeÚ )Útextr   Úendr   c                 C  sZ   | j ststdddd� dat| dƒr8| jdu s8| jjrDd}t|ƒ‚t|| j||d� dS )	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. Defaults to ``""``.
            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.)ZsinceÚpendingÚmessager   Nz?File is not open. Use FileCallbackHandler as a context manager.)r   r   r.   )r   Ú_GLOBAL_DEPRECATION_WARNEDr   r*   r   r+   ÚRuntimeErrorr   )r   r-   r   r.   Úmsgr   r   r   Ú_write|   s    
ü	zFileCallbackHandler._writezdict[str, Any]r   )Ú
serializedÚinputsÚkwargsr   c                 K  sB   |  d¡p&|  d|  ddg¡d ¡p&d}| jd|› d�dd� d	S )
zóPrint 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...Ú
©r.   N)Úgetr4   )r   r5   r6   r7   r8   r   r   r   Úon_chain_start¡   s    
ÿýz"FileCallbackHandler.on_chain_start)Úoutputsr7   r   c                 K  s   | j ddd� dS )z›Print that we finished a chain.

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

        z
> Finished chain.r;   r<   N©r4   )r   r?   r7   r   r   r   Úon_chain_end´   s    	z FileCallbackHandler.on_chain_endr   )Úactionr   r7   r   c                 K  s   | j |j|p| jd� dS )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©r4   Úlogr   )r   rB   r   r7   r   r   r   Úon_agent_action¿   s    z#FileCallbackHandler.on_agent_action)Úoutputr   Úobservation_prefixÚ
llm_prefixr7   r   c                 K  s>   |dur|   d|› �¡ |   |¡ |dur:|   d|› �¡ dS )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;   r@   )r   rF   r   rG   rH   r7   r   r   r   Úon_tool_endÎ   s
    
zFileCallbackHandler.on_tool_end)r-   r   r.   r7   r   c                 K  s   | j ||p| j|d� dS )a8  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. Defaults to ``""``.
            **kwargs: Additional keyword arguments.

        ©r   r.   N)r4   r   )r   r-   r   r.   r7   r   r   r   Úon_textè   s    zFileCallbackHandler.on_textr   )Úfinishr   r7   r   c                 K  s   | j |j|p| jdd� dS )a2  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;   rJ   NrC   )r   rL   r   r7   r   r   r   Úon_agent_finishø   s    z#FileCallbackHandler.on_agent_finish)r   N)Nr,   )N)NNN)Nr,   )N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r!   r(   r)   r'   r4   r
   r>   rA   rE   rI   rK   rM   r   r   r   r   r      s8   & ÿ  ü%
 ÿ   û ÿ ÿr   N)rQ   Ú
__future__r   Úpathlibr   Útypingr   r   r   r   r   Ztyping_extensionsr	   r
   Zlangchain_core._apir   Zlangchain_core.callbacksr   Zlangchain_core.utils.inputr   Zlangchain_core.agentsr   r   r1   r   r   r   r   r   Ú<module>   s   