
    3fi =                       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
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 dd
ZdZdZ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)z*Callback Handler that prints to streamlit.    )annotations)Enum)TYPE_CHECKINGAnyDictList
NamedTupleOptional)AgentActionAgentFinish)BaseCallbackHandler)	LLMResult)MutableExpander)DeltaGeneratorc                &    | j                  dd      S )zZConvert newline characters to markdown newline sequences
    (space, space, newline).
    
z  
)replace)texts    /var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_community/callbacks/streamlit/streamlit_callback_handler.py_convert_newlinesr      s     <<f%%    u   ✅z:thinking_face:z:books:u   ⚠️c                      e Zd ZdZdZdZdZy)LLMThoughtStatez#Enumerator of the LLMThought state.THINKINGRUNNING_TOOLCOMPLETEN)__name__
__module____qualname____doc__r   r   r    r   r   r   r      s    - H!LHr   r   c                  &    e Zd ZU dZded<   ded<   y)
ToolRecordzTool record as a NamedTuple.strname	input_strN)r   r   r   r    __annotations__r!   r   r   r#   r#   *   s    &
INr   r#   c                  X    e Zd ZdZedd       Zedd       Zedd       Ze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                     t          dS )ziReturn the markdown label for a new LLMThought that doesn't have
        an associated tool yet.
        z **Thinking...**)THINKING_EMOJIr!   r   r   get_initial_labelz#LLMThoughtLabeler.get_initial_label8   s    
 !!!122r   c                   | j                   }| j                  }|rt        nt        }|dk(  rt        }d}t        dt        |      g      }|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 error<   r   z...r    z **z:** )r&   r%   CHECKMARK_EMOJIr+   EXCEPTION_EMOJIminlenr   )toolis_completeinputr%   emojiidxlabels          r   get_tool_labelz LLMThoughtLabeler.get_tool_label?   s    & yy#.N<#E"D2s5z"#at~~$EMEdC('TF$ug.r   c                     t          dS )zmReturn a markdown label for the special 'history' container
        that contains overflow thoughts.
        z **History**)HISTORY_EMOJIr!   r   r   get_history_labelz#LLMThoughtLabeler.get_history_label`   s    
  --r   c                     t          dS )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!**)r1   r!   r   r   get_final_agent_thought_labelz/LLMThoughtLabeler.get_final_agent_thought_labelg   s     "".11r   N)returnr$   )r5   r#   r6   boolrA   r$   )	r   r   r   r    staticmethodr,   r;   r>   r@   r!   r   r   r)   r)   1   sX     3 3  @ . . 2 2r   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ddZy)
LLMThoughtz&A thought in the LLM's thought stream.c                    t        ||j                         |      | _        t        j                  | _        d| _        d| _        d| _        || _	        || _
        y)a@  Initialize the LLMThought.

        Args:
            parent_container: The container we're writing into.
            labeler: The labeler to use for this thought.
            expanded: Whether the thought should be expanded by default.
            collapse_on_complete: Whether the thought should be collapsed.
        )parent_containerr:   expanded N)r   r,   
_containerr   r   _state_llm_token_stream_llm_token_writer_idx
_last_tool_collapse_on_complete_labeler)selfrG   labelerrH   collapse_on_completes        r   __init__zLLMThought.__init__s   sW     *-++-

 &..!#48"04%9"r   c                    | j                   S )z!The container we're writing into.)rJ   rQ   s    r   	containerzLLMThought.container        r   c                    | j                   S )z&The last tool executed by this thought)rN   rV   s    r   	last_toolzLLMThought.last_tool   rX   r   c                     d| _         d | _        y NrI   )rL   rM   rV   s    r   _reset_llm_token_streamz"LLMThought._reset_llm_token_stream   s    !#%)"r   c                $    | j                          y Nr]   )rQ   
serializedpromptss      r   on_llm_startzLLMThought.on_llm_start   s    $$&r   c                    | xj                   t        |      z  c_         | j                  j                  | j                   | j                        | _        y )N)index)rL   r   rJ   markdownrM   rQ   tokenkwargss      r   on_llm_new_tokenzLLMThought.on_llm_new_token   sF    "3E"::%)__%=%=""$*D*D &> &
"r   c                $    | j                          y r_   r`   rQ   responseri   s      r   
on_llm_endzLLMThought.on_llm_end   s     	$$&r   c                p    | j                   j                  d       | j                   j                  |       y )Nz**LLM encountered an error...**rJ   rf   	exceptionrQ   errorri   s      r   on_llm_errorzLLMThought.on_llm_error   s'      !BC!!%(r   c                    t         j                  | _        |d   }t        ||      | _        | j
                  j                  | j                  j                  | j                  d             y )Nr%   )r%   r&   Fr6   	new_label)	r   r   rK   r#   rN   rJ   updaterP   r;   )rQ   ra   r&   ri   	tool_names        r   on_tool_startzLLMThought.on_tool_start   s\    
 &22v&	$)yImm224??PU2V 	 	
