
    gC<                        d Z ddlmZ ddl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 erddlmZmZmZ dd	lmZ dd
lmZ ddZdZ G d de      Z G d de	      Z G d d      Z G d d      Z G d de      Zy)a  
LangChain CallbackHandler that prints to streamlit.

This is a special API that's imported and used by LangChain itself. Any updates
to the public API (the StreamlitCallbackHandler constructor, and the entirety
of LLMThoughtLabeler) *must* remain backwards-compatible to avoid breaking
LangChain.

This means that it's acceptable to add new optional kwargs to StreamlitCallbackHandler,
but no new positional args or required kwargs should be added, and no existing
args should be removed. If we need to overhaul the API, we must ensure that a
compatible API continues to exist.

Any major change to the StreamlitCallbackHandler should be tested by importing
the API *from LangChain itself*.

This module is lazy-loaded.
    )annotationsN)Enum)TYPE_CHECKINGAny
NamedTuple)BaseCallbackHandler)gather_metrics)AgentActionAgentFinish	LLMResult)DeltaGenerator)StatusContainerc                &    | j                  dd      S )zZConvert newline characters to markdown newline sequences
    (space, space, newline).
    
z  
)replace)texts    l/var/www/openai/venv/lib/python3.12/site-packages/streamlit/external/langchain/streamlit_callback_handler.py_convert_newlinesr   >   s     <<f%%    <   c                      e Zd ZdZdZdZdZy)LLMThoughtStateTHINKINGRUNNING_TOOLCOMPLETEERRORN)__name__
__module____qualname__r   r   r   r    r   r   r   r   J   s    H!LHEr   r   c                  "    e Zd ZU ded<   ded<   y)
ToolRecordstrname	input_strN)r   r   r   __annotations__r    r   r   r"   r"   U   s    
INr   r"   c                  (    e Zd ZdZddZddZddZy)LLMThoughtLabelerz
    Generates markdown labels for LLMThought containers. Pass a custom
    subclass of this to StreamlitCallbackHandler to override its default
    labeling logic.
    c                     y)ziReturn the markdown label for a new LLMThought that doesn't have
        an associated tool yet.
        zThinking...r    selfs    r   get_initial_labelz#LLMThoughtLabeler.get_initial_labela   s     r   c                    |j                   }|j                  }|dk(  rd}t        t        t	        |            }|d| }t	        |j                         |kD  r|dz   }|j                  dd      }d| d| S )	a}  Return the label for an LLMThought that has an associated
        tool.

        Parameters
        ----------
        tool
            The tool's ToolRecord

        is_complete
            True if the thought is complete; False if the thought
            is still receiving input.

        Returns
        -------
        The markdown label for the thought's container.

        
_ExceptionzParsing errorNz...r    z**z:** )r%   r$   minMAX_TOOL_INPUT_STR_LENGTHlenr   )r+   toolis_completer%   r$   input_str_lens         r   get_tool_labelz LLMThoughtLabeler.get_tool_labelg   s    $ NN	yy<"D5s9~Fn}-	t~~.!E)I%%dC0	D6i[))r   c                     y)zReturn the markdown label for the agent's final thought -
        the "Now I have the answer" thought, that doesn't involve
        a tool.
        z**Complete!**r    r*   s    r   get_final_agent_thought_labelz/LLMThoughtLabeler.get_final_agent_thought_label   s    
 r   N)returnr#   )r3   r"   r4   boolr9   r#   )r   r   r   __doc__r,   r6   r8   r    r   r   r(   r(   Z   s    *:r   r(   c                      e Zd ZdZ	 	 	 	 	 	 	 	 ddZedd       Zedd       ZddZddZ	ddZ
ddZdd	Z	 	 	 	 	 	 	 	 dd
Z	 	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZddZ	 d	 	 	 	 	 	 	 ddZdddZy)
LLMThoughta)  Encapsulates the Streamlit UI for a single LLM 'thought' during a LangChain Agent
    run. Each tool usage gets its own thought; and runs also generally having a
    concluding thought where the Agent determines that it has an answer to the prompt.

    Each thought gets its own expander UI.
    c                    |j                  |j                         |      | _        t        j                  | _        d| _        d | _        d | _        || _	        || _
        y )N)expanded )statusr,   
_containerr   r   _state_llm_token_stream_llm_token_stream_placeholder
_last_tool_collapse_on_complete_labeler)r+   parent_containerlabelerr?   collapse_on_completes        r   __init__zLLMThought.__init__   s^     +11%%'( 2 
 &..!#DH*-1%9"r   c                    | j                   S )z!The container we're writing into.)rB   r*   s    r   	containerzLLMThought.container        r   c                    | j                   S )z&The last tool executed by this thought)rF   r*   s    r   	last_toolzLLMThought.last_tool   rO   r   c                    | j                   %| j                   j                  | j                         d| _        d | _         y )Nr@   )rE   markdownrD   r*   s    r   _reset_llm_token_streamz"LLMThought._reset_llm_token_stream   s8    --9..778N8NO!#-1*r   c                $    | j                          y N)rT   )r+   
