
    NgR                     R   d dl Z d dl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 d dlmZmZ d dlm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efdZdee ef         de!fdZ"	 	 	 	 dde de#de#dede
ee ef                  de!fdZ$de de defdZ% G d dee          Z&dS )    N)deepcopy)Path)AnyDictListOptionalSequenceUnion)warn_deprecated)AgentActionAgentFinish)BaseCallbackHandler)	LLMResultguard_import)BaseMetadataCallbackHandlerflatten_dicthash_stringimport_pandasimport_spacyimport_textstatreturnc                       t          d          S )zJImport the wandb python package and raise an error if it is not installed.wandbr        h/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/callbacks/wandb_callback.pyimport_wandbr      s       r   	json_pathc                 ~    t          | d          5 }t          j        |          }ddd           n# 1 swxY w Y   |S )zLoad json file to a dictionary.

    Parameters:
        json_path (str): The path to the json file.

    Returns:
        (dict): The dictionary representation of the json file.
    rN)openjsonload)r   fdatas      r   load_json_to_dictr'      sx     
i		 y||              Ks   266Ttextcomplexity_metrics	visualizenlp
output_dirc                    i }t                      }t                      }t                      }|rwi d|                    |           d|                    |           d|                    |           d|                    |           d|                    |           d|                    |           d|	                    |           d|
                    |           d	|                    |           d
|                    |           d|                    |           d|                    |           d|                    |           d|                    |           d|                    |           d|                    |           }	|                    |	           |rA|r>|; ||           }
|j                            |
ddd          }t-          |t/          d|            dz             }|                    dd                              |           |j                            |
ddd          }t-          |t/          d|            dz             }|                    dd                              |           |                    t7          |                    |                    t7          |                    d}|                    |           |S )a  Analyze text using textstat and spacy.

    Parameters:
        text (str): The text to analyze.
        complexity_metrics (bool): Whether to compute complexity metrics.
        visualize (bool): Whether to visualize the text.
        nlp (spacy.lang): The spacy language model to use for visualization.
        output_dir (str): The directory to save the visualization files to.

    Returns:
        (dict): A dictionary containing the complexity metrics and visualization
            files serialized in a wandb.Html element.
    flesch_reading_easeflesch_kincaid_grade
smog_indexcoleman_liau_indexautomated_readability_indexdale_chall_readability_scoredifficult_wordslinsear_write_formulagunning_fogtext_standardfernandez_huertaszigriszt_pazosgutierrez_polinicrawfordgulpease_indexosmanNdepFT)stylejupyterpagezdep-z.htmlwzutf-8)encodingentzent-)dependency_treeentities)r   r   r   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   updatedisplacyrenderr   r   r"   writeHtmlstr)r(   r)   r*   r+   r,   resptextstatr   spacytext_complexity_metricsdocdep_outdep_output_pathent_outent_output_pathtext_visualizationss                   r   analyze_textrW   *   s-   ( D  HNNENNE -#
!8#?#?#E#E#
"H$A$A$$G$G#
 (--d33#
 !("="=d"C"C	#

 *8+O+OPT+U+U#
 +H,Q,QRV,W,W#
 x77==#
 $X%C%CD%I%I#
 8//55#
 X33D99#
  9 9$ ? ?#
 x77==#
  9 9$ ? ?#
 ))$//#
 h55d;;#
  X^^D))!#
$ 	+,,, )S )Z3c$ii.''5%d'SSz;}d}}+E+E+OPPS73399'BBB.''5%d'SSz;}d}}+E+E+OPPS73399'BBB  %zz#o*>*>??

3#7#788
 
 	'(((Kr   prompt
generationc                     t                      }|                     dd          }|                    dd          }|                    d| d| dd          S )zConstruct an html element from a prompt and a generation.

    Parameters:
        prompt (str): The prompt.
        generation (str): The generation.

    Returns:
        (wandb.Html): The html element.