r   Nc                T    | j                   j                  dt        |       d       y )Nz**)rJ   rf   r$   rQ   outputcolorobservation_prefix
llm_prefixri   s         r   on_tool_endzLLMThought.on_tool_end   s#     	  2c&k]"!56r   c                p    | j                   j                  d       | j                   j                  |       y )Nz **Tool encountered an error...**rp   rr   s      r   on_tool_errorzLLMThought.on_tool_error   s'      !CD!!%(r   c                     y r_   r!   rQ   actionr   ri   s       r   on_agent_actionzLLMThought.on_agent_action        	r   c                l   |W| j                   t        j                  k(  r:| j                  J d       | j                  j                  | j                  d      }t        j                  | _         | j                  r| j                  j                  |d       y| j                  j                  |       y)zFinish the thought.Nz;_last_tool should never be null when _state == RUNNING_TOOLTrv   F)rx   new_expandedrw   )
rK   r   r   rN   rP   r;   r   rO   rJ   ry   )rQ   final_labels     r   completezLLMThought.complete   s    4;;/2N2N#N??. M. --66T 7 K &..%%OO""[u"MOO""["9r   c                8    | j                   j                          y)zFRemove the thought from the screen. A cleared thought can't be reused.N)rJ   clearrV   s    r   r   zLLMThought.clear   s    r   )rG   r   rR   r)   rH   rB   rS   rB   )rA   r   )rA   zOptional[ToolRecord]rA   None)ra   Dict[str, Any]rb   	List[str]rA   r   rh   r$   ri   r   rA   r   rm   r   ri   r   rA   r   rs   BaseExceptionri   r   rA   r   ra   r   r&   r$   ri   r   rA   r   NNNr~   r   r   Optional[str]r   r   r   r   ri   r   rA   r   r_   r   r   r   r   ri   r   rA   r   r   r   rA   r   )r   r   r   r    rT   propertyrW   rZ   r]   rc   rj   rn   rt   r{   r   r   r   r   r   r!   r   r   rE   rE   p   s   0 (  #  	 
 # 6    *'
')

(

58

DG

	

  $,0$(77 7 *	7
 "7 7 
7)
 ;?!*7JM	: r   rE   c                  \   e Zd ZdZddddd	 	 	 	 	 	 	 	 	 ddZddZddZedd	       Zd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Zd*dZd#dZ	 d	 	 	 	 	 	 	 d+dZ	 d	 	 	 	 	 	 	 d,dZy)-StreamlitCallbackHandlerz0Callback handler that writes to a Streamlit app.   TN)max_thought_containersexpand_new_thoughtscollapse_completed_thoughtsthought_labelerc                   || _         |j                         | _        d| _        d| _        g | _        t        |d      | _        || _        || _	        |xs
 t               | _        y)a  Create a StreamlitCallbackHandler instance.

        Parameters
        ----------
        parent_container
            The `st.container` that will contain all the Streamlit elements that the
            Handler creates.
        max_thought_containers
            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 True.
        collapse_completed_thoughts
            If True, LLM thought expanders will be collapsed when completed.
            Defaults to True.
        thought_labeler
            An optional custom LLMThoughtLabeler instance. If unspecified, the handler
            will use the default thought labeling logic. Defaults to None.
        N   )_parent_containerrW   _history_parent_history_container_current_thought_completed_thoughtsmax_max_thought_containers_expand_new_thoughts_collapse_completed_thoughtsr)   _thought_labeler)rQ   rG   r   r   r   r   s         r   rT   z!StreamlitCallbackHandler.__init__   sf    < "2/99;=A6: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   RuntimeErrorrV   s    r   _require_current_thoughtz1StreamlitCallbackHandler._require_current_thought  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)r4   r   rV   s    r   _get_last_completed_thoughtz4StreamlitCallbackHandler._get_last_completed_thought  s9    t''(1,++C0H0H,IA,MNNr   c                t    t        | j                        }| j                  |dz  }| j                  |dz  }|S )zThe number of 'thought containers' we're currently showing: the
        number of completed thought containers, the history container (if it exists),
        and the current thought container (if it exists).
        r   )r4   r   r   r   )rQ   counts     r   _num_thought_containersz0StreamlitCallbackHandler._num_thought_containers   sC     D,,-"".QJE  ,QJE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   r   r   appendr   )rQ   r   thoughts      r   _complete_current_thoughtz2StreamlitCallbackHandler._complete_current_thought-  s<     //1%  ''0 $r   c                   | j                   | j                  kD  r*t        | j                        dkD  r| j                  D| j                  dkD  r5t        | j                  | j                  j                         d      | _        | j                  j                  d      }| j                  T| j                  j                  |j                  j                         | j                  j                  |j                         |j                          | j                   | j                  kD  rt        | j                        dkD  ryyyy)zgIf we have too many thoughts onscreen, move older thoughts to the
        'history container.'
        r   Nr   F)r:   rH   )r   r   r4   r   r   r   r   r   r>   poprf   rW   r:   append_copyr   )rQ   oldest_thoughts     r   _prune_old_thought_containersz6StreamlitCallbackHandler._prune_old_thought_containers6  s   
 ((4+G+GGD,,-1
 &&.43O3ORS3S*9((//AAC"+' "5599!<N&&2''001I1I1O1OP''33N4L4LM  "# ((4+G+GGD,,-1 H1 Hr   c                    | j                   <t        | j                  | j                  | j                  | j
                        | _         | j                   j                  ||       y )N)rG   rH   rS   rR   )r   rE   r   r   r   r   rc   )rQ   ra   rb   ri   s       r   rc   z%StreamlitCallbackHandler.on_llm_startN  sY       ($.!%!7!722%)%F%F--	%D! 	**:w?r   c                f     | j                         j                  |fi | | j                          y r_   )r   rj   r   rg   s      r   rj   z)StreamlitCallbackHandler.on_llm_new_token^  s,    8%%'88I&I**,r   c                f     | j                         j                  |fi | | j                          y r_   )r   rn   r   rl   s      r   rn   z#StreamlitCallbackHandler.on_llm_endb  s,    2%%'228FvF**,r   c                f     | j                         j                  |fi | | j                          y r_   )r   rt   r   rr   s      r   rt   z%StreamlitCallbackHandler.on_llm_errorf  s,    4%%'44UEfE**,r   c                h     | j                         j                  ||fi | | j                          y r_   )r   r{   r   )rQ   ra   r&   ri   s       r   r{   z&StreamlitCallbackHandler.on_tool_startj  s0     	6%%'55j)VvV**,r   c                    t        |      } | j                         j                  ||||fi | | j                          y r_   )r$   r   r   r   r}   s         r   r   z$StreamlitCallbackHandler.on_tool_endp  sF     V3%%'33E-z	