serializedpromptss      r   on_llm_startzLLMThought.on_llm_start   s    $$&r   c                    | xj                   t        |      z  c_         | j                  | j                  j	                         | _        | j                  j                  | j                   dz          y )Nu   ▕)rD   r   rE   rB   emptyrS   r+   tokenkwargss      r   on_llm_new_tokenzLLMThought.on_llm_new_token   sY    "3E"::--5151F1F1HD.**33D4J4JU4RSr   c                v    | j                          | j                  | j                  j                                y rV   )rT   completerH   r8   r+   responser^   s      r   
on_llm_endzLLMThought.on_llm_end   s)     	$$&dmmAACDr   c                    | j                   j                  |       t        j                  | _        | j                  d       y )NzLLM encountered an error...)rB   	exceptionr   r   rC   ra   r+   errorargsr^   s       r   on_llm_errorzLLMThought.on_llm_error   s.    !!%(%++34r   c                D   t         j                  | _        |d   }t        ||      | _        | j
                  j                  | j                  j                  | j                  d      d       t        |      t        kD  r | j
                  j                  d| d       y y )	Nr$   )r$   r%   Fr4   running)labelstatez**Input:**

z

**Output:**)r   r   rC   r"   rF   rB   updaterH   r6   r2   r1   rS   )r+   rW   r%   r^   	tool_names        r   on_tool_startzLLMThought.on_tool_start   s    
 &22v&	$)yI--..tE.R 	 	
 y>55OO$$~i[%PQ 6r   Nc                :    | j                   j                  |       y rV   )rB   rS   r+   outputcolorobservation_prefix
llm_prefixr^   s         r   on_tool_endzLLMThought.on_tool_end   s     	  (r   c                    | j                   j                  d       | j                   j                  |       | j                   j                  d       y )Nz **Tool encountered an error...**rh   )ro   )rB   rS   rf   rp   rg   s       r   on_tool_errorzLLMThought.on_tool_error   s<      !CD!!%(W-r   c                     y rV   r    r+   actionrv   r^   s       r   on_agent_actionzLLMThought.on_agent_action   s     	r   c                t   |W| j                   t        j                  k(  r:| j                  J d       | j                  j                  | j                  d      }| j                  r/| j                  j                  dk(  rt        j                  | _         n2| j                   t        j                  k7  rt        j                  | _         | j                  rt        j                  d       | j                  j                  || j                  rdnd| j                   t        j                  k(  rd
       yd	
       y)zFinish the thought.Nz;_last_tool should never be null when _state == RUNNING_TOOLTrl   r.   g      ?Frh   ra   )rn   r?   ro   )rC   r   r   rF   rH   r6   r$   r   r   rG   timesleeprB   rp   )r+   final_labels     r   ra   zLLMThought.complete   s    4;;/2N2N#N??. M. --66T 7 K ??t33|C)//DK[[O111)22DK%%JJt"88Ud![[O,A,AA' 	 	
 HR 	 	
