🎯 Tunable Ensemble for LLM Uncertainty (Advanced)#
Ensemble UQ methods combine multiple individual scorers to provide a more robust uncertainty estimate. They offer high flexibility and customizability, allowing you to tailor the ensemble to specific use cases. This ensemble can leverage any combination of black-box, white-box, or LLM-as-a-Judge scorers offered by uqlm. Below is a list of the available scorers:
Black-Box (Consistency) Scorers#
Non-Contradiction Probability (Chen & Mueller, 2023; Lin et al., 2025; Manakul et al., 2023)
Semantic Negentropy (based on Farquhar et al., 2024; Kuhn et al., 2023)
Exact Match (Cole et al., 2023; Chen & Mueller, 2023)
BERT-score (Manakul et al., 2023; Zheng et al., 2020)
BLUERT (Sellam et al., 2020)
Normalized Cosine Similarity (Shorinwa et al., 2024; HuggingFace)
White-Box (Token-Probability-Based) Scorers#
Minimum token probability (Manakul et al., 2023)
Length-Normalized Joint Token Probability (Malinin & Gales, 2021)
LLM-as-a-Judge Scorers#
Categorical LLM-as-a-Judge (Manakul et al., 2023; Chen & Mueller, 2023; Luo et al., 2023)
Continuous LLM-as-a-Judge (Xiong et al., 2024)
📊 What You’ll Do in This Demo#
1
Set up LLM and prompts.
Set up LLM instance and load example data prompts.
2
Tune Ensemble Weights
Tune the ensemble weights on a set of tuning prompts. You will execute a single UQEnsemble.tune() method that will generate responses, compute confidence scores, and optimize weights using a provided answer key corresponding to the provided questions.
3
Generate LLM Responses and Confidence Scores with Tuned Ensemble.
Generate and score LLM responses to the example questions using the tuned UQEnsemble() object.
4
Evaluate Hallucination Detection Performance.
Visualize LLM accuracy at different thresholds of the ensemble score that combines various scorers. Compute precision, recall, and F1-score of hallucination detection.
⚖️ Advantages & Limitations#
Pros
Highly Flexible: Versatile and adaptable to various tasks and question types.
Highly Customizable: Ensemble weights can be tuned for optimal performance on a specific use case.
Cons
Requires More Setup: Not quite “off-the-shelf”; requires some effort to configure and tune the ensemble.
Best for Advanced Users: Optimizing the ensemble requires a deeper understanding of the individual scorers.
[2]:
import numpy as np
from sklearn.metrics import precision_score, recall_score, f1_score
from uqlm import UQEnsemble
from uqlm.utils import load_example_dataset, math_postprocessor, plot_model_accuracies
## 1. Set up LLM and Prompts
In this demo, we will illustrate this approach using a set of math questions from the GSM8K benchmark. To implement with your use case, simply replace the example prompts with your data.
[3]:
# Load example dataset (GSM8K)
gsm8k = load_example_dataset("gsm8k", n=100)
gsm8k.head()
Loading dataset - gsm8k...
Processing dataset...
Dataset ready!
[3]:
question | answer | |
---|---|---|
0 | Natalia sold clips to 48 of her friends in Apr... | 72 |
1 | Weng earns $12 an hour for babysitting. Yester... | 10 |
2 | Betty is saving money for a new wallet which c... | 5 |
3 | Julie is reading a 120-page book. Yesterday, s... | 42 |
4 | James writes a 3-page letter to 2 different fr... | 624 |
[4]:
gsm8k_tune = gsm8k.iloc[0:50]
gsm8k_test = gsm8k.iloc[51:100]
[5]:
# Define prompts
MATH_INSTRUCTION = (
"When you solve this math problem only return the answer with no additional text.\n"
)
tune_prompts = [MATH_INSTRUCTION + prompt for prompt in gsm8k_tune.question]
test_prompts = [MATH_INSTRUCTION + prompt for prompt in gsm8k_test.question]
In this example, we use ChatVertexAI
and AzureChatOpenAI
to instantiate our LLMs, but any LangChain Chat Model may be used. Be sure to replace with your LLM of choice.
[6]:
# import sys
# !{sys.executable} -m pip install python-dotenv
# !{sys.executable} -m pip install langchain-openai
# # User to populate .env file with API credentials. In this step, replace with your LLM of choice.
from dotenv import load_dotenv, find_dotenv
from langchain_openai import AzureChatOpenAI
load_dotenv(find_dotenv())
gpt = AzureChatOpenAI(
deployment_name=os.getenv("DEPLOYMENT_NAME"),
openai_api_key=os.getenv("API_KEY"),
azure_endpoint=os.getenv("API_BASE"),
openai_api_type=os.getenv("API_TYPE"),
openai_api_version=os.getenv("API_VERSION"),
temperature=1, # User to set temperature
)
[7]:
# import sys
# !{sys.executable} -m pip install langchain-google-vertexai
from langchain_google_vertexai import ChatVertexAI
gemini = ChatVertexAI(model="gemini-pro")
## 2. Tune Ensemble
UQEnsemble()
- Ensemble of uncertainty scorers#
📋 Class Attributes#
Parameter | Type & Default | Description |
---|---|---|
llm | BaseChatModeldefault=None | A langchain llm |
scorers | Listdefault=None | Specifies which black-box, white-box, or LLM-as-a-Judge scorers to include in the ensemble. List containing instances of BaseChatModel, LLMJudge, black-box scorer names from [‘semantic_negentropy’, ‘noncontradiction’,’exact_match’, ‘bert_score’, ‘bleurt’, ‘cosine_sim’], or white-box scorer names from [“normalized_probability”, “min_probability”]. If None, defaults to the off-the-shelf BS Detector ensemble by Chen & Mueller, 2023 which uses components [“noncontradiction”, “exact_match”,”self_reflection”] with respective weights of [0.56, 0.14, 0.3]. |
device | str or torch.devicedefault=”cpu” | Specifies the device that NLI model use for prediction. Only applies to ‘semantic_negentropy’, ‘noncontradiction’ scorers. Pass a torch.device to leverage GPU. |
use_best | booldefault=True | Specifies whether to swap the original response for the uncertainty-minimized response among all sampled responses based on semantic entropy clusters. Only used if |
system_prompt | str or Nonedefault=”You are a helpful assistant.” | Optional argument for user to provide custom system prompt for the LLM. |
max_calls_per_min | intdefault=None | Specifies how many API calls to make per minute to avoid rate limit errors. By default, no limit is specified. |
use_n_param | booldefault=False | Specifies whether to use n parameter for BaseChatModel. Not compatible with all BaseChatModel classes. If used, it speeds up the generation process substantially when num_responses is large. |
postprocessor | callabledefault=None | A user-defined function that takes a string input and returns a string. Used for postprocessing outputs. |
sampling_temperature | floatdefault=1 | The ‘temperature’ parameter for LLM model to generate sampled LLM responses. Must be greater than 0. |
weights | list of floatsdefault=None | Specifies weight for each component in ensemble. If None, and scorers is not None, and defaults to equal weights for each scorer. These weights get updated with tune method is executed. |
nli_model_name | strdefault=”microsoft/deberta-large-mnli” | Specifies which NLI model to use. Must be acceptable input to AutoTokenizer.from_pretrained() and AutoModelForSequenceClassification.from_pretrained(). |
🔍 Parameter Groups#
🧠 LLM-Specific
llm
system_prompt
sampling_temperature
📊 Confidence Scores
scorers
weights
use_best
nli_model_name
postprocessor
🖥️ Hardware
device
⚡ Performance
max_calls_per_min
use_n_param
💻 Usage Examples#
# Basic usage with default parameters
uqe = UQEnsemble(llm=llm)
# Using GPU acceleration
uqe = UQEnsemble(llm=llm, device=torch.device("cuda"))
# Custom scorer list
uqe = BlackBoxUQ(llm=llm, scorers=["bert_score", "exact_match", llm])
# High-throughput configuration with rate limiting
uqe = UQEnsemble(llm=llm, max_calls_per_min=200, use_n_param=True)
[8]:
import torch
# Set the torch device
if torch.cuda.is_available(): # NVIDIA GPU
device = torch.device("cuda")
elif torch.backends.mps.is_available(): # macOS
device = torch.device("mps")
else:
device = torch.device("cpu") # CPU
print(f"Using {device.type} device")
Using cuda device
[9]:
scorers = [
"exact_match", # Measures proportion of candidate responses that match original response (black-box)
"noncontradiction", # mean non-contradiction probability between candidate responses and original response (black-box)
"normalized_probability", # length-normalized joint token probability (white-box)
gpt, # LLM-as-a-judge (self)
gemini, # LLM-as-a-judge (separate LLM)
]
uqe = UQEnsemble(
llm=gpt,
device=device,
max_calls_per_min=175,
# postprocessor=math_postprocessor,
use_n_param=True, # Set True if using AzureChatOpenAI for faster generation
scorers=scorers,
)
Some weights of the model checkpoint at microsoft/deberta-large-mnli were not used when initializing DebertaForSequenceClassification: ['config']
- This IS expected if you are initializing DebertaForSequenceClassification from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).
- This IS NOT expected if you are initializing DebertaForSequenceClassification from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).
Method | Description & Parameters |
---|---|
UQEnsemble.tune | Generate responses from provided prompts, grade responses with provided grader function, and tune ensemble weights. If weights and threshold objectives match, joint optimization will happen. Otherwise, sequential optimization will happen. If an optimization problem has fewer than three choice variables, grid search will happen. Parameters:
Returns: UQResult containing data (prompts, responses, sampled responses, and confidence scores) and metadata 💡 Best For: Tuning an optimized ensemble for detecting hallucinations in a specific use case. |
Note that below, we are providing a grader function that is specific to our use case (math questions). If you are running this example notebook with your own prompts/questions, update the grader function accordingly. Note that the default grader function, vectara/hallucination_evaluation_model
, is used if no grader function is provided and generally works well across use cases.
[10]:
def grade_response(response: str, answer: str) -> bool:
return (math_postprocessor(response) == answer)
[11]:
tune_results = await uqe.tune(
prompts=tune_prompts, # prompts for tuning (responses will be generated from these prompts)
ground_truth_answers=gsm8k_tune["answer"], # correct answers to 'grade' LLM responses against
grader_function=grade_response, # grader function to grade responses against provided answers
)
Generating responses...
Generating candidate responses...
Computing confidence scores...
Generating LLMJudge scores...
Generating LLMJudge scores...
Grading responses with grader function...
Optimizing weights...
Optimizing threshold with grid search...
[12]:
result_df = tune_results.to_df()
result_df.head()
[12]:
prompt | response | sampled_responses | ensemble_score | exact_match | noncontradiction | normalized_probability | judge_1 | judge_2 | |
---|---|---|---|---|---|---|---|---|---|
0 | When you solve this math problem only return t... | 72 | [72, 72, 72, 72, 72] | 0.952566 | 1.0 | 1.000000 | 0.999188 | 1.0 | 0.5 |
1 | When you solve this math problem only return t... | $10 | [$10, $10, $10, $10, $10] | 0.895037 | 1.0 | 1.000000 | 0.999019 | 0.0 | 0.5 |
2 | When you solve this math problem only return t... | $20 | [$20, $20, $20, $20, $10] | 0.762877 | 0.8 | 0.801301 | 0.946584 | 1.0 | 0.0 |
3 | When you solve this math problem only return t... | 48 | [48, 48, 48, 48, 48] | 0.941798 | 1.0 | 1.000000 | 0.996091 | 0.0 | 1.0 |
4 | When you solve this math problem only return t... | 624 | [624, 624, 624, 624, 624] | 0.999969 | 1.0 | 1.000000 | 0.999828 | 1.0 | 1.0 |
[13]:
for i, weight in enumerate(uqe.weights):
print(f"Weight for {uqe.component_names[i]}: {weight}")
Weight for exact_match: 0.14848838407926002
Weight for noncontradiction: 0.5195905565435162
Weight for normalized_probability: 0.17984565170407496
Weight for judge_1: 0.05749867602904491
Weight for judge_2: 0.09457673164410399
## 3. Generate LLM Responses and Confidence Scores
To evaluate hallucination detection performance, we will generate responses and corresponding confidence scores on a holdout set using the tuned ensemble.
Method | Description & Parameters |
---|---|
UQEnsemble.generate_and_score | Generate LLM responses, sampled LLM (candidate) responses, and compute confidence scores for the provided prompts. Parameters:
Returns: UQResult containing data (prompts, responses, sampled responses, and confidence scores) and metadata 💡 Best For: Complete end-to-end uncertainty quantification when starting with prompts. |
UQEnsemble.score | Compute confidence scores on provided LLM responses. Should only be used if responses and sampled responses are already generated. Parameters:
Returns: UQResult containing data (responses, sampled responses, and confidence scores) and metadata 💡 Best For: Computing uncertainty scores when responses are already generated elsewhere. |
[15]:
test_results = await uqe.generate_and_score(prompts=test_prompts, num_responses=5)
Generating responses...
Generating candidate responses...
Computing confidence scores...
Generating LLMJudge scores...
Generating LLMJudge scores...
## 4. Evaluate Hallucination Detection Performance
To evaluate hallucination detection performance, we ‘grade’ the responses against an answer key. Again, note that the grade_response
function is specific to our use case (math questions). If you are using your own prompts/questions, update the grading method accordingly.
[16]:
test_result_df = test_results.to_df()
test_result_df["response_correct"] = [
grade_response(r, a) for r, a in zip(test_result_df["response"], gsm8k_test["answer"])
]
test_result_df.head(5)
[16]:
prompt | response | sampled_responses | ensemble_score | exact_match | noncontradiction | normalized_probability | judge_1 | judge_2 | response_correct | |
---|---|---|---|---|---|---|---|---|---|---|
0 | When you solve this math problem only return t... | 160 | [68, 176, 152, 80, 72] | 0.030060 | 0.0 | 0.021150 | 0.106042 | 0.0 | 0.0 | True |
1 | When you solve this math problem only return t... | 12 | [12, 14, 18, 11, 13] | 0.158690 | 0.2 | 0.240650 | 0.021982 | 0.0 | 0.0 | False |
2 | When you solve this math problem only return t... | $36 | [$36, $36, $36, $36, 36] | 0.870801 | 0.8 | 0.994231 | 0.989287 | 1.0 | 0.0 | True |
3 | When you solve this math problem only return t... | 9 | [$3, $9, 3, $10, 9] | 0.359167 | 0.2 | 0.452459 | 0.205047 | 1.0 | 0.0 | False |
4 | When you solve this math problem only return t... | 75% | [75%, 75., 75%, 75%, 75%] | 0.873314 | 0.8 | 0.998718 | 0.990297 | 1.0 | 0.0 | True |
[17]:
print(f"""Baseline LLM accuracy: {np.mean(test_result_df["response_correct"])}""")
Baseline LLM accuracy: 0.5714285714285714
4.1 Filtered LLM Accuracy Evaluation#
Here, we explore ‘filtered accuracy’ as a metric for evaluating the performance of our confidence scores. Filtered accuracy measures the change in LLM performance when responses with confidence scores below a specified threshold are excluded. By adjusting the confidence score threshold, we can observe how the accuracy of the LLM improves as less certain responses are filtered out.
We will plot the filtered accuracy across various confidence score thresholds to visualize the relationship between confidence and LLM accuracy. This analysis helps in understanding the trade-off between response coverage (measured by sample size below) and LLM accuracy, providing insights into the reliability of the LLM’s outputs.
[18]:
plot_model_accuracies(
scores=test_result_df.ensemble_score,
correct_indicators=test_result_df.response_correct,
)

