o
    Ag,                     @   sN  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 edgd edgd e!dgd e"dgd edgd edgd ed egd ed egd ed egd e degd iZ$d efd!d"Z%G d#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                   C   s   t dddS )zLImport the fiddler python package and raise an error if it is not installed.r   zfiddler-client)pip_namer	    r#   r#   u/var/www/html/development/chatbot/venv/lib/python3.10/site-packages/langchain_community/callbacks/fiddler_callback.pyimport_fiddler8   s   r%   c                       s   e Zd Zdedededededdf fdd	Zedefd
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dZdeeef de	e dedefddZdededdfddZdededdfddZ  ZS )!FiddlerCallbackHandlerurlorgprojectmodelapi_keyr!   Nc           
         s  t    t | _t | _|| _|| _|| _|| _	|| _
| jt| _i | _i | _i | _| jj|||d| _| j| j vrhtd| j d z	| j| j W n tyg } ztd| j d |d}~ww | jjj| jdd}tt|jD ]3}|j| jtkr| jjj|j| _ t!|j| _"qy|j| jt#kr| jjj|j| _ t$t%g|j| _"qy| j	| j&| jvrO| j	| j'| jvrtd	| j	 d
| j d z| jj(| j| j	d| ji|d W n ty } ztd| j	 d| d |d}~ww | jj)j*|d| jj+j,t-t.t/gtt0t1t2t3t4t5g| j6d}	td| j	 d
| j d z| jj7| j| j	| j	|	d W dS  tyN } ztd| j	 d| d |d}~w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_infor1   
model_taskfeaturestargetmetadata_colscustom_featureszadding model )r0   r1   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DURATIONr9   	add_model)
selfr'   r(   r)   r*   r+   er4   ir;   	__class__r#   r$   r=   ?   s   

zFiddlerCallbackHandler.__init__c                 C   s   | j jddtgd| j jdtdd| j jddtgd| j jdtdd| j jdd	ttgd
g did| j jddttgd| j jddttgd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)rQ   
enrichmentrP   z	Prompt CF)rQ   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)rQ   rr   rP   configPIIpii	Sentiment	sentiment)r>   
Enrichmentrb   TextEmbeddingrd   )rl   r#   r#   r$   r9      sL   z&FiddlerCallbackHandler.custom_features r   prompt_responsesr   r   r   token_usage_dictc                 C   s  t | j| }| jt| j| t|tt|g| t|g| t	|g| t
|g| i}|rC| D ]\}	}
t|
tr>|
g| n|
||	< q0z*|jd dkrX| j| j| j| W dS |jdd}| jj| j| j|d d W dS  ty } ztd| d W Y d}~dS d}~ww )	z+
        Publish events to fiddler
        r   r    records)orient)eventz$Error publishing events to fiddler: z. continuing...N)rO   rC   r?   r@   rb   rd   re   strrj   rX   ri   items
isinstanceintshaperG   publish_events_batchr)   r*   to_dictpublish_eventrK   rI   )rl   r   r   r   r   r   r   prompt_countdfkeyvaluedf_dictrm   r#   r#   r$   _publish_events   s4   




z&FiddlerCallbackHandler._publish_events
serializedpromptskwargsc                 K   s,   |t  }|| j|< tt d | j|< d S )N  )re   rC   r   timerE   )rl   r   r   r   r   r#   r#   r$   on_llm_start&  s   
z#FiddlerCallbackHandler.on_llm_startr   c           	      K   s   |  }|t }tt d | j|  }d}i }t|jtr0dd |j D }|j	t
d}dd |D }| |||t|| d S )Nr   r   c                 S   s$   i | ]\}}|t ttfv r||qS r#   )rf   rg   rh   ).0kvr#   r#   r$   
<dictcomp>5  s
    z5FiddlerCallbackHandler.on_llm_end.<locals>.<dictcomp>c                 S   s   g | ]
}|j d  d  jqS )r   )generationstext)r   	llmresultr#   r#   r$   
<listcomp><  s    z5FiddlerCallbackHandler.on_llm_end.<locals>.<listcomp>)flattenre   r   r   rE   r   
llm_outputdictr   getri   r   rY   )	rl   r   r   flattened_llmresultr   run_durationr   r   r   r#   r#   r$   
on_llm_end-  s*   z!FiddlerCallbackHandler.on_llm_enderrorc                 K   sF   |t  }tt d | j|  }| |dgt| j|  |t d S )Nr   r   )re   r   r   rE   r   rO   rC   rZ   )rl   r   r   r   r   r#   r#   r$   on_llm_errorI  s
   z#FiddlerCallbackHandler.on_llm_error)r   N)__name__
__module____qualname__r   r=   propertylistr9   r   r   r   r   r   r   r   r   r   r   BaseExceptionr   __classcell__r#   r#   ro   r$   r&   >   sX    wK
*

r&   )'r   typingr   r   r   r   uuidr   langchain_core.callbacksr   langchain_core.outputsr   langchain_core.utilsr
   #langchain_community.callbacks.utilsr   TOKEN_USAGErf   rg   rh   re   ri   GOODBADNEUTRALrY   rZ   DEFAULT_MAX_TOKENDEFAULT_MAX_DURATIONrb   rd   rc   rj   rR   rX   rV   rA   r%   r&   r#   r#   r#   r$   <module>   sR    