r   )rI   r   rJ   r(   r?   r:   rK   r:   )r9   r   )r9   zToolRecord | None)r9   None)rW   dict[str, Any]rX   	list[str]r9   r   r]   r#   r^   r   r9   r   rc   r   r^   r   r9   r   rh   BaseExceptionri   r   r^   r   r9   r   rW   r   r%   r#   r^   r   r9   r   NNNru   r#   rv   
str | Nonerw   r   rx   r   r^   r   r9   r   rV   r~   r
   rv   r   r^   r   r9   r   r   r   r9   r   )r   r   r   r;   rL   propertyrN   rQ   rT   rY   r_   rd   rj   rr   ry   r{   r   ra   r    r   r   r=   r=      s    (  #  	 
 # $    2'TE5
R(R58RDGR	R& !)-!%)) ) '	)
 ) ) 
). 8<!*4GJ	
r   r=   c                     e Zd Z ed      ddddd	 	 	 	 	 	 	 	 	 dd       ZddZddZddd	Z	 	 	 	 	 	 	 	 dd
ZddZ	ddZ
ddZ	 	 	 	 	 	 	 	 ddZ	 	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZddZ	 d	 	 	 	 	 	 	 ddZ	 d	 	 	 	 	 	 	 d dZy)!StreamlitCallbackHandlerz+external.langchain.StreamlitCallbackHandler   FN)max_thought_containersexpand_new_thoughtscollapse_completed_thoughtsthought_labelerc                   || _         |j                         | _        d| _        g | _        t        |d      | _        || _        || _        |xs
 t               | _
        y)a=  Construct a new StreamlitCallbackHandler. This CallbackHandler is geared
        towards use with a LangChain Agent; it displays the Agent's LLM and tool-usage
        "thoughts" inside a series of Streamlit expanders.

        Parameters
        ----------

        parent_container
            The `st.container` that will contain all the Streamlit elements that the
            Handler creates.

        max_thought_containers

            .. note::
                This parameter is deprecated and is ignored in the latest version of
                the callback handler.

            The max number of completed LLM thought containers to show at once. When
            this threshold is reached, a new thought will cause the oldest thoughts to
            be collapsed into a "History" expander. Defaults to 4.

        expand_new_thoughts
            Each LLM "thought" gets its own `st.expander`. This param controls whether
            that expander is expanded by default. Defaults to False.

        collapse_completed_thoughts
            If True, LLM thought expanders will be collapsed when completed.
            Defaults to False.

        thought_labeler
            An optional custom LLMThoughtLabeler instance. If unspecified, the handler
            will use the default thought labeling logic. Defaults to None.
        N   )_parent_containerrN   _history_parent_current_thought_completed_thoughtsmax_max_thought_containers_expand_new_thoughts_collapse_completed_thoughtsr(   _thought_labeler)r+   rI   r   r   r   r   s         r   rL   z!StreamlitCallbackHandler.__init__  s_    V "2/99;3757 '*+A1'E$$7!,G) / F3D3Fr   c                H    | j                   t        d      | j                   S )z]Return our current LLMThought. Raise an error if we have no current
        thought.
        z(Current LLMThought is unexpectedly None!)r   RuntimeErrorr*   s    r   _require_current_thoughtz1StreamlitCallbackHandler._require_current_thoughtE  s(       (IJJ$$$r   c                ~    t        | j                        dkD  r%| j                  t        | j                        dz
     S y)zJReturn our most recent completed LLMThought, or None if we don't have one.r   r   N)r2   r   r*   s    r   _get_last_completed_thoughtz4StreamlitCallbackHandler._get_last_completed_thoughtM  s9    t''(1,++C0H0H,IA,MNNr   c                    | j                         }|j                  |       | j                  j                  |       d| _        y)z{Complete the current thought, optionally assigning it a new label.
        Add it to our _completed_thoughts list.
        N)r   ra   r   appendr   )r+   r   thoughts      r   _complete_current_thoughtz2StreamlitCallbackHandler._complete_current_thoughtS  s<     //1%  ''0 $r   c                    | j                   <t        | j                  | j                  | j                  | j
                        | _         | j                   j                  ||       y )N)rI   r?   rK   rJ   )r   r=   r   r   r   r   rY   )r+   rW   rX   r^   s       r   rY   z%StreamlitCallbackHandler.on_llm_start\  sY       ($.!%!7!722%)%F%F--	%D! 	**:w?r   c                F     | j                         j                  |fi | y rV   )r   r_   r\   s      r   r_   z)StreamlitCallbackHandler.on_llm_new_tokenl  s     8%%'88I&Ir   c                F     | j                         j                  |fi | y rV   )r   rd   rb   s      r   rd   z#StreamlitCallbackHandler.on_llm_endo  s     2%%'228FvFr   c                F     | j                         j                  |fi | y rV   )r   rj   rg   s       r   rj   z%StreamlitCallbackHandler.on_llm_errorr  s     4%%'44UEfEr   c                H     | j                         j                  ||fi | y rV   )r   rr   )r+   rW   r%   r^   s       r   rr   z&StreamlitCallbackHandler.on_tool_startu  s$     	6%%'55j)VvVr   c                l     | j                         j                  ||||fi | | j                          y rV   )r   ry   r   rt   s         r   ry   z$StreamlitCallbackHandler.on_tool_endz  s=     	4%%'33E-z	
=C	
 	&&(r   c                F     | j                         j                  |fi | y rV   )r   r{   rg   s       r   r{   z&StreamlitCallbackHandler.on_tool_error  s     5%%'55eFvFr   c                H     | j                         j                  ||fi | y rV   )r   r   r}   s       r   r   z(StreamlitCallbackHandler.on_agent_action  s$     	8%%'77PPr   c                    | j                   ;| j                   j                  | j                  j                                d | _         y y rV   )r   ra   r   r8   )r+   finishrv   r^   s       r   on_agent_finishz(StreamlitCallbackHandler.on_agent_finish  sE       ,!!**%%CCE %)D!	 -r   )
rI   r   r   intr   r:   r   r:   r   zLLMThoughtLabeler | None)r9   r=   )r9   zLLMThought | NonerV   r   )rW   r   rX   r   r^   r   r9   r   r   r   r   r   r   r   r   )r   r   rv   r   r^   r   r9   r   )r   r   r   r	   rL   r   r   r   rY   r_   rd   rj   rr   ry   r{   r   r   r    r   r   r   r     s   AB
 '($),1481G(1G !$	1G
 "1G &*1G 21G C1Gf%%@(@3<@HK@	@ JGFW(W58WDGW	W !)-!%)) ) '	)
 ) ) 
)G 8<Q!Q*4QGJQ	Q 8<)!)*4)GJ)	)r   r   )r   r#   r9   r#   )r;   
__future__r   r   enumr   typingr   r   r   langchain.callbacks.baser   streamlit.runtime.metrics_utilr	   langchain.schemar
   r   r   streamlit.delta_generatorr   /streamlit.elements.lib.mutable_status_containerr   r   r1   r   r"   r(   r=   r   r    r   r   <module>r      s   0 #   1 1 :  9O&  d  
/ /dA
 A
HF)2 F)r   