z<br>z
    <p style="color:black;">z>:</p>
    <blockquote>
      <p style="color:green;">
        z"
      </p>
    </blockquote>
    F)inject)r   replacerK   )rX   rY   r   formatted_promptformatted_generations        r   )construct_html_from_prompt_and_generationr`   k   s}     NNE~~dF33%--dF;;::	-	 	 
		 	 	   
 
 
r   c                        e Zd ZdZ	 	 	 	 	 	 	 	 	 	 d1dee         dee         dee         dee         d	ee         d
ee         dee         dedededdf fdZde	fdZ
de	eef         dee         deddfdZdededdfdZdededdfdZdededdfdZde	eef         de	eef         deddfdZde	eef         deddfdZdededdfd Zde	eef         d!ededdfd"Zd#ededdfd$Zdededdfd%Zd&ededdfd'Zd(ededdfd)Zd*ededefd+Zdefd,Z	 	 	 	 	 	 	 	 	 	 	 	 d2d.ed/ed(edee         dee         dee         dee         d	ee         d
ee         dee         dee         dee         ddfd0Z xZ S )3WandbCallbackHandlera  Callback Handler that logs to Weights and Biases.

    Parameters:
        job_type (str): The type of job.
        project (str): The project to log to.
        entity (str): The entity to log to.
        tags (list): The tags to log.
        group (str): The group to log to.
        name (str): The name of the run.
        notes (str): The notes to log.
        visualize (bool): Whether to visualize the run.
        complexity_metrics (bool): Whether to log complexity metrics.
        stream_logs (bool): Whether to stream callback actions to W&B

    This handler will utilize the associated callback method called and formats
    the input of each callback function with metadata regarding the state of LLM run,
    and adds the response to the list of records for both the {method}_records and
    action. It then logs the response using the run.log() method to Weights and Biases.
    Nlangchain_callback_demoFjob_typeprojectentitytagsgroupnamenotesr*   r)   stream_logsr   c           	         t                      }t                       t                       t                      }t	                                                       || _        || _        || _        || _	        || _
        || _        || _        || _        |	| _        |
| _        t!          j                    | _        |                    | j        | j        | j        | j	        | j
        | j        | j                  | _        d}|                    |d           g | _        g | _        |	| _        || _        |                    d          | _        t5          dddd	           d
S )zInitialize callback handler.)rd   re   rf   rg   rh   ri   rj   zDEPRECATION: The `WandbCallbackHandler` will soon be deprecated in favor of the `WandbTracer`. Please update your code to use the `WandbTracer` instead.F)repeaten_core_web_smz0.3.8zPlease use the WeaveTracer instead of the WandbCallbackHandler. The WeaveTracer is a more flexible and powerful tool for logging and tracing your LangChain callables.Find more information at https://weave-docs.wandb.ai/guides/integrations/langchainzPlease instantiate the WeaveTracer from weave.integrations.langchain import WeaveTracer .For autologging simply use weave.init() and log all traces from your LangChain callables.)pendingmessagealternativeN)r   r   r   r   super__init__rd   re   rf   rg   rh   ri   rj   r*   r)   rk   tempfileTemporaryDirectorytemp_dirinitruntermwarncallback_columnsaction_recordsr$   r+   r   )selfrd   re   rf   rg   rh   ri   rj   r*   r)   rk   r   rO   warning	__class__s                 r   rs   zWandbCallbackHandler.__init__   sk     	
	
""4& 355::]L;**  
 
 	
 	 	 	
 	
 	
 ')$&"4"::.//e1	
 	
 	
 	
 	
 	
r   c                 $    d | j         D             S )Nc                     i | ]}|d S )Nr   ).0ks     r   
<dictcomp>z3WandbCallbackHandler._init_resp.<locals>.<dictcomp>   s    777A4777r   )rz   )r|   s    r   
_init_respzWandbCallbackHandler._init_resp   s    77!67777r   
serializedpromptskwargsc                 *   | xj         dz  c_         | xj        dz  c_        | xj        dz  c_        |                                 }|                    ddi           |                    t          |                     |                    |                                            |D ]k}t          |          }||d<   | j        	                    |           | j
        	                    |           | j        r| j                            |           ldS )zRun when LLM starts.   actionon_llm_startr   N)step
llm_startsstartsr   rG   r   get_custom_callback_metar   on_llm_start_recordsappendr{   rk   rx   log)r|   r   r   r   rM   rX   prompt_resps          r   r   z!WandbCallbackHandler.on_llm_start   s    			Q		1q  X~.///L,,---D1133444 	* 	*F"4..K%+K	"%,,[999&&{333 *[)))	* 	*r   tokenc                    | xj         dz  c_         | xj        dz  c_        |                                 }|                    d|d           |                    |                                            | j                            |           | j                            |           | j        r| j	        
                    |           dS dS )z#Run when LLM generates a new token.r   on_llm_new_token)r   r   N)r   llm_streamsr   rG   r   on_llm_token_recordsr   r{   rk   rx   r   )r|   r   r   rM   s       r   r   z%WandbCallbackHandler.on_llm_new_token   s    		Q		A  1EBBCCCD1133444!((...""4((( 	HLL	 	r   responsec                 4   | xj         dz  c_         | xj        dz  c_        | xj        dz  c_        |                                 }|                    ddi           |                    t          |j        pi                      |                    |                                            |j        D ]}|D ]}t          |          }|                    t          |
                                                     |                    t          |j        | j        | j        | j        | j        j                             | j                            |           | j                            |           | j        r| j                            |           dS )zRun when LLM ends running.r   r   
on_llm_end)r)   r*   r+   r,   N)r   llm_endsendsr   rG   r   
llm_outputr   generationsr   dictrW   r(   r)   r*   r+   rv   ri   on_llm_end_recordsr   r{   rk   rx   r   )r|   r   r   rM   r   rY   generation_resps          r   r   zWandbCallbackHandler.on_llm_end	  s   		Q				Q		  X|,---L!4!:;;<<<D1133444#/ 	2 	2K) 2 2
"*4..&&|JOO4E4E'F'FGGG&& "+/+B"&. H#'=#5     '..???#**?;;;# 2HLL1112	2 	2r   errorc                 F    | xj         dz  c_         | xj        dz  c_        dS )zRun when LLM errors.r   Nr   errorsr|   r   r   s      r   on_llm_errorz!WandbCallbackHandler.on_llm_error&  %    		Q		qr   inputsc                    | xj         dz  c_         | xj        dz  c_        | xj        dz  c_        |                                 }|                    ddi           |                    t          |                     |                    |                                            |d         }t          |t                    rmt          |          }||d<   | j
                            |           | j                            |           | j        r| j                            |           dS dS t          |t                     r|D ]{}t          |          }|                    |           | j
                            |           | j                            |           | j        r| j                            |           |dS t#          d          )zRun when chain starts running.r   r   on_chain_startinputz Unexpected data format provided!N)r   chain_startsr   r   rG   r   r   
isinstancerL   r   on_chain_start_recordsr   r{   rk   rx   r   list
ValueError)r|   r   r   r   rM   chain_input
input_respinps           r   r   z#WandbCallbackHandler.on_chain_start+  s    			Q		Qq  X/0111L,,---D1133444Wok3'' 	A!$J"-Jw'..z:::&&z222 )Z((((() )T** 		A" - -%d^^
!!#&&&+22:>>>#**:666# -HLL,,,- - ?@@@r   outputsc                    | xj         dz  c_         | xj        dz  c_        | xj        dz  c_        |                                 }|                    d|d         d           |                    |                                            | j                            |           | j                            |           | j	        r| j
                            |           dS dS )zRun when chain ends running.r   on_chain_endoutput)r   r   N)r   
chain_endsr   r   rG   r   on_chain_end_recordsr   r{   rk   rx   r   )r|   r   r   rM   s       r   r   z!WandbCallbackHandler.on_chain_endL  s    		Q		1		Q		  ~'(:KLLMMMD1133444!((...""4((( 	HLL	 	r   c                 F    | xj         dz  c_         | xj        dz  c_        dS )zRun when chain errors.r   Nr   r   s      r   on_chain_errorz#WandbCallbackHandler.on_chain_error[  r   r   	input_strc                    | xj         dz  c_         | xj        dz  c_        | xj        dz  c_        |                                 }|                    d|d           |                    t          |                     |                    |                                            | j                            |           | j	                            |           | j
        r| j                            |           dS dS )zRun when tool starts running.r   on_tool_start)r   r   N)r   tool_startsr   r   rG   r   r   on_tool_start_recordsr   r{   rk   rx   r   )r|   r   r   r   rM   s        r   r   z"WandbCallbackHandler.on_tool_start`  s     			Q		Aq  YGGHHHL,,---D1133444"))$///""4((( 	HLL	 	r   r   c                    t          |          }| xj        dz  c_        | xj        dz  c_        | xj        dz  c_        |                                 }|                    d|d           |                    |                                            | j                            |           | j	                            |           | j
        r| j                            |           dS dS )zRun when tool ends running.r   on_tool_end)r   r   N)rL   r   	tool_endsr   r   rG   r   on_tool_end_recordsr   r{   rk   rx   r   )r|   r   r   rM   s       r   r   z WandbCallbackHandler.on_tool_endr  s    V		Q		!		Q		  }??@@@D1133444 ''---""4((( 	HLL	 	r   c                 F    | xj         dz  c_         | xj        dz  c_        dS )zRun when tool errors.r   Nr   r   s      r   on_tool_errorz"WandbCallbackHandler.on_tool_error  r   r   r(   c                    | xj         dz  c_         | xj        dz  c_        |                                 }|                    d|d           |                    |                                            | j                            |           | j                            |           | j        r| j	        
                    |           dS dS )z+
        Run when agent is ending.
        r   on_text)r   r(   N)r   text_ctrr   rG   r   on_text_recordsr   r{   rk   rx   r   )r|   r(   r   rM   s       r   r   zWandbCallbackHandler.on_text  s     			Q		  y$77888D1133444##D)))""4((( 	HLL	 	r   finishc                    | xj         dz  c_         | xj        dz  c_        | xj        dz  c_        |                                 }|                    d|j        d         |j        d           |                    |                                            | j        	                    |           | j
        	                    |           | j        r| j                            |           dS dS )zRun when agent ends running.r   on_agent_finishr   )r   r   r   N)r   