4.2 Precision, Recall, F1-Score of Hallucination Detection#
Lastly, we compute the optimal threshold for binarizing confidence scores, using F1-score as the objective. Using this threshold, we compute precision, recall, and F1-score for black box scorer predictions of whether responses are correct.
[19]:
# extract optimal threshold
best_threshold = uqe.thresh
# Define score vector and corresponding correct indicators (i.e. ground truth)
y_scores = test_result_df["ensemble_score"] # confidence score
correct_indicators = (
test_result_df.response_correct
) * 1 # Whether responses is actually correct
y_pred = [
(s > best_threshold) * 1 for s in y_scores
] # predicts whether response is correct based on confidence score
print(f"Ensemble F1-optimal threshold: {best_threshold}")
Ensemble F1-optimal threshold: 0.36
[20]:
# evaluate precision, recall, and f1-score of semantic entropy predictions of correctness
print(
f"Ensemble precision: {precision_score(y_true=correct_indicators, y_pred=y_pred)}"
)
print(f"Ensemble recall: {recall_score(y_true=correct_indicators, y_pred=y_pred)}")
print(f"Ensemble f1-score: {f1_score(y_true=correct_indicators, y_pred=y_pred)}")
Ensemble precision: 0.6585365853658537
Ensemble recall: 0.9642857142857143
Ensemble f1-score: 0.782608695652174
5. Scorer Definitions#
Black-Box Scorers#
Black-Box UQ scorers exploit variation in LLM responses to the same prompt to measure semantic consistency. All scorers have outputs ranging from 0 to 1, with higher values indicating higher confidence.
For a given prompt \(x_i\), these approaches involves generating \(m\) responses \(\tilde{\mathbf{y}}_i = \{ \tilde{y}_{i1},...,\tilde{y}_{im}\}\), using a non-zero temperature, from the same prompt and comparing these responses to the original response \(y_{i}\). We provide detailed descriptions of each below.
Exact Match Rate (exact_match
)#
Exact Match Rate (EMR) computes the proportion of candidate responses that are identical to the original response.
For more on this scorer, refer to Cole et al., 2023.
Non-Contradiction Probability (noncontradiction
)#
Non-contradiction probability (NCP) computes the mean non-contradiction probability estimated by a natural language inference (NLI) model. This score is formally defined as follows:
- :nbsphinx-math:`begin{equation}
NCP(y_i; tilde{mathbf{y}}_i) = frac{1}{m} sum_{j=1}^m(1 - p_j)
end{equation}` where
- :nbsphinx-math:`begin{equation}
p_j = frac{eta(y_{i}, tilde{y}_{ij}) + eta(tilde{y}_{ij},y_i)}{2}.
end{equation}`
Above, \(\eta(\tilde{y}_{ij},y_i)\) denotes the contradiction probability estimated by the NLI model for response \(y_i\) and candidate \(\tilde{y}_{ij}\). For more on this scorer, refer to Chen & Mueller, 2023, Lin et al., 2025, or Manakul et al., 2023.
Normalized Semantic Negentropy (semantic_negentropy
)#
Normalized Semantic Negentropy (NSN) normalizes the standard computation of discrete semantic entropy to be increasing with higher confidence and have [0,1] support. In contrast to the EMR and NCP, semantic entropy does not distinguish between an original response and candidate responses. Instead, this approach computes a single metric value on a list of responses generated from the same prompt. Under this approach, responses are clustered using an NLI model based on mutual entailment. We consider the discrete version of SE, where the final set of clusters is defined as follows:
- :nbsphinx-math:`begin{equation}
SE(y_i; tilde{mathbf{y}}_i) = - sum_{C in mathcal{C}} P(C|y_i, tilde{mathbf{y}}_i)log P(C|y_i, tilde{mathbf{y}}_i),
end{equation}` where \(P(C|y_i, \tilde{\mathbf{y}}_i)\) denotes the probability a randomly selected response $y \in `{y_i} :nbsphinx-math:cup :nbsphinx-math:tilde{mathbf{y}}`_i $ belongs to cluster \(C\), and \(\mathcal{C}\) denotes the full set of clusters of \(\{y_i\} \cup \tilde{\mathbf{y}}_i\).
- To ensure that we have a normalized confidence score with \([0,1]\) support and with higher values corresponding to higher confidence, we implement the following normalization to arrive at Normalized Semantic Negentropy (NSN): :nbsphinx-math:`begin{equation}
NSN(y_i; tilde{mathbf{y}}_i) = 1 - frac{SE(y_i; tilde{mathbf{y}}_i)}{log m},
end{equation}` where \(\log m\) is included to normalize the support.
BERTScore (bert_score
)#
Let a tokenized text sequence be denoted as \(\textbf{t} = \{t_1,...t_L\}\) and the corresponding contextualized word embeddings as \(\textbf{E} = \{\textbf{e}_1,...,\textbf{e}_L\}\), where \(L\) is the number of tokens in the text. The BERTScore precision, recall, and F1-scores between two tokenized texts \(\textbf{t}, \textbf{t}'\) are respectively defined as follows:
- :nbsphinx-math:`begin{equation}
BertP(textbf{t}, textbf{t}’) = frac{1}{| textbf{t}|} sum_{t in textbf{t}} max_{t’ in textbf{t}’} textbf{e} cdot textbf{e}’
end{equation}`
- :nbsphinx-math:`begin{equation}
BertR(textbf{t}, textbf{t}’) = frac{1}{| textbf{t}’|} sum_{t’ in textbf{t}’} max_{t in textbf{t}} textbf{e} cdot textbf{e}’
end{equation}`
- :nbsphinx-math:`begin{equation}
BertF(textbf{t}, textbf{t}’) = 2frac{ BertP(textbf{t}, textbf{t}’) BertR(textbf{t}, textbf{t}’)}{BertPr(textbf{t}, textbf{t}’) + BertRec(textbf{t}, textbf{t}’)},
- end{equation}` where \(e, e'\) respectively correspond to \(t, t'\). We compute our BERTScore-based confidence scores as follows: :nbsphinx-math:`begin{equation}
BertConfidence(y_i; tilde{mathbf{y}}_i) = frac{1}{m} sum_{j=1}^m BertF(y_i, tilde{y}_{ij}),
end{equation}` i.e. the average BERTScore F1 across pairings of the original response with all candidate responses. For more on BERTScore, refer to Zheng et al., 2020.
BLEURT (bleurt
)#
In contrast to the aforementioned scorers, BLEURT is specifically pre-trained and fine-tuned to learn human judgments of text similarity. Our BLEURT confidence score is the average BLEURT value across pairings of the original response with all candidate responses:
- :nbsphinx-math:`begin{equation}
BLEURTConfidence(y_i; tilde{mathbf{y}}_i) = frac{1}{m} sum_{j=1}^m BLEURT(y_i, tilde{y}_{ij}).
end{equation}`
For more on this scorer, refer to Sellam et al., 2020.
Normalized Cosine Similarity (cosine_sim
)#
This scorer leverages a sentence transformer to map LLM outputs to an embedding space and measure similarity using those sentence embeddings. Let \(V: \mathcal{Y} \xrightarrow{} \mathbb{R}^d\) denote the sentence transformer, where \(d\) is the dimension of the embedding space. The average cosine similarity across pairings of the original response with all candidate responses is given as follows:
- :nbsphinx-math:`begin{equation}
CS(y_i; tilde{mathbf{y}}_i) = frac{1}{m} sum_{i=1}^m frac{mathbf{V}(y_i) cdot mathbf{V}(tilde{y}_{ij}) }{ lVert mathbf{V}(y_i) rVert lVert mathbf{V}(tilde{y}_{ij}) rVert}.
end{equation}`
To ensure a standardized support of \([0, 1]\), we normalize cosine similarity to obtain confidence scores as follows:
- :nbsphinx-math:`begin{equation}
NCS(y_i; tilde{mathbf{y}}_i) = frac{CS(y_i; tilde{mathbf{y}}_i) + 1}{2}.
end{equation}`
White-box UQ scorers leverage token probabilities of the LLM’s generated response to quantify uncertainty. All scorers have outputs ranging from 0 to 1, with higher values indicating higher confidence. We define two white-box UQ scorers below.
Length-Normalized Token Probability (normalized_probability
)#
Let the tokenization LLM response \(y_i\) be denoted as \(\{t_1,...,t_{L_i}\}\), where \(L_i\) denotes the number of tokens the response. Length-normalized token probability (LNTP) computes a length-normalized analog of joint token probability:
- :nbsphinx-math:`begin{equation}
LNTP(y_i) = prod_{t in y_i} p_t^{frac{1}{L_i}},
end{equation}` where \(p_t\) denotes the token probability for token \(t\). Note that this score is equivalent to the geometric mean of token probabilities for response \(y_i\). For more on this scorer, refer to Malinin & Gales, 2021.
Minimum Token Probability (min_probability
)#
Minimum token probability (MTP) uses the minimum among token probabilities for a given responses as a confidence score:
- :nbsphinx-math:`begin{equation}
MTP(y_i) = min_{t in y_i} p_t,
end{equation}` where \(t\) and \(p_t\) follow the same definitions as above. For more on this scorer, refer to Manakul et al., 2023.
Under the LLM-as-a-Judge approach, either the same LLM that was used for generating the original responses or a different LLM is asked to form a judgment about a pre-generated response. Below, we define two LLM-as-a-Judge scorer templates. #### Categorical Judge Template (true_false_uncertain
) We follow the approach proposed by Chen & Mueller, 2023 in which an LLM is instructed to score a question-answer concatenation as either incorrect, uncertain,
or correct using a carefully constructed prompt. These categories are respectively mapped to numerical scores of 0, 0.5, and 1. We denote the LLM-as-a-judge scorers as \(J: \mathcal{Y} \xrightarrow[]{} \{0, 0.5, 1\}\). Formally, we can write this scorer function as follows:
:nbsphinx-math:`begin{equation} J(y_i) = begin{cases}
0 & text{LLM states response is incorrect} \ 0.5 & text{LLM states that it is uncertain} \ 1 & text{LLM states response is correct}.
end{cases} end{equation}`
Continuous Judge Template (continuous
)#
For the continuous template, the LLM is asked to directly score a question-answer concatenation’s correctness on a scale of 0 to 1.
© 2025 CVS Health and/or one of its affiliates. All rights reserved.