LLM evaluators utilize LLMs as judges to assess the success of your experiment. These evaluators can either use a prebuilt LLM evaluation template or be customized to suit your specific needs.
Arize supports a large number of LLM evaluators out of the box with LLM Classify:
Here's an example of a LLM evaluator that checks for hallucinations in the model output:
from phoenix.evals import llm_classify
from phoenix.experiments.types import EvaluationResult
from openai import OpenAIModel
HALLUCINATION_PROMPT_TEMPLATE = """
In this task, you will be presented with a query, a reference text and an answer. The answer is
generated to the question based on the reference text. The answer may contain false information. You
must use the reference text to determine if the answer to the question contains false information,
if the answer is a hallucination of facts. Your objective is to determine whether the answer text
contains factual information and is not a hallucination. A 'hallucination' refers to
an answer that is not based on the reference text or assumes information that is not available in
the reference text.
Your response should be a single word: either "factual" or "hallucinated", and
it should not include any other text or characters. "hallucinated" indicates that the answer
provides factually inaccurate information to the query based on the reference text. "factual"
indicates that the answer to the question is correct relative to the reference text, and does not
contain made up information. Please read the query and reference text carefully before determining
your response.
# Query: {query}
# Reference text: {reference}
# Answer: {response}
Is the answer above factual or hallucinated based on the query and reference text?
"""
def hallucination_eval(output, dataset_row):
# Get the original query and reference text from the dataset_row
query = dataset_row.get("query")
reference = dataset_row.get("reference")
# Create a DataFrame to pass into llm_classify
df_in = pd.DataFrame(
{"query": query, "reference": reference, "response": output}, index=[0]
)
# Run the LLM classification
eval_df = llm_classify(
dataframe=df_in,
template=HALLUCINATION_PROMPT_TEMPLATE,
model=OpenAIModel(model="gpt-4o-mini", api_key=OPENAI_API_KEY),
rails=["factual", "hallucinated"],
provide_explanation=True,
)
# Map the eval df to EvaluationResult
label = eval_df["label"][0]
score = 1 if label == "factual" else 0
explanation = eval_df["explanation"][0]
# Return the evaluation result
return EvaluationResult(label=label, score=score, explanation=explanation)
In this example, the HallucinationEvaluator class evaluates whether the output of an experiment contains hallucinations by comparing it to the expected output using an LLM. The llm_classify function runs the eval, and the evaluator returns an EvaluationResult that includes a score, label, and explanation.
Once you define your evaluator class, you can use it in your experiment run like this:
You can customize LLM evaluators to suit your experiment's needs — update the template with your instructions and the rails with the desired output.
Create a code evaluator
Code Evaluators
Code evaluators are functions designed to assess the outputs of your experiments. They allow you to define specific criteria for success, which can be as simple or complex as your application requires. Code evaluators are especially useful when you need to apply tailored logic or rules to validate the output of your model.
Custom Code Evaluators
Creating a custom code evaluator is as simple as writing a Python function. By default, this function will take the output of an experiment run as its single argument. Your custom evaluator can return either a boolean or a numeric value, which will then be recorded as the evaluation score.
For example, let’s say our experiment is testing a task that should output a numeric value between 1 and 100. We can create a simple evaluator function to check if the output falls within this range:
def in_bounds(output):
return 1 <= output <= 100
By passing the in_bounds function to run_experiment, evaluations will automatically be generated for each experiment run, indicating whether the output is within the allowed range. This allows you to quickly assess the validity of your experiment’s outputs based on custom criteria.
Alternatively, you can leverage one of our prebuilt evaluators using phoenix.experiments.evaluators
This evaluator checks whether the output of an experiment run is a JSON-parsable string. It's useful when you want to ensure that the generated output can be correctly formatted and parsed as JSON, which is critical for applications that rely on structured data formats.
from phoenix.experiments import JSONParsable
# This defines a code evaluator that checks if the output is JSON-parsable
json_parsable_evaluator = JSONParsable()
This evaluator checks whether the output matches a specified regex pattern. It’s ideal for validating outputs that need to conform to a specific format, such as phone numbers, email addresses, or other structured data that can be described with a regular expression.
from phoenix.experiments import MatchesRegex
# This defines a code evaluator that checks if the output contains
# a valid phone number format
phone_number_evaluator = MatchesRegex(
pattern=r"\d{3}-\d{3}-\d{4}",
name="valid-phone-number"
)
This evaluator checks if a specific keyword is present in the output of an experiment run. It’s helpful for validating that certain key phrases or terms appear in the output, which might be essential for tasks like content generation or response validation.
from phoenix.experiments import ContainsKeyword
# This defines a code evaluator that checks for the presence of
# the keyword "success"
contains_keyword = ContainsKeyword(keyword="success")
This evaluator checks if any of a list of keywords are present in the output. It’s useful when you want to validate that at least one of several important terms or phrases appears in the generated output, providing flexibility in how success is defined.
from phoenix.experiments import ContainsAnyKeyword
# This defines a code evaluator that checks if any of the keywords
# "error", "failed", or "warning" are present
contains_any_keyword = ContainsAnyKeyword(keywords=["error", "failed", "warning"])
This evaluator ensures that all specified keywords are present in the output of an experiment run. It's useful for cases where the presence of multiple key phrases is essential, such as ensuring all required elements of a response or content piece are included.
from phoenix.experiments import ContainsAllKeywords
# This defines a code evaluator that checks if all of the keywords
# "foo" and "bar" are present
contains_all_keywords = ContainsAllKeywords(keywords=["foo", "bar"])
Advanced: Evaluator as a Class
This is an alternative you can use if you'd prefer to use object oriented programming instead of functional programming.
Eval Class Inputs
The Eval argument values are supported below:
Parameter name
Description
Example
input
experiment run input
def eval(input): ...
output
experiment run output
def eval(output): ...
dataset_row
the entire row of the data, including every column as dictionary key
def eval(expected): ...
metadata
experiment metadata
def eval(metadata): ...
class ExampleAll(Evaluator):
def evaluate(self, input, output, dataset_row, metadata, **kwargs) -> EvaluationResult:
print("Evaluator Using All Inputs")
class ExampleDatasetrow(Evaluator):
def evaluate(self, dataset_row, **kwargs) -> EvaluationResult:
print("Evaluator Using dataset_row ")
class ExampleInput(Evaluator):
def evaluate(self, input, **kwargs) -> EvaluationResult:
print("Evaluator Using Input")
class ExampleOutput(Evaluator):
def evaluate(self, output, **kwargs) -> EvaluationResult:
print("Evaluator Using Output")
EvaluationResult Outputs
The EvaluationResult results can be a score, label, tuple (score, label, explanation) or a Class EvaluationResult
Return Type
Description
EvaluationResult
Score, label and explanation
float
Score output
string
Label string output
class ExampleResult(Evaluator):
def evaluate(self, input, output, dataset_row, metadata, **kwargs) -> EvaluationResult:
print("Evaluator Using All Inputs")
return(EvaluationResult(score=score, label=label, explanation=explanation)
class ExampleScore(Evaluator):
def evaluate(self, input, output, dataset_row, metadata, **kwargs) -> EvaluationResult:
print("Evaluator Using A float")
return 1.0
class ExampleLabel(Evaluator):
def evaluate(self, input, output, dataset_row, metadata, **kwargs) -> EvaluationResult:
print("Evaluator label")
return "good"
Here's an example of a LLM evaluator that checks for hallucinations in the model output:
from phoenix.evals import (
HALLUCINATION_PROMPT_RAILS_MAP,
HALLUCINATION_PROMPT_TEMPLATE,
llm_classify,
)
from phoenix.experiments.types import EvaluationResult
from openai import OpenAIModel
class HallucinationEvaluator(Evaluator):
def evaluate(self, output, dataset_row, **kwargs) -> EvaluationResult:
print("Evaluating outputs")
expected_output = dataset_row["attributes.llm.output_messages"]
# Create a DataFrame with the actual and expected outputs
df_in = pd.DataFrame(
{"selected_output": output, "expected_output": expected_output}, index=[0]
)
# Run the LLM classification
expect_df = llm_classify(
dataframe=df_in,
template=HALLUCINATION_PROMPT_TEMPLATE,
model=OpenAIModel(model="gpt-4o-mini", api_key=OPENAI_API_KEY),
rails=HALLUCINATION_PROMPT_RAILS_MAP,
provide_explanation=True,
)
label = expect_df["label"][0]
score = 1 if label == rails[1] else 0 # Score 1 if output is incorrect
explanation = expect_df["explanation"][0]
# Return the evaluation result
return EvaluationResult(score=score, label=label, explanation=explanation)
In this example, the HallucinationEvaluator class evaluates whether the output of an experiment contains hallucinations by comparing it to the expected output using an LLM. The llm_classify function runs the eval, and the evaluator returns an EvaluationResult that includes a score, label, and explanation.
To use , use the following import statement:
To run the experiment, you can load the evaluator into as following:
Need help writing a custom evaluator template? Use ✨ to write one for you
Users have the option to run an experiment by creating an evaluator that inherits from the base class in the Arize Python SDK. The evaluator takes in a single dataset row as input and returns an dataclass.