agent_endsr   r   rG   return_valuesr   r   on_agent_finish_recordsr   r{   rk   rx   )r|   r   r   rM   s       r   r   z$WandbCallbackHandler.on_agent_finish  s    		Q		1		Q		  + .x8z 	
 	
 	
 	D1133444$++D111""4((( 	HLL	 	r   r   c                    | xj         dz  c_         | xj        dz  c_        | xj        dz  c_        |                                 }|                    d|j        |j        |j        d           |                    |                                            | j	        
                    |           | j        
                    |           | j        r| j                            |           dS dS )zRun on agent action.r   on_agent_action)r   tool
tool_inputr   N)r   r   r   r   rG   r   r   r   r   on_agent_action_recordsr   r{   rk   rx   )r|   r   r   rM   s       r   r   z$WandbCallbackHandler.on_agent_action  s    		Q		Aq  +$/z	 	
 	
 	
 	D1133444$++D111""4((( 	HLL	 	r   c                    t                      }|                    | j                  }|                    | j                  }|g d                             d                              ddid          }g }g }| j        rg d}| j        rddg}|g d	|z   |z                                d                              d
ddd          }|                    ||gd          }|ddg         	                    d d          |d<   |S )z=Create a dataframe with all the information from the session.)r   r   ri   r   )axisr   prompt_step)r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   rE   rF   )r   r(   token_usage_total_tokenstoken_usage_prompt_tokenstoken_usage_completion_tokensoutput_stepr   )r   r(   r   c                 :    t          | d         | d                   S )Nr   r   )r`   )rows    r   <lambda>zBWandbCallbackHandler._create_session_analysis_df.<locals>.<lambda>  s    AIH  r   	chat_html)
r   	DataFramer   r   dropnarenamer)   r*   concatapply)	r|   pdon_llm_start_records_dfon_llm_end_records_dfllm_input_prompts_dfcomplexity_metrics_columnsvisualizations_columnsllm_outputs_dfsession_analysis_dfs	            r   _create_session_analysis_dfz0WandbCallbackHandler._create_session_analysis_df  so   __"$,,t/H"I"I "T-D E E $$?$?$?@VV^^VV]+!V44 	
 &("!#" 	* * *&& > 	E&7%D" "   -- ))
 VV^^V]H==AVFF 	 !ii)=~(NUViWW+>!,

%  	  
 
 	K( #"r   Tlangchain_assetresetc                 `   t                      }t                      }|                    |                    | j                            }|                    |                                           }| j                            ||d           |r^t          | j	        j
        d          }|                    dd          }|                    |d           |                    |d           	 |                    |           |                    t          |                     t!          |          |_        n# t$          $ rN |                    |           |                    t          |                     t!          |          |_        Y nAt(          $ r5}t+          d	           t+          t-          |                     Y d
}~nd
}~ww xY w| j                            |           |s|rF| j                                         | j	                                         |                                  |rq|                     |r|n| j        |r|n| j        |r|n| j        |r|n| j        |r|n| j         |	r|	n| j
        |
