Skip to main content

Overview

Evaluating LLM outputs is critical, but underexplored for generative AI uses cases. Natural language unit tests provide a systematic approach for evaluating LLM response quality. Contextual AI’s LMUnit is a specialized model that achieves state-of-the-art performance in creating and applying unit tests to evaluate LLM outputs.

Why Natural Language Unit Testing?

Traditional LLM evaluation methods often face several challenges:
  • Human evaluations are inconsistent and costly, while metrics like ROUGE fail to capture nuanced quality measures.
  • General-purpose LLMs may not provide fine-grained feedback
  • Simple yes/no evaluations miss important nuances
Natural language unit tests address these challenges by:
  • Breaking down evaluation into specific, testable criteria
  • Providing granular feedback on different quality aspects
  • Enabling systematic improvement of LLM outputs
  • Supporting domain-specific quality requirements
For example, financial compliance often requires precise regulatory phrasing, which is hard to assess with a generic style evaluation.

1. Set Up Development Environment

Set up your environment to start using LMUnit to evaluate LLM responses. This example uses LMUnit as provided through the Contextual AI python client, so install it first.
You’ll need several Python packages for data handling and visualization:
To use LMUnit, you’ll need an API key from Contextual AI. Follow these instructions to get your API key.

2. Load Evaluation Dataset

LMUnit evaluates query–response pairs, which means we need:
  • The original query/promptprompt
  • The LLM’s responseresponse
This example uses synthetic financial data. The dataset contains 10 financial questions and responses designed to highlight different aspects of response-quality evaluation.

3. Identify Unit Tests

Unit tests offer deeper insight than simply asking an LLM whether a response is “high quality.” When writing effective unit tests, strive to ensure they are:
  • Specific and focused on a single aspect
  • Clear and unambiguous
  • Measurable and consistent
  • Relevant to the domain
  • Framed positively
You should create unit tests tailored to your own use case. For this example, we use six global unit tests across all responses. These reflect critical dimensions of high-quality communication in financial services.

Context

Question: “Are relevant market conditions or external factors acknowledged?”
Why: Ensures responses consider the broader financial environment.

Clarity

Question: “Is complex financial information presented in an accessible way?”
Why: Tests whether technical concepts are explained effectively.

Precision

Question: “Is terminology used accurately and consistently?”
Why: Validates the correct use of financial terms.

Compliance

Question: “Does the response adhere to relevant financial regulations and disclosure requirements?”
Why: Ensures regulatory alignment.

Actionable

Question: “Does the response provide clear next steps or implications?”
Why: Tests practical usefulness.

Risks

Question: “Are potential risks clearly identified and explained?”
Why: Verifies appropriate risk disclosure.

4. Evaluate Unit Tests Using LMUnit

LMUnit is specifically trained to evaluate natural-language unit tests and provides several advantages:
  • Scores on a continuous 1–5 scale
  • Consistent evaluation across different criteria
  • Stronger performance than general-purpose LLMs like GPT-4
  • Support for custom scoring rubrics
  • Threshold-based binary scoring, e.g., score > 2.5 → 1, else 0
Below is a simple example demonstrating how LMUnit evaluates a response against a single unit test.
Here is more complex example with a custom scoring rubric:
For this use case, you will need to apply each global unit test to the query/response pairs we identified in the evaluation data. Here is helper function for testing batches:
Now examine the results—you see every unit test is scored on a continuous scale of 1-5.
Save out the results

5. Visualize Individual Results

Visualizations are helpful for understanding unit test results. Create a visualization of individual response radar plots showing performance across all dimensions:
Radar plots are a great way to visualize the different dimensions that the unit tests provide. Try changing the index to view other plots:
You want to compare multiple plots? Try this

6. Visualize Group Results

For analyzing larger sets of results, it’s useful to use clustering methods. Let’s walk through using clustering to help analyze a dataset of 40 unit test results.
Start by using Kmeans and clustering this into four groups. For your analysis, you may need to use fewer or more clusters.
Look at how each of our samples are now clustered:
You can visualize these cluster, both in terms of how the clusters centers vary as well as how the individuals points.
The following code helps analyze the clusters by the categories used for unit tests:

Interpret the clusters

Now that you have a better understanding of the response clusters, you can identify the patterns and characteristics of each cluster. After looking at the clusters, these patterns should emerge: Cluster 0: Compliance Blind Spot. High CLARITY/PRECISION, Low COMPLIANCE/RISK Clear communication but missing regulatory elements Cluster 1: Clarity Gap. High CONTEXT/RISK, Low CLARITY/PRECISION High context awareness but poor explanation clarity Cluster 2: Theory-Practice Gap. High PRECISION/CLARITY, Low ACTIONABLE. Strong theoretical understanding but impractical Cluster 3: Surface Analysis Medium CLARITY but Low CONTEXT/RISK Basic understanding without depth
Your clusters may be less straightforward to interpret, so use the patterns that do emerge to guide error analysis and refinement.

Best Practices for Using LMUnit

Unit Test Design:

  • Keep tests focused and specific
  • Avoid compound criteria
  • Use clear, unambiguous language
  • Assess a desirable quality, such as “Is the response coherent?” rather than “Is the response incoherent?”

Evaluation Strategy:

  • Start with global tests
  • Add query-level tests as needed
  • Monitor patterns across responses

Score Interpretation:

  • 5: Excellent - Fully satisfies criteria
  • 4: Good - Minor issues
  • 3: Acceptable - Some issues
  • 2: Poor - Significant issues
  • 1: Unacceptable - Fails criteria
You can provide a custom rubric for scoring.

Next Steps

  • Customize unit tests for your use case
  • Integrate with your evaluation pipeline
  • Monitor and adjust based on results

Additional Resources