
    Ng                        d dl mZ d dlZd dlmZmZmZ d dlmZ d dl	m
Z
mZ erd dlmZ  ej        e          Z	 	 	 dddZ G d de          ZdS )    )annotationsN)TYPE_CHECKINGAnyOptional)BaseCallbackHandler)get_from_envguard_import)LoggerF	sentimentbooltoxicitythemesreturnr   c                    t          d          }t          d           t          d           | rt          d           |rt          d           |rt          d           |S )a  Import the langkit python package and raise an error if it is not installed.

    Args:
        sentiment: Whether to import the langkit.sentiment module. Defaults to False.
        toxicity: Whether to import the langkit.toxicity module. Defaults to False.
        themes: Whether to import the langkit.themes module. Defaults to False.

    Returns:
        The imported langkit module.
    langkitzlangkit.regexeszlangkit.textstatzlangkit.sentimentzlangkit.toxicityzlangkit.themes)r	   )r   r   r   r   s       j/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/callbacks/whylabs_callback.pyimport_langkitr      sy     9%%G"####$$$ *())) )'((( '%&&&N    c            	      n     e Zd ZdZd fdZdd	Zdd
ZddZd dZe	ddddddddd!d            Z
 xZS )"WhyLabsCallbackHandlera  
    Callback Handler for logging to WhyLabs. This callback handler utilizes
    `langkit` to extract features from the prompts & responses when interacting with
    an LLM. These features can be used to guardrail, evaluate, and observe interactions
    over time to detect issues relating to hallucinations, prompt engineering,
    or output validation. LangKit is an LLM monitoring toolkit developed by WhyLabs.

    Here are some examples of what can be monitored with LangKit:
    * Text Quality
      - readability score
      - complexity and grade scores
    * Text Relevance
      - Similarity scores between prompt/responses
      - Similarity scores against user-defined themes
      - Topic classification
    * Security and Privacy
      - patterns - count of strings matching a user-defined regex pattern group
      - jailbreaks - similarity scores with respect to known jailbreak attempts
      - prompt injection - similarity scores with respect to known prompt attacks
      - refusals - similarity scores with respect to known LLM refusal responses
    * Sentiment and Toxicity
      - sentiment analysis
      - toxicity analysis

    For more information, see https://docs.whylabs.ai/docs/language-model-monitoring
    or check out the LangKit repo here: https://github.com/whylabs/langkit

    ---
    Args:
        api_key (Optional[str]): WhyLabs API key. Optional because the preferred
            way to specify the API key is with environment variable
            WHYLABS_API_KEY.
        org_id (Optional[str]): WhyLabs organization id to write profiles to.
            Optional because the preferred way to specify the organization id is
            with environment variable WHYLABS_DEFAULT_ORG_ID.
        dataset_id (Optional[str]): WhyLabs dataset id to write profiles to.
            Optional because the preferred way to specify the dataset id is
            with environment variable WHYLABS_DEFAULT_DATASET_ID.
        sentiment (bool): Whether to enable sentiment analysis. Defaults to False.
        toxicity (bool): Whether to enable toxicity analysis. Defaults to False.
        themes (bool): Whether to enable theme analysis. Defaults to False.
    loggerr
   handlerr   c                N   t                                                       t          |d          r|                    |            t          |d          r|                                | _        n-t                      | _        t                              d           || _	        dS )zInitiate the rolling logger.init_get_callbacksz&initialized handler without callbacks.N)
super__init__hasattrr   r   
_callbacksdictdiagnostic_loggerwarning_logger)selfr   r   	__class__s      r   r   zWhyLabsCallbackHandler.__init__V   s    7F## 	LL7,-- 	P%4466DOO"ffDO%%&NOOOr   r   Nonec                    | j         rJt          | j         d          r7| j                                          t                              d           dS dS dS )z;Explicitly write current profile if using a rolling logger._do_rolloverz+Flushing WhyLabs logger, writing profile...N)r#   r   r(   r!   infor$   s    r   flushzWhyLabsCallbackHandler.flushb   sh    < 	RGDL.AA 	RL%%'''""#PQQQQQ	R 	R 	R 	Rr   c                    | j         rJt          | j         d          r7| j                                          t                              d           dS dS dS )zFClose any loggers to allow writing out of any profiles before exiting.closez*Closing WhyLabs logger, see you next time!N)r#   r   r-   r!   r)   r*   s    r   r-   zWhyLabsCallbackHandler.closeh   sh    < 	QGDL':: 	QL   ""#OPPPPP	Q 	Q 	Q 	Qr   c                    | S N r*   s    r   	__enter__z WhyLabsCallbackHandler.__enter__n   s    r   exception_typeexception_value	tracebackc                .    |                                   d S r/   )r-   )r$   r2   r3   r4   s       r   __exit__zWhyLabsCallbackHandler.__exit__q   s     	

