Source code for langchain_community.callbacks.uptrain_callback
"""UpTrain Callback HandlerUpTrain is an open-source platform to evaluate and improve LLM applications. It providesgrades for 20+ preconfigured checks (covering language, code, embedding use cases),performs root cause analyses on instances of failure cases and provides guidance forresolving them.This module contains a callback handler for integrating UpTrain seamlessly into yourpipeline and facilitating diverse evaluations. The callback handler automates variousevaluations to assess the performance and effectiveness of the components within thepipeline.The evaluations conducted include:1. RAG: - Context Relevance: Determines the relevance of the context extracted from the query to the response. - Factual Accuracy: Assesses if the Language Model (LLM) is providing accurate information or hallucinating. - Response Completeness: Checks if the response contains all the information requested by the query.2. Multi Query Generation: MultiQueryRetriever generates multiple variants of a question with similar meanings to the original question. This evaluation includes previous assessments and adds: - Multi Query Accuracy: Ensures that the multi-queries generated convey the same meaning as the original query.3. Context Compression and Reranking: Re-ranking involves reordering nodes based on relevance to the query and selecting top n nodes. Due to the potential reduction in the number of nodes after re-ranking, the following evaluations are performed in addition to the RAG evaluations: - Context Reranking: Determines if the order of re-ranked nodes is more relevant to the query than the original order. - Context Conciseness: Examines whether the reduced number of nodes still provides all the required information.These evaluations collectively ensure the robustness and effectiveness of the RAG queryengine, MultiQueryRetriever, and the re-ranking process within the pipeline.Useful links:Github: https://github.com/uptrain-ai/uptrainWebsite: https://uptrain.ai/Docs: https://docs.uptrain.ai/getting-started/introduction"""importloggingimportsysfromcollectionsimportdefaultdictfromtypingimport(Any,DefaultDict,Dict,List,Optional,Sequence,Set,)fromuuidimportUUIDfromlangchain_core.callbacks.baseimportBaseCallbackHandlerfromlangchain_core.documentsimportDocumentfromlangchain_core.outputsimportLLMResultfromlangchain_core.utilsimportguard_importlogger=logging.getLogger(__name__)handler=logging.StreamHandler(sys.stdout)formatter=logging.Formatter("%(message)s")handler.setFormatter(formatter)logger.addHandler(handler)
[docs]defimport_uptrain()->Any:"""Import the `uptrain` package."""returnguard_import("uptrain")
[docs]classUpTrainDataSchema:"""The UpTrain data schema for tracking evaluation results. Args: project_name (str): The project name to be shown in UpTrain dashboard. Attributes: project_name (str): The project name to be shown in UpTrain dashboard. uptrain_results (DefaultDict[str, Any]): Dictionary to store evaluation results. eval_types (Set[str]): Set to store the types of evaluations. query (str): Query for the RAG evaluation. context (str): Context for the RAG evaluation. response (str): Response for the RAG evaluation. old_context (List[str]): Old context nodes for Context Conciseness evaluation. new_context (List[str]): New context nodes for Context Conciseness evaluation. context_conciseness_run_id (str): Run ID for Context Conciseness evaluation. multi_queries (List[str]): List of multi queries for Multi Query evaluation. multi_query_run_id (str): Run ID for Multi Query evaluation. multi_query_daugher_run_id (str): Run ID for Multi Query daughter evaluation. """
[docs]def__init__(self,project_name:str)->None:"""Initialize the UpTrain data schema."""# For tracking project name and resultsself.project_name:str=project_nameself.uptrain_results:DefaultDict[str,Any]=defaultdict(list)# For tracking event typesself.eval_types:Set[str]=set()## RAGself.query:str=""self.context:str=""self.response:str=""## CONTEXT CONCISENESSself.old_context:List[str]=[]self.new_context:List[str]=[]self.context_conciseness_run_id:UUID=UUID(int=0)# MULTI QUERYself.multi_queries:List[str]=[]self.multi_query_run_id:UUID=UUID(int=0)self.multi_query_daugher_run_id:UUID=UUID(int=0)
[docs]classUpTrainCallbackHandler(BaseCallbackHandler):"""Callback Handler that logs evaluation results to uptrain and the console. Args: project_name (str): The project name to be shown in UpTrain dashboard. key_type (str): Type of key to use. Must be 'uptrain' or 'openai'. api_key (str): API key for the UpTrain or OpenAI API. (This key is required to perform evaluations using GPT.) Raises: ValueError: If the key type is invalid. ImportError: If the `uptrain` package is not installed. """
[docs]def__init__(self,*,project_name:str="langchain",key_type:str="openai",api_key:str="sk-****************",# The API key to use for evaluationmodel:str="gpt-3.5-turbo",# The model to use for evaluationlog_results:bool=True,)->None:"""Initializes the `UpTrainCallbackHandler`."""super().__init__()uptrain=import_uptrain()self.log_results=log_results# Set uptrain variablesself.schema=UpTrainDataSchema(project_name=project_name)self.first_score_printed_flag=Falseifkey_type=="uptrain":settings=uptrain.Settings(uptrain_access_token=api_key,model=model)self.uptrain_client=uptrain.APIClient(settings=settings)elifkey_type=="openai":settings=uptrain.Settings(openai_api_key=api_key,evaluate_locally=True,model=model)self.uptrain_client=uptrain.EvalLLM(settings=settings)else:raiseValueError("Invalid key type: Must be 'uptrain' or 'openai'")
[docs]defuptrain_evaluate(self,evaluation_name:str,data:List[Dict[str,Any]],checks:List[str],)->None:"""Run an evaluation on the UpTrain server using UpTrain client."""ifself.uptrain_client.__class__.__name__=="APIClient":uptrain_result=self.uptrain_client.log_and_evaluate(project_name=self.schema.project_name,evaluation_name=evaluation_name,data=data,checks=checks,)else:uptrain_result=self.uptrain_client.evaluate(project_name=self.schema.project_name,evaluation_name=evaluation_name,data=data,checks=checks,)self.schema.uptrain_results[self.schema.project_name].append(uptrain_result)score_name_map={"score_context_relevance":"Context Relevance Score","score_factual_accuracy":"Factual Accuracy Score","score_response_completeness":"Response Completeness Score","score_sub_query_completeness":"Sub Query Completeness Score","score_context_reranking":"Context Reranking Score","score_context_conciseness":"Context Conciseness Score","score_multi_query_accuracy":"Multi Query Accuracy Score",}ifself.log_results:# Set logger level to INFO to print the evaluation resultslogger.setLevel(logging.INFO)forrowinuptrain_result:columns=list(row.keys())forcolumnincolumns:ifcolumn=="question":logger.info(f"\nQuestion: {row[column]}")self.first_score_printed_flag=Falseelifcolumn=="response":logger.info(f"Response: {row[column]}")self.first_score_printed_flag=Falseelifcolumn=="variants":logger.info("Multi Queries:")forvariantinrow[column]:logger.info(f" - {variant}")self.first_score_printed_flag=Falseelifcolumn.startswith("score"):ifnotself.first_score_printed_flag:logger.info("")self.first_score_printed_flag=Trueifcolumninscore_name_map:logger.info(f"{score_name_map[column]}: {row[column]}")else:logger.info(f"{column}: {row[column]}")ifself.log_results:# Set logger level back to WARNING# (We are doing this to avoid printing the logs from HTTP requests)logger.setLevel(logging.WARNING)
[docs]defon_llm_end(self,response:LLMResult,*,run_id:UUID,parent_run_id:Optional[UUID]=None,**kwargs:Any,)->None:"""Log records to uptrain when an LLM ends."""uptrain=import_uptrain()self.schema.response=response.generations[0][0].textif("qa_rag"inself.schema.eval_typesandparent_run_id!=self.schema.multi_query_daugher_run_id):data=[{"question":self.schema.query,"context":self.schema.context,"response":self.schema.response,}]self.uptrain_evaluate(evaluation_name="rag",data=data,checks=[uptrain.Evals.CONTEXT_RELEVANCE,uptrain.Evals.FACTUAL_ACCURACY,uptrain.Evals.RESPONSE_COMPLETENESS,],)
[docs]defon_chain_start(self,serialized:Dict[str,Any],inputs:Dict[str,Any],*,run_id:UUID,tags:Optional[List[str]]=None,parent_run_id:Optional[UUID]=None,metadata:Optional[Dict[str,Any]]=None,run_type:Optional[str]=None,name:Optional[str]=None,**kwargs:Any,)->None:"""Do nothing when chain starts"""ifparent_run_id==self.schema.multi_query_run_id:self.schema.multi_query_daugher_run_id=run_idifisinstance(inputs,dict)andset(inputs.keys())=={"context","question"}:self.schema.eval_types.add("qa_rag")context=""ifisinstance(inputs["context"],Document):context=inputs["context"].page_contentelifisinstance(inputs["context"],list):fordocininputs["context"]:context+=doc.page_content+"\n"elifisinstance(inputs["context"],str):context=inputs["context"]self.schema.context=contextself.schema.query=inputs["question"]pass