
    Ng,                     p   d dl Z d dlmZmZmZmZ d dlmZ d dlm	Z	 d dl
mZ d dlmZ d dlmZ dZd	Zd
ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!dZ"eeegZ#edgdz  edgdz  edgdz  e!dgdz  e"dgdz  edgdz  edgdz  ed egdz  ed egdz  ed egdz  e degdz  iZ$d efd!Z% G d" d#e	          Z&dS )$    N)AnyDictListOptional)UUID)BaseCallbackHandler)	LLMResultguard_import)import_pandastoken_usagetotal_tokensprompt_tokenscompletion_tokensrun_id
model_namegoodbadneutralsuccessfailurei   i promptresponsecontextdurationfeedback
llm_statusfiddler
   z$123e4567-e89b-12d3-a456-426614174000      returnc                  $    t          dd          S )zLImport the fiddler python package and raise an error if it is not installed.r   zfiddler-client)pip_namer
        j/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/callbacks/fiddler_callback.pyimport_fiddlerr(   8   s    	,<====r&   c                       e Zd Zdedededededdf fdZedefd	            Z	 	 ddede	e         de
dedee         deeeef                  ddfdZdeeef         de	e         dedefdZdededdfdZdededdfdZ xZS )FiddlerCallbackHandlerurlorgprojectmodelapi_keyr"   Nc                    t                                                       t                      | _        t	                      | _        || _        || _        || _        || _	        || _
        | j                            t                    | _        i | _        i | _        i | _        | j                            |||          | _        | j        | j                                        vret)          d| j         d           	 | j                            | j                   n,# t,          $ r}t)          d| j         d           |d}~ww xY w| j        j                            | j        d          }t3          t5          |j                            D ]}|j        |         j        t:          k    r9| j        j        j        |j        |         _         tB          |j        |         _"        V|j        |         j        tF          k    r?| j        j        j        |j        |         _         tH          tJ          g|j        |         _"        | j	        | j        &                    | j                  vr| j	        | j        '                    | j                  vrt)          d	| j	         d
| j         d           	 | j        (                    | j        | j	        d| j        i|           n/# t,          $ r"}t)          d| j	         d| d           |d}~ww xY w| j        j)        *                    |d| j        j+        j,        tZ          t\          t^          gt:          t`          tb          td          tf          th          tj          g| j6                  }	t)          d| j	         d
| j         d           	 | j        7                    | j        | j	        | j	        |	           dS # t,          $ r"}t)          d| j	         d| d           |d}~ww xY wdS )a  
        Initialize Fiddler callback handler.

        Args:
            url: Fiddler URL (e.g. https://demo.fiddler.ai).
                Make sure to include the protocol (http/https).
            org: Fiddler organization id
            project: Fiddler project name to publish events to
            model: Fiddler model name to publish events to
            api_key: Fiddler authentication token
        )org_id
auth_tokenzadding project z.This only has to be done once.zError adding project z(:{e}. Fiddler integration will not work.Nr   )max_inferred_cardinalityzadding dataset z to project train)
project_id
dataset_iddatasetinfozError adding dataset z: z#.Fiddler integration will not work.)dataset_infor6   
model_taskfeaturestargetmetadata_colscustom_featureszadding model )r5   r6   model_id
model_infozError adding model )8super__init__r(   fdlr   pdr+   r,   r-   r.   r/   	DataFrame_dataset_dict_dfrun_id_promptsrun_id_responserun_id_starttime
FiddlerApifiddler_clientget_project_namesprintadd_project	ExceptionDatasetInfofrom_dataframerangelencolumnsnameFEEDBACKDataTypeCATEGORY	data_typeFEEDBACK_POSSIBLE_VALUESpossible_values
LLM_STATUSSUCCESSFAILUREget_model_namesget_dataset_namesupload_dataset	ModelInfofrom_dataset_info	ModelTaskLLMPROMPTCONTEXTRESPONSERUN_IDTOTAL_TOKENSPROMPT_TOKENSCOMPLETION_TOKENS
MODEL_NAMEDURATIONr>   	add_model)selfr+   r,   r-   r.   r/   er9   ir@   	__class__s             r'   rB   zFiddlerCallbackHandler.__init__?   s   & 	!##//
7$$]33576813 #h11#cg1VV<t2DDFFFFR$,RRR  #//====   >DL > > >    x+::Hq ; 
 

 s</0011 	M 	MA#A&+x7748H4E4N$Q'1:R$Q'77%a(-;;48H4E4N$Q'1;BG:L$Q'7:T0@@NNNNz!4!F!Ft|!T!TTT5dj 5 5dl 5 5 5  '66#'<#':!($( 3)	 7     !   =
 = =a = = =   G +==)"8-1 '84 !% !% 4 >  J  1
 1 1 1 1 1  #--#|#z!Z)	 .         9$* 9 9 9 9 9   _ ONsH   ?D 
E)EE1/K! !
L+LL&-O 
PO<<Pc                    | j                             ddt          g          | j                             dt          d          | j                             ddt          g          | j                             dt          d          | j                             dd	t          t          gd
g di          | j                             ddt          t          g          | j                             ddt          t          g          gS )a[  
        Define custom features for the model to automatically enrich the data with.
        Here, we enable the following enrichments:
        - Automatic Embedding generation for prompt and response
        - Text Statistics such as:
            - Automated Readability Index
            - Coleman Liau Index
            - Dale Chall Readability Score
            - Difficult Words
            - Flesch Reading Ease
            - Flesch Kincaid Grade
            - Gunning Fog
            - Linsear Write Formula
        - PII - Personal Identifiable Information
        - Sentiment Analysis

        zPrompt Embedding	embedding)rV   