r   NF)api_keyorg_id
dataset_idr   r   r   r   r7   Optional[str]r8   r9   r   r   r   r   Optional[Logger]c               B   t          |||           t          d          }t          d          j        }	t          d          j        }
t          d          j        }|||pt          dd          }|pt          d	d
          }|pt          dd          } |
|||          }|                    ddd |                      }|                    |           nt          	                    d           |} |	||           }t          	                    d           |S )an  Instantiate whylogs Logger from params.

        Args:
            api_key (Optional[str]): WhyLabs API key. Optional because the preferred
                way to specify the API key is with environment variable
                WHYLABS_API_KEY.
            org_id (Optional[str]): WhyLabs organization id to write profiles to.
                If not set must be specified in environment variable
                WHYLABS_DEFAULT_ORG_ID.
            dataset_id (Optional[str]): The model or dataset this callback is gathering
                telemetry for. If not set must be specified in environment variable
                WHYLABS_DEFAULT_DATASET_ID.
            sentiment (bool): If True will initialize a model to perform
                sentiment analysis compound score. Defaults to False and will not gather
                this metric.
            toxicity (bool): If True will initialize a model to score
                toxicity. Defaults to False and will not gather this metric.
            themes (bool): If True will initialize a model to calculate
                distance to configured themes. Defaults to None and will not gather this
                metric.
            logger (Optional[Logger]): If specified will bind the configured logger as
                the telemetry gathering agent. Defaults to LangKit schema with periodic
                WhyLabs writer.
        )r   r   r   whylogszlangkit.callback_handlerzwhylogs.api.writer.whylabsz$whylogs.experimental.core.udf_schemaNr7   WHYLABS_API_KEYr8   WHYLABS_DEFAULT_ORG_IDr9   WHYLABS_DEFAULT_DATASET_ID)r7   r8   r9   rolling   M)modeintervalwhenschema)writerz'Using passed in whylogs logger {logger})r   impluG   Started whylogs Logger with WhyLabsWriter and initialized LangKit. 📝)
r   r	   get_callback_instanceWhyLabsWriter
udf_schemar   r   append_writerr!   r)   )clsr7   r8   r9   r   r   r   r   whyrJ   rK   rL   whylabs_writerwhylabs_loggercallback_handler_clss                  r   from_paramsz"WhyLabsCallbackHandler.from_paramsv   sf   J 	XfMMMM9%% ,&!
 !

 	 %%ABBP!"HIIT
>Ki9J!K!KGO|H6NOOF# |:( (J +]:  N !ZZZZ\\ (  N (((????""#LMMM#N44NQTUUUU	
 	
 	
 $#r   )r   r
   r   r   )r   r&   )r   r   )r2   r   r3   r   r4   r   r   r&   )r7   r:   r8   r:   r9   r:   r   r   r   r   r   r   r   r;   r   r   )__name__
__module____qualname____doc__r   r+   r-   r1   r6   classmethodrS   __classcell__)r%   s   @r   r   r   *   s        ) )V
 
 
 
 
 
R R R RQ Q Q Q      
  "& $$(#'D$ D$ D$ D$ D$ [D$ D$ D$ D$ D$r   r   )FFF)r   r   r   r   r   r   r   r   )
__future__r   loggingtypingr   r   r   langchain_core.callbacksr   langchain_core.utilsr   r	   whylogs.api.logger.loggerr
   	getLoggerrT   r!   r   r   r0   r   r   <module>ra      s    " " " " " "  / / / / / / / / / / 8 8 8 8 8 8 ; ; ; ; ; ; ; ; 1000000%G%h//      6Q$ Q$ Q$ Q$ Q$0 Q$ Q$ Q$ Q$ Q$r   