Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
A common strategy for evaluating unstructured text application is to use other LLMs and text embedding models to drive metrics of interest.
The LLM-as-judge text metrics in dbnl.eval
support OpenAI, Azure OpenAI and any other third-party LLM / embedding model provider that is compatible with the OpenAI python client. Specifically, third-party endpoints should (mostly) adhere to the schema of:
v1/chat/completions endpoint for LLMs
v1/embeddings endpoint for embedding models
The following examples show how to initialize an llm_eval_client
and an eval_embedding_client
under different providers.
It is possible for some of the LLM-as-judge metrics to occasionally return values that are unable to be parsed. These metrics values will surface as None
Distributional is able to accept dataframes including None
values. The platform will intelligently filter them when applicable.
LLM service providers often impose request rate limits and token throughput caps. Some example errors that one might encounter are shown below:
In the event you experience these errors, please work with your LLM service provider to adjust your limits. Additionally, feel free to reach out to Distributional support with the issue you are seeing.
Many generative AI applications focus on text generation. It can be challenging to create metrics for insights into expected performance when dealing with unstructured text.
dbnl.eval
is a special module designed for evaluating unstructured text. This module currently includes:
Adaptive metric sets for generic text and RAG applications
12+ simple statistical local library powered text metrics
15+ LLM-as-judge and embedding powered text metrics
Support for user-defined custom LLM-as-judge metrics
LLM-as-judge metrics compatible with OpenAI, Azure OpenAI
Building dbnl tests on these evaluation metrics can then drive rich insights into an AI application's stability and performance.
In RAG (retrieval-augmented generation or "question and answer") applications, the high level goal is:
Given a question, generate an answer that adheres to knowledge in some corpus
However, this is easier said than done. Data is often collected at various steps in the RAG process to help evaluate which steps might be performing poorly or not as expected. This data can help understand the following:
What question was asked?
Which documents / chunks (ids) were retrieved?
What was the text of those retrieved documents / chunks?
From the retrieved documents, what was the top-ranked document and its id?
What is the expected answer?
What is the expected document id and text that contains the answer to the question?
What was the generated answer?
Having data that answers some or all of these questions allows for evaluations to run, producing metrics that can highlight what part of the RAG system is performing in unexpected ways.
The short example below demonstrates what a dataframe with rich contextual data would look like for and how to use dbnl.eval
to generate relevant metrics
You can inspect a subset of the the aug_eval_df
rows and examine, for example, the metrics related to retrieval and answer similarity
We can see the first result (idx
= 0) represents a complete failure of the RAG system. The relevant documents were not retrieved (mrr
= 0.0) and the generated answer is very dissimilar from the expected answer (answer_similarity
= 1).
The second result (idx
= 1) represents a better response from the RAG system. The relevant document was retrieved, but ranked lower (mrr
= 0.33333) and the answer is somewhat similar to the expected answer (answer_similarity
= 3)
The final result (idx
= 2) represents a strong response from the RAG system. The relevant document was retrieved and top ranked (mrr
= 1.0) and the generated answer is very similar to the expected answer (answer_similarity
= 5)
The signature for question_and_answer_metrics()
highlights its adaptability. Again, the optional arguments are not required and the helper will intelligently return only the metrics that depend on the info that is provided.
0
0.0
1
1
0.33333
3
2
1.0
5
No problem, just don’t include an eval_llm_client
or an eval_embedding_client
argument in the call(s) to the evaluation helpers. The helpers will automatically exclude any metrics that depend on them.
No problem. You can simply remove the target argument from the helper. The metric set helper will automatically exclude any metrics that depend on the target column being specified.
There is an additional helper that can generate a list of generic metrics appropriate for “monitoring” unstructured text columns : text_monitor_metrics()
. Simply provide a list of text column names and optionally an eval_llm_client
for LLM-as-judge metrics.
You can write your own LLM-as-judge metric that uses your custom prompt. The example below defines a custom LLM-as-judge metric and runs it on an example dataframe.
You can also write a metric that includes only the prediction column specified and reference only {prediction}
in the custom prompt. An example is below:
The metric set helpers return an adaptive list of metrics, relevant to the application type
text_metrics()
Basic metrics for generic text comparison and monitoring
question_and_answer_metrics()
Basic metrics for RAG / question answering
The metric set helpers are adaptive in that :
The metrics returned encode which columns of the dataframe are input to the metric computation
e.g., rougeL_prediction__ground_truth
is the rougeL
metric run with both the column named prediction
and the column named ground_truth
as input
The metrics returned support any additional optional column info and LLM-as-judge or embedding model clients. If any of this optional info is not provided, the metric set will exclude any metrics that depend on that information
See the How-To section for concrete examples of adaptive text_metrics()
usage
See the RAG example for question_and_answer_metrics()
usage
eval.metrics
To use dbnl.eval
, you will need to install the extra 'eval' package as described in these instructions.
Create a client to power LLM-as-judge text metrics [optional]
Generate a list of metrics suitable for comparing text_A to reference text_B
Use dbnl.eval
to evaluate to compute the list metrics.
Publish the augmented dataframe and new metric quantities to DBNL
You can inspect a subset of the the aug_eval_df
rows and for example, one of the columns created by one of the metrics in the text_metrics
list : llm_text_similarity_v0
0
France has no capital
The capital of France is Paris
1
1
The capital of France is Toronto
The capital of France is Paris
1
2
Paris is the capital
The capital of France is Paris
5
The values of llm_text_similarity_v0
qualitatively match our expectations on semantic similarity between the prediction and ground_truth
The call to evaluate()
takes a dataframe and metric list as input and returns a dataframe with extra columns. Each new column holds the value of a metric computation for that row
The column names of the metrics in the returned dataframe include the metric name and the columns that were used in that metrics computation
For example the metric named llm_text_similarity_v0
becomes llm_text_similarity_v0__prediction__ground_truth
because it takes as input both the column named prediction
and the column named ground_truth
Functions in the dbnl.eval module.
Evaluates a set of metrics on a dataframe, returning an augmented dataframe.
Parameters:
df – input dataframe
metrics – metrics to compute
inplace – whether to modify the input dataframe in place
Returns: input dataframe augmented with metrics
Get the run config column schemas for a dataframe that was augmented with a list of metrics.
Parameters:
df – Dataframe to get column schemas from
metrics – list of metrics added to the dataframe
Returns: list of columns schemas for dataframe and metrics
Get the run config column schemas from a list of metrics.
Parameters: metrics – list of metrics to get column schemas from
Returns: list of column schemas for metrics
Classes and methods in dbnl.eval.metrics.
Returns the column schema for the metric to be used in a run config.
Returns: _description_
Return type: ColumnSchema
Returns the description of the metric.
Returns: Description of the metric.
Evaluates the metric over the provided dataframe.
Parameters: df – Input data from which to compute metric.
Returns: Metric values.
Returns the expression representing the metric (e.g. rouge1(prediction, target)
).
Returns: Metric expression.
If true, larger values are assumed to be directionally better than smaller once. If false, smaller values are assumged to be directionally better than larger one. If None, assumes nothing.
Returns: True if greater is better, False if smaller is better, otherwise None.
Returns: Metric name (e.g. rouge1
).
Returns the fully qualified name of the metric (e.g. rouge1__prediction__target
).
Returns: Metric name.
Returns the type of the metric (e.g. float)
Returns: Metric type.
Computes the accuracy of the answer by evaluating the accuracy score of the answer using a language model.
This metric is generated by an LLM using a specific prompt named llm_accuracy
available in dbnl.eval.metrics.prompts
.
Parameters:
input – input column name
context – context column name
prediction – prediction column name
eval_llm_client – eval_llm_client
Returns: accuracy metric
Returns the answer correctness metric.
This metric is generated by an LLM using a specific prompt named llm_answer_correctness
available in dbnl.eval.metrics.prompts
.
Parameters:
input – input column name
prediction – prediction column name
target – target column name
eval_llm_client – eval LLM client
Returns: answer correctness metric
Returns answer similarity metric.
This metric is generated by an LLM using a specific prompt named llm_answer_similarity
available in dbnl.eval.metrics.prompts
.
Parameters:
input – input column name
prediction – prediction column name
target – target column name
eval_llm_client – eval_llm_client
Returns: answer similarity metric
Computes the coherence of the answer by evaluating the coherence score of the answer using a language model.
This metric is generated by an LLM using a specific prompt named llm_coherence
available in dbnl.eval.metrics.prompts
.
Parameters:
prediction – prediction column name
eval_llm_client – eval_llm_client
Returns: coherence metric
Computes the commital of the answer by evaluating the commital score of the answer using a language model.
This metric is generated by an LLM using a specific prompt named llm_commital
available in dbnl.eval.metrics.prompts
.
Parameters:
prediction – prediction column name
eval_llm_client – eval_llm_client
Returns: commital metric
Computes the completeness of the answer by evaluating the completeness score of the answer using a language model.
This metric is generated by an LLM using a specific prompt named llm_completeness
available in dbnl.eval.metrics.prompts
.
Parameters:
input – input column name
prediction – prediction column
eval_llm_client – eval_llm_client
Returns: completeness metric
Computes the contextual relevance of the answer by evaluating the contextual relevance score of the answer using a language model.
This metric is generated by an LLM using a specific prompt named llm_contextual_relevance
available in dbnl.eval.metrics.prompts
.
Parameters:
input – input column name
context – context column name
eval_llm_client – eval_llm_client
Returns: contextual relevance metric
Returns the faithfulness metric.
This metric is generated by an LLM using a specific prompt named llm_faithfulness
available in dbnl.eval.metrics.prompts
.
Parameters:
input – input column name
context – context column name
prediction – prediction column name
eval_llm_client – eval_llm_client
Returns: faithfulness metric
Computes the grammar accuracy of the answer by evaluating the grammar accuracy score of the answer using a language model.
This metric is generated by an LLM using a specific prompt named llm_grammar_accuracy
available in dbnl.eval.metrics.prompts
.
Parameters:
prediction – prediction column name
eval_llm_client – eval_llm_client
Returns: grammar accuracy metric
Returns a set of metrics which evaluate the quality of the generated answer. This does not include metrics that require a ground truth.
Parameters:
input – input column name (i.e. question)
prediction – prediction column name (i.e. generated answer)
context – context column name (i.e. document or set of documents retrieved)
eval_llm_client – eval_llm_client
Returns: list of metrics
Computes the originality of the answer by evaluating the originality score of the answer using a language model.
This metric is generated by an LLM using a specific prompt named llm_originality
available in dbnl.eval.metrics.prompts
.
Parameters:
prediction – prediction column name
eval_llm_client – eval_llm_client
Returns: originality metric
Returns relevance metric with context.
This metric is generated by an LLM using a specific prompt named llm_relevance
available in dbnl.eval.metrics.prompts
.
Parameters:
input – input column name
context – context column name
prediction – prediction column name
eval_llm_client – eval_llm_client
Returns: answer relevance metric with context
Returns a list of metrics relevant for a question and answer task.
Parameters:
prediction – prediction column name (i.e. generated answer)
eval_llm_client – eval_llm_client
Returns: list of metrics
Computes the reading complexity of the answer by evaluating the reading complexity score of the answer using a language model.
This metric is generated by an LLM using a specific prompt named llm_reading_complexity
available in dbnl.eval.metrics.prompts
.
Parameters:
prediction – prediction column name
eval_llm_client – eval_llm_client
Returns: reading complexity metric
Computes the sentiment of the answer by evaluating the sentiment assessment score of the answer using a language model.
This metric is generated by an LLM using a specific prompt named llm_sentiment_assessment
available in dbnl.eval.metrics.prompts
.
Parameters:
prediction – prediction column name
eval_llm_client – eval_llm_client
Returns: sentiment assessment metric
Computes the text fluency of the answer by evaluating the perplexity of the answer using a language model.
This metric is generated by an LLM using a specific prompt named llm_text_fluency
available in dbnl.eval.metrics.prompts
.
Parameters:
prediction – prediction column name
eval_llm_client – eval_llm_client
Returns: text fluency metric
Computes the toxicity of the answer by evaluating the toxicity score of the answer using a language model.
This metric is generated by an LLM using a specific prompt named llm_text_toxicity
available in dbnl.eval.metrics.prompts
.
Parameters:
prediction – prediction column name
eval_llm_client – eval_llm_client
Returns: toxicity metric
Returns the Automated Readability Index metric for the text_col_name
column.
Calculates the Automated Readability Index (ARI) for a given text. ARI is a readability metric that estimates the U.S. school grade level necessary to understand the text, based on the number of characters per word and words per sentence.
Parameters: text_col_name – text column name
Returns: automated_readability_index metric:
Returns the bleu metric between the prediction and target columns.
The BLEU score is a metric for evaluating a generated sentence to a reference sentence. The BLEU score is a number between 0 and 1, where 1 means that the generated sentence is identical to the reference sentence.
Parameters:
prediction – prediction column name
target – target column name
Returns: bleu metric
Returns the character count metric for the text_col_name
column.
Parameters: text_col_name – text column name
Returns: character_count metric
Returns the context hit metric.
This boolean-valued metric is used to evaluate whether the ground truth document is present in the list of retrieved documents. The context hit metric is 1 if the ground truth document is present in the list of retrieved documents, and 0 otherwise.
Parameters:
ground_truth_document_id – ground_truth_document_id column name
retrieved_document_ids – retrieved_document_ids column name
Returns: context hit metric
Returns a set of metrics relevant for a question and answer task.
Parameters: text_col_name – text column name
Returns: list of metrics
Returns the Flesch-Kincaid Grade metric for the text_col_name
column.
Calculates the Flesch-Kincaid Grade Level for a given text. The Flesch-Kincaid Grade Level is a readability metric that estimates the U.S. school grade level required to understand the text. It is based on the average number of syllables per word and words per sentence.
Parameters: text_col_name – text column name
Returns: flesch_kincaid_grade metric
Returns a set of metrics relevant for a question and answer task.
Parameters:
prediction – prediction column name (i.e. generated answer)
target – target column name (i.e. expected answer)
Returns: list of metrics
Returns a set of metrics relevant for a question and answer task.
Parameters:
ground_truth_document_id – ground_truth_document_id column name
retrieved_document_ids – retrieved_document_ids column name
Returns: list of metrics
Returns the inner product metric between the ground_truth_document_text
and top_retrieved_document_text
columns.
This metric is used to evaluate the similarity between the ground truth document and the top retrieved document using the inner product of their embeddings. The embedding client is used to retrieve the embeddings for the ground truth document and the top retrieved document. An embedding is a high-dimensional vector representation of a string of text.
Parameters:
ground_truth_document_text – ground_truth_document_text column name
top_retrieved_document_text – top_retrieved_document_text column name
embedding_client – embedding client
Returns: inner product metric
Returns the inner product metric between the prediction and target columns.
This metric is used to evaluate the similarity between the prediction and target columns using the inner product of their embeddings. The embedding client is used to retrieve the embeddings for the prediction and target columns. An embedding is a high-dimensional vector representation of a string of text.
Parameters:
prediction – prediction column name
target – target column name
embedding_client – embedding client
Returns: inner product metric
Returns the levenshtein metric between the prediction and target columns.
The Levenshtein distance is a metric for evaluating the similarity between two strings. The Levenshtein distance is an integer value, where 0 means that the two strings are identical, and a higher value returns the number of edits required to transform one string into the other.
Parameters:
prediction – prediction column name
target – target column name
Returns: levenshtein metric
Returns the mean reciprocal rank (MRR) metric.
This metric is used to evaluate the quality of a ranked list of documents. The MRR score is a number between 0 and 1, where 1 means that the ground truth document is ranked first in the list. The MRR score is calculated by taking the reciprocal of the rank of the first relevant document in the list.
Parameters:
ground_truth_document_id – ground_truth_document_id column name
retrieved_document_ids – retrieved_document_ids column name
Returns: mrr metric
Returns a set of metrics relevant for a question and answer task.
Parameters: prediction – prediction column name (i.e. generated answer)
Returns: list of metrics
Returns a set of metrics relevant for a question and answer task.
Parameters:
prediction – prediction column name (i.e. generated answer)
target – target column name (i.e. expected answer)
input – input column name (i.e. question)
context – context column name (i.e. document or set of documents retrieved)
ground_truth_document_id – ground_truth_document_id containing the information in the target
retrieved_document_ids – retrieved_document_ids containing the full context
ground_truth_document_text – text containing the information in the target (ideal is for this to be the top retrieved document)
top_retrieved_document_text – text of the top retrieved document
eval_llm_client – eval_llm_client
eval_embedding_client – eval_embedding_client
Returns: list of metrics
Returns a set of all metrics relevant for a question and answer task.
Parameters:
prediction – prediction column name (i.e. generated answer)
target – target column name (i.e. expected answer)
input – input column name (i.e. question)
context – context column name (i.e. document or set of documents retrieved)
ground_truth_document_id – ground_truth_document_id containing the information in the target
retrieved_document_ids – retrieved_document_ids containing the full context
ground_truth_document_text – text containing the information in the target (ideal is for this to be the top retrieved document)
top_retrieved_document_text – text of the top retrieved document
eval_llm_client – eval_llm_client
eval_embedding_client – eval_embedding_client
Returns: list of metrics
Returns a set metrics relevant for generic text applications
Parameters:
prediction – prediction column name (i.e. generated answer)
target – target column name (i.e. expected answer)
eval_llm_client – eval_llm_client
eval_embedding_client – eval_embedding_client
Returns: list of metrics
Returns the rouge1 metric between the prediction and target columns.
ROUGE-1 is a recall-oriented metric that calculates the overlap of unigrams (individual words) between the predicted/generated summary and the reference summary. It measures how many single words from the reference summary appear in the predicted summary. ROUGE-1 focuses on basic word-level similarity and is used to evaluate the content coverage.
Parameters:
prediction – prediction column name
target – target column name
Returns: rouge1 metric
Returns the rouge2 metric between the prediction and target columns.
ROUGE-2 is a recall-oriented metric that calculates the overlap of bigrams (pairs of words) between the predicted/generated summary and the reference summary. It measures how many pairs of words from the reference summary appear in the predicted summary. ROUGE-2 focuses on word-level similarity and is used to evaluate the content coverage.
Parameters:
prediction – prediction column name
target – target column name
Returns: rouge2 metric
Returns the rougeL metric between the prediction and target columns.
ROUGE-L is a recall-oriented metric based on the Longest Common Subsequence (LCS) between the reference and generated summaries. It measures how well the generated summary captures the longest sequences of words that appear in the same order in the reference summary. This metric accounts for sentence-level structure and coherence.
Parameters:
prediction – prediction column name
target – target column name
Returns: rougeL metric
Returns the rougeLsum metric between the prediction and target columns.
ROUGE-LSum is a variant of ROUGE-L that applies the Longest Common Subsequence (LCS) at the sentence level for summarization tasks. It evaluates how well the generated summary captures the overall sentence structure and important elements of the reference summary by computing the LCS for each sentence in the document.
Parameters:
prediction – prediction column name
target – target column name
Returns: rougeLsum metric
Returns all rouge metrics between the prediction and target columns.
Parameters:
prediction – prediction column name
target – target column name
Returns: list of rouge metrics
Returns the sentence count metric for the text_col_name column.
Parameters: text_col_name – text column name
Returns: sentence_count metric
Returns a set of metrics relevant for a summarization task.
Parameters:
prediction – prediction column name (i.e. generated summary)
target – target column name (i.e. expected summary)
Returns: list of metrics
Returns the token count metric for the text_col_name column.
A token is a sequence of characters that represents a single unit of meaning, such as a word or punctuation mark. The token count metric calculates the total number of tokens in the text. Different languages may have different tokenization rules. This function is implemented using the nltk library.
Parameters: text_col_name – text column name
Returns: token_count metric
Returns the word count metric for the text_col_name
column.
Parameters: text_col_name – text column name
Returns: word_count metric
Computes the similarity of the prediction and target text by evaluating using a language model.
This metric is generated by an LLM using a specific specific prompt named llm_accuracy available in dbnl.eval.metrics.prompts.
Parameters:
prediction – prediction column name
target - target (expected value) column name
eval_llm_client – Eval LLM client
Returns: text similarity metric