=C	
 	&&(r   c                f     | j                         j                  |fi | | j                          y r_   )r   r   r   rr   s      r   r   z&StreamlitCallbackHandler.on_tool_error~  s,    5%%'55eFvF**,r   c                     y r_   r!   )rQ   r   r   endri   s        r   on_textz StreamlitCallbackHandler.on_text  r   r   c                     y r_   r!   )rQ   ra   inputsri   s       r   on_chain_startz'StreamlitCallbackHandler.on_chain_start  s     	r   c                     y r_   r!   )rQ   outputsri   s      r   on_chain_endz%StreamlitCallbackHandler.on_chain_end      r   c                     y r_   r!   rr   s      r   on_chain_errorz'StreamlitCallbackHandler.on_chain_error  r   r   c                h     | j                         j                  ||fi | | j                          y r_   )r   r   r   r   s       r   r   z(StreamlitCallbackHandler.on_agent_action  s0     	8%%'77PP**,r   c                    | j                   ;| j                   j                  | j                  j                                d | _         y y r_   )r   r   r   r@   )rQ   finishr   ri   s       r   on_agent_finishz(StreamlitCallbackHandler.on_agent_finish  sE       ,!!**%%CCE %)D!	 -r   )
rG   r   r   intr   rB   r   rB   r   zOptional[LLMThoughtLabeler])rA   rE   )rA   zOptional[LLMThought])rA   r   r_   r   r   )ra   r   rb   r   ri   r   rA   r   r   r   r   r   r   r   r\   )
r   r$   r   r   r   r$   ri   r   rA   r   )ra   r   r   r   ri   r   rA   r   )r   r   ri   r   rA   r   r   )r   r   r   r   ri   r   rA   r   )r   r   r   r    rT   r   r   r   r   r   r   rc   rj   rn   rt   r{   r   r   r   r   r   r   r   r   r!   r   r   r   r      s   : '($(,07;&G(&G !$	&G
 "&G &*&G 5&GP% 
 
%#0@(@3<@HK@	@ ----(-58-DG-	-  $,0$()) ) *	)
 ") ) 
)-  $	  	
  
(2@LO	
 ;?-!-*7-JM-	- ;?)!)*7)JM)	)r   r   N)r   r$   rA   r$   )!r    
__future__r   enumr   typingr   r   r   r   r	   r
   langchain_core.agentsr   r   langchain_core.callbacksr   langchain_core.outputsr   8langchain_community.callbacks.streamlit.mutable_expanderr   streamlit.delta_generatorr   r   r1   r+   r=   r2   r   r#   r)   rE   r   r!   r   r   <module>r      s    0 "  G G : 8 , T8& "d  <2 <2~t  t n|)2 |)r   