r|
n| j!        |r|n| j"        |r|n| j#        	  	         d
S d
S )aS  Flush the tracker and reset the session.

        Args:
            langchain_asset: The langchain asset to save.
            reset: Whether to reset the session.
            finish: Whether to finish the run.
            job_type: The job type.
            project: The project.
            entity: The entity.
            tags: The tags.
            group: The group.
            name: The name.
            notes: The notes.
            visualize: Whether to visualize.
            complexity_metrics: Whether to compute complexity metrics.

            Returns:
                None
        )	dataframe)r{   session_analysisz
model.jsonmodel)ri   typer{   )ri   r   zCould not save model.N)	rd   re   rf   rg   rh   ri   rj   r*   r)   )$r   r   Tabler   r{   r   rx   r   r   rv   ri   Artifactaddsaveadd_filerL   r'   metadatar   
save_agentNotImplementedErrorprintreprlog_artifactr   cleanupreset_callback_metars   rd   re   rf   rg   rh   rj   r*   r)   )r|   r   r   r   rd   re   rf   rg   rh   ri   rj   r*   r)   r   r   action_records_tablesession_analysis_tablelangchain_asset_pathmodel_artifactes                       r   flush_trackerz"WandbCallbackHandler.flush_tracker   s   D __${{R\\$BU5V5V{WW!&6688 "- "
 "
 	"6$: 	
 	
 	
  	2#'(:L#I#I "^^w^GGN3:JKKK5<NOOO$$%9:::'',@(A(ABBB*;<P*Q*Q'' R R R**+?@@@'',@(A(ABBB*;<P*Q*Q'''&   -...d1gg H!!.111 	'U 	'HOOM!!###$$&&& 	MM%-@4=#*<!'8vvT[!0TTty$4ee$*!0TTty$4ee$*'0D))dn *1&&0      	 	s    3AD? ?AG	G+GG)
