o
    /if,                     @  s`  d dl mZ d dlZd dlmZmZ d dlZd dl	m
Z
mZ d dlmZ d dlmZ d dlmZmZ d dlmZ d d	l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"m#Z# d dl$m%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/m0Z0 d dl1m2Z2m3Z3m4Z4m5Z5 ej6rd dl7m8Z8 									d.d/d+d,Z9eG d-d* d*e:Z;dS )0    )annotationsN)	dataclassfield)Datasetconcatenate_datasets)
Embeddings)BaseLanguageModel)EvaluationEventtrack)	new_group)BaseRagasEmbeddingsLangchainEmbeddingsWrapperembedding_factory)ExceptionInRunner)Executor)llm_factory)BaseRagasLLMLangchainLLMWrapper)AnswerCorrectness)MetricMetricWithEmbeddingsMetricWithLLMis_reproducable)AspectCritique)	RunConfigget_feature_language)handle_deprecated_ground_truthsremap_column_namesvalidate_column_dtypesvalidate_evaluation_modes)	CallbacksFTdatasetr   metricslist[Metric] | Nonellm't.Optional[BaseRagasLLM | LangchainLLM]
embeddings5t.Optional[BaseRagasEmbeddings | LangchainEmbeddings]	callbacksr!   in_ciboolis_async
run_configt.Optional[RunConfig]raise_exceptions
column_mapt.Optional[t.Dict[str, str]]returnResultc
           "        sP  |	pi }	|pg }| du rt d|pt }|du r+ddlm}
m}m}m} |
|||g}t| |	} t| } t	| | t
|  t|trHt||d}t|trQt|}g }g }g }g }d}t|D ]e\}t|trn||j t|tr|jdu r|du rt }||_| t|tr|jdu r|du rt }||_| t|tr|jdu r}|rt|r|jdkrd|_| || q_td	d
||d g }t di |d\}}t| D ]1\t!"t!j#t$t!j%f t d |d\}||f  fdd|D  qg }zzE & }|g krt' t| D ]2\}i }t|D ]\}}|t(| |  ||j< q-|| | \}j)sT|*| q#W n t+yo } z|j)si|,| |d}~ww t-t./|| |d}|j)s|*| W |D ]dt!"t| _q|D ]dt!"t| _q|dkrdt!"t|| _|D ]d| _qn8|D ]dt!"t| _q|D ]dt!"t| _q|dkrdt!"t|| _|D ]d| _qw dd |D } dd |D }!t01dd |!D }!t2t3d| d| j4d t(|!dkr |!d nd|d |S )aJ  
    Run the evaluation on the dataset with different metrics

    Parameters
    ----------
    dataset : Dataset[question: list[str], contexts: list[list[str]], answer: list[str], ground_truth: list[list[str]]]
        The dataset in the format of ragas which the metrics will use to score the RAG
        pipeline with
    metrics : list[Metric] , optional
        List of metrics to use for evaluation. If not provided then ragas will run the
        evaluation on the best set of metrics to give a complete view.
    llm: BaseRagasLLM, optional
        The language model to use for the metrics. If not provided then ragas will use
        the default language model for metrics which require an LLM. This can we overridden by the llm specified in
        the metric level with `metric.llm`.
    embeddings: BaseRagasEmbeddings, optional
        The embeddings to use for the metrics. If not provided then ragas will use
        the default embeddings for metrics which require embeddings. This can we overridden by the embeddings specified in
        the metric level with `metric.embeddings`.
    callbacks: Callbacks, optional
        Lifecycle Langchain Callbacks to run during evaluation. Check the
        [langchain documentation](https://python.langchain.com/docs/modules/callbacks/)
        for more information.
    in_ci: bool
        Whether the evaluation is running in CI or not. If set to True then some
        metrics will be run to increase the reproducability of the evaluations. This
        will increase the runtime and cost of evaluations. Default is False.
    is_async: bool
        Whether to run the evaluation in async mode or not. If set to True then the
        evaluation is run by calling the `metric.ascore` method. In case the llm or
        embeddings does not support async then the evaluation can be run in sync mode
        with `is_async=False`. Default is False.
    run_config: RunConfig, optional
        Configuration for runtime settings like timeout and retries. If not provided,
        default values are used.
    raise_exceptions: True
        Whether to raise exceptions or not. If set to True then the evaluation will
        raise an exception if any of the metrics fail. If set to False then the
        evaluation will return `np.nan` for the row that failed. Default is True.
    column_map : dict[str, str], optional
        The column names of the dataset to use for evaluation. If the column names of
        the dataset are different from the default ones then you can provide the
        mapping as a dictionary here. Example: If the dataset column name is contexts_v1,
        column_map can be given as {"contexts":"contexts_v1"}

    Returns
    -------
    Result
        Result object containing the scores of each metric. You can use this do analysis
        later.

    Raises
    ------
    ValueError
        if validation fails because the columns required for the metrics are missing or
        if the columns are of the wrong format.

    Examples
    --------
    the basic usage is as follows:
    ```
    from ragas import evaluate

    >>> dataset
    Dataset({
        features: ['question', 'ground_truth', 'answer', 'contexts'],
        num_rows: 30
    })

    >>> result = evaluate(dataset)
    >>> print(result)
    {'context_precision': 0.817,
    'faithfulness': 0.892,
    'answer_relevancy': 0.874}
    ```
    NzProvide dataset!r   )answer_relevancycontext_precisioncontext_recallfaithfulness)r-         
EvaluatingT)desckeep_progress_barr/   r-   zragas evaluation)nameinputsr)   r,   zrow c              
     s.   g | ]} j |j|j d  dqS )-r>   )submitascorer>   ).0metricexecutorir,   rowrow_group_cm I/var/www/html/corbot_env/lib/python3.10/site-packages/ragas/evaluation.py
<listcomp>   s    zevaluate.<locals>.<listcomp>)scoresr"   binary_columnsc                 S  s   g | ]}|j qS rK   rA   rD   mrK   rK   rL   rM     s    c                 S  s   g | ]}t |qS rK   r   rP   rK   rK   rL   rM     s    c                 S  s   g | ]}|d ur|qS )NrK   rP   rK   rK   rL   rM     s    
evaluation )
event_typer#   evaluation_modenum_rowslanguager*   )5
ValueErrorr   ragas.metricsr4   r5   r6   r7   r   r   r    r   
isinstanceLangchainLLMr   LangchainEmbeddingsr   	enumerater   appendr>   r   r%   r   r   r'   r   r   answer_similarityr   reproducibilityinitr   r   tcastDictstrAnyresultsr   lenendedon_chain_end	Exceptionon_chain_errorr3   r   	from_listnpuniquer
   r	   shape)"r"   r#   r%   r'   r)   r*   r,   r-   r/   r0   r4   r5   r6   r7   binary_metricsllm_changedembeddings_changedreproducable_metricsanswer_correctness_is_setrE   row_run_managersevaluation_rmevaluation_group_cmrow_rmrN   rg   _sjrQ   eresultmetrics_namesmetric_langrK   rF   rL   evaluate-   s
  X





















r   c                   @  sR   e Zd ZU ded< dZded< eedZded< d	d
 ZddddZ	dddZ
dS )r3   r   rN   Nzt.Optional[Dataset]r"   )default_factoryzt.List[str]rO   c                 C  sX   g }| j d  D ] }t| j | }|| |< || jvr)tt|}||d  q	d S )Nr   g|=)	rN   keysrn   nanmeanrO   rb   rc   floatr^   )selfvaluescnvaluerK   rK   rL   __post_init__(  s   
zResult.__post_init__F
batch_size
int | Nonebatchedr+   c                 C  sP   | j d u r	td| jjd | j jd ksJ t| j | jgdd}|j||dS )Nz-dataset is not provided for the results classr   r9   )axis)r   r   )r"   rX   rN   rp   r   	to_pandas)r   r   r   	result_dsrK   rK   rL   r   1  s
   
zResult.to_pandasr2   re   c                 C  s,   |   }dd | D }dd| d S )Nc                 S  s"   g | ]\}}d | d|dqS )'z': z0.4frK   )rD   kvrK   rK   rL   rM   ;  s   " z#Result.__repr__.<locals>.<listcomp>{z, })copyitemsjoin)r   rN   
score_strsrK   rK   rL   __repr__9  s   zResult.__repr__)NF)r   r   r   r+   )r2   re   )__name__
__module____qualname____annotations__r"   r   listrO   r   r   r   rK   rK   rK   rL   r3   "  s   
 	)	NNNNFTNTN)r"   r   r#   r$   r%   r&   r'   r(   r)   r!   r*   r+   r,   r+   r-   r.   r/   r+   r0   r1   r2   r3   )<
__future__r   typingrb   dataclassesr   r   numpyrn   datasetsr   r   langchain_core.embeddingsr   r\   langchain_core.language_modelsr   r[   ragas._analyticsr	   r
   ragas.callbacksr   ragas.embeddings.baser   r   r   ragas.exceptionsr   ragas.executorr   
ragas.llmsr   ragas.llms.baser   r   !ragas.metrics._answer_correctnessr   ragas.metrics.baser   r   r   r   ragas.metrics.critiquer   ragas.run_configr   ragas.utilsr   ragas.validationr   r   r   r    TYPE_CHECKINGlangchain_core.callbacksr!   r   dictr3   rK   rK   rK   rL   <module>   sF     v