enrichmentrU   z	Prompt CF)rV   source_columncolumnzResponse EmbeddingzResponse CFzText Statisticstextstat
statistics)automated_readability_indexcoleman_liau_indexdale_chall_readability_scoredifficult_wordsflesch_reading_easeflesch_kincaid_gradegunning_foglinsear_write_formula)rV   rw   rU   configPIIpii	Sentiment	sentiment)rC   
Enrichmentrg   TextEmbeddingri   )rq   s    r'   r>   z&FiddlerCallbackHandler.custom_features   s:   * H'&    
 H"" $) #  
 H)&!
    
 H"""&+ #  
 H&%*  	# 	# 	#	    " H *    
 H &*    W0
 0	
r&    r   prompt_responsesr   r   r   token_usage_dictc                    t          | j        |                   }| j                            t          | j        |         t
          |t          t          |          g|z  t          |g|z  t          |g|z  t          |g|z  i          }|r:|                                D ]%\  }	}
t          |
t                    r|
g|z  n|
||	<   &	 |j        d         dk    r(| j                            | j        | j        |           dS |                    d          }| j                            | j        | j        |d                    dS # t*          $ r}t-          d| d           Y d}~dS d}~ww xY w)	z+
        Publish events to fiddler
        r   r!   records)orient)eventz$Error publishing events to fiddler: z. continuing...N)rT   rH   rD   rE   rg   ri   rj   strro   r]   rn   items
isinstanceintshaperL   publish_events_batchr-   r.   to_dictpublish_eventrP   rN   )rq   r   r   r   r   r   r   prompt_countdfkeyvaluedf_dictrr   s                r'   _publish_eventsz&FiddlerCallbackHandler._publish_events   s    4.v677W+F3*V48*|3ZL<7ZL<7	
 	
  	V.4466 V V
U4>uc4J4JU5'L00PU3	x{Q#88tzSUVVVVV**I*66#11L$*GAJ 2       	 	 	IqIII        	s   7E =AE 
E*E%%E*
serializedpromptskwargsc                     |t                    }|| j        |<   t          t          j                    dz            | j        |<   d S )N  )rj   rH   r   timerJ   )rq   r   r   r   r   s        r'   on_llm_startz#FiddlerCallbackHandler.on_llm_start&  s@     &-F#(+DIKK$,>(?(?f%%%r&   r   c                    |                                 }|t                   }t          t          j                    dz            | j        |         z
  }d}i }t          |j        t                    rCd |j                                        D             }|j        	                    t          d          }d |D             }|                     |||t          ||           d S )Nr   r   c                 F    i | ]\  }}|t           t          t          fv ||S r%   )rk   rl   rm   ).0kvs      r'   
<dictcomp>z5FiddlerCallbackHandler.on_llm_end.<locals>.<dictcomp>5  s;          Aq}6GHHH 1HHHr&   c                 >    g | ]}|j         d          d          j        S )r   )generationstext)r   	llmresults     r'   
<listcomp>z5FiddlerCallbackHandler.on_llm_end.<locals>.<listcomp><  s5     
 
 
1:I!!$Q',
 
 
r&   )flattenrj   r   r   rJ   r   
llm_outputdictr   getrn   r   r^   )	rq   r   r   flattened_llmresultr   run_durationr   r   r   s	            r'   
on_llm_endz!FiddlerCallbackHandler.on_llm_end-  s    &..0049;;-..1Fv1NN
h)400 	A   $/5577     
 ",00R@@J
 
>Q
 
 
 		
 	
 	
 	
 	
r&   errorc                     |t                    }t          t          j                    dz            | j        |         z
  }|                     |dgt          | j        |                   z  |t                     d S )Nr   r   )rj   r   r   rJ   r   rT   rH   r_   )rq   r   r   r   r   s        r'   on_llm_errorz#FiddlerCallbackHandler.on_llm_errorI  sr    ty{{T)**T-B6-JJRD3t26:;;;Xw	
 	
 	
 	
 	
r&   )r   N)__name__
__module____qualname__r   rB   propertylistr>   r   r   r   r   r   r   r   r   r	   r   BaseExceptionr   __classcell__)rt   s   @r'   r*   r*   >   s       uu u 	u
 u u 
u u u u u un C
 C
 C
 C
 XC
V %'59( (( s)( 	(
 ( SM( #4S>2( 
( ( ( (T@sCx.@379@HK@	@ @ @ @
9 
 
 
 
 
 
8
- 
3 
4 
 
 
 
 
 
 
 
r&   r*   )'r   typingr   r   r   r   uuidr   langchain_core.callbacksr   langchain_core.outputsr	   langchain_core.utilsr   #langchain_community.callbacks.utilsr   TOKEN_USAGErk   rl   rm   rj   rn   GOODBADNEUTRALr^   r_   DEFAULT_MAX_TOKENDEFAULT_MAX_DURATIONrg   ri   rh   ro   rW   r]   r[   rF   r(   r*   r%   r&   r'   <module>r      s    , , , , , , , , , , , ,       8 8 8 8 8 8 , , , , , , - - - - - - = = = = = =
 ' 	



    


 #w/  YK"ykBi[2vhmb b 
34r91'(1,A()A-,-1q&'!+> > > > >Q
 Q
 Q
 Q
 Q
0 Q
 Q
 Q
 Q
 Q
r&   