Nrc   NNNNNFFF)NTFNNNNNNNNN)!__name__
__module____qualname____doc__r   rL   r	   boolrs   r   r   r   r   r   r   r   r   BaseExceptionr   r   r   r   r   r   r   r   r   r   r   r   r   r
  __classcell__)r~   s   @r   rb   rb      s        , #'!: $#'#"##(!G
 G
3-G
 #G
 	G

 x G
 }G
 smG
 }G
 G
 !G
 G
 
G
 G
 G
 G
 G
 G
R8D 8 8 8 8*sCx.*379*HK*	* * * **c S T    29 2 2 2 2 2 2:- 3 4    
AsCx.A26sCx.ALOA	A A A ABDcN c d    M S T    
sCx.58DG	   $#       = C D    
C 3 4     k S T    *k S S    *=#S =# =# =# =#B  $"&!% $#'#"#$(-1U UU U 	U
 3-U #U U x U }U smU }U D>U %TNU 
U U U U U U U Ur   rb   )TTNN)'r#   rt   copyr   pathlibr   typingr   r   r   r   r	   r
   langchain_core._apir   langchain_core.agentsr   r   langchain_core.callbacksr   langchain_core.outputsr   langchain_core.utilsr   #langchain_community.callbacks.utilsr   r   r   r   r   r   r   rL   r   r'   r  rW   r`   rb   r   r   r   <module>r     s:                 = = = = = = = = = = = = = = = = / / / / / / : : : : : : : : 8 8 8 8 8 8 , , , , , , - - - - - -               !c ! ! ! !
sDy!1 d       $-1> >
>> > 
	>
 sDy)*> 
> > > >Bc s s    4P P P P P68K P P P P Pr   