o
    Zh,                     @   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_pandasZtoken_usageZtotal_tokensZprompt_tokensZcompletion_tokensrun_id
model_nameZgoodbadZneutralsuccessZfailurei   i promptresponsecontextdurationZ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)Zpip_namer	    r   r   e/var/www/html/lang_env/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
        )Zorg_idZ
auth_tokenzadding project z.This only has to be done once.zError adding project z(:{e}. Fiddler integration will not work.Nr   )Zmax_inferred_cardinalityzadding dataset z to project train)
project_id
dataset_idZdatasetinfozError adding dataset z: z#.Fiddler integration will not work.)dataset_infor%   Z
model_taskfeaturestargetZmetadata_colscustom_featureszadding model )r$   r%   Zmodel_id
model_infozError adding model )8super__init__r   fdlr   pdr   r   r    r!   r"   	DataFrame_dataset_dictZ_dfrun_id_promptsZrun_id_responserun_id_starttimeZ
FiddlerApifiddler_clientZget_project_namesprintZadd_project	ExceptionZDatasetInfoZfrom_dataframerangelencolumnsnameFEEDBACKZDataTypeCATEGORYZ	data_typeFEEDBACK_POSSIBLE_VALUESZpossible_values
LLM_STATUSSUCCESSFAILUREZget_model_namesZget_dataset_namesZupload_datasetZ	ModelInfoZfrom_dataset_infoZ	ModelTaskZLLMPROMPTCONTEXTRESPONSERUN_IDTOTAL_TOKENSPROMPT_TOKENSCOMPLETION_TOKENS
MODEL_NAMEDURATIONr*   Z	add_model)
selfr   r   r    r!   r"   er'   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 EmbeddingZ	embedding)r:   
enrichmentr9   z	Prompt CF)r:   Zsource_columncolumnzResponse EmbeddingzResponse CFzText StatisticsZtextstat
statistics)Zautomated_readability_indexZcoleman_liau_indexZdale_chall_readability_scoreZdifficult_wordsZflesch_reading_easeZflesch_kincaid_gradeZgunning_fogZlinsear_write_formula)r:   rO   r9   configZPIIZpiiZ	SentimentZ	sentiment)r.   Z
EnrichmentrA   ZTextEmbeddingrC   )rJ   r   r   r   r*      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)Zorient)eventz$Error publishing events to fiddler: z. continuing...N)r8   r2   r/   r0   rA   rC   rD   strrI   r>   rH   items
isinstanceintshaper4   Zpublish_events_batchr    r!   to_dictZpublish_eventr6   r5   )rJ   r   rT   r   r   r   rU   Zprompt_countdfkeyvalueZdf_dictrK   r   r   r   _publish_events   s4   




z&FiddlerCallbackHandler._publish_events
serializedpromptskwargsc                 K   s,   |t  }|| j|< tt d | j|< d S )N  )rD   r2   r[   timer3   )rJ   rb   rc   rd   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 )Nre   rS   c                 S   s$   i | ]\}}|t ttfv r||qS r   )rE   rF   rG   ).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   )Zgenerationstext)rh   Z	llmresultr   r   r   
<listcomp><  s    z5FiddlerCallbackHandler.on_llm_end.<locals>.<listcomp>)flattenrD   r[   rf   r3   rZ   Z
llm_outputdictrY   getrH   ra   r?   )	rJ   r   rd   Zflattened_llmresultr   Zrun_durationr   rU   rT   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 )Nre   rS   )rD   r[   rf   r3   ra   r8   r2   r@   )rJ   rr   rd   r   r   r   r   r   on_llm_errorI  s
   z#FiddlerCallbackHandler.on_llm_error)rS   N)__name__
__module____qualname__rX   r-   propertylistr*   r   r   r[   r   r   r   ra   rg   r   rq   BaseExceptionrs   __classcell__r   r   rM   r   r   >   sX    wK
*

r   )'rf   typingr   r   r   r   uuidr   Zlangchain_core.callbacksr   Zlangchain_core.outputsr   Zlangchain_core.utilsr
   Z#langchain_community.callbacks.utilsr   ZTOKEN_USAGErE   rF   rG   rD   rH   ZGOODBADZNEUTRALr?   r@   ZDEFAULT_MAX_TOKENZDEFAULT_MAX_DURATIONrA   rC   rB   rI   r;   r>   r=   r1   r   r   r   r   r   r   <module>   sR    







