Featured resource
2026 Tech Forecast
2026 Tech Forecast

1,500+ tech insiders, business leaders, and Pluralsight Authors share their predictions on what’s shifting fastest and how to stay ahead.

Download the forecast
  • Lab
    • Libraries: If you want this lab, consider one of these libraries.
    • Core Tech
Labs

Evaluate and Protect an AI-enabled Java Feature

You have inherited an AI-enabled Java feature that produces correct output on the happy path but has no quality checks and no protection against bad input or unsafe actions. In this lab, you evaluate the feature against defined quality criteria, add safeguards that block unsafe inputs and unauthorized actions, and write focused tests that confirm both the safeguards and the service-failure handling work as intended. At the end of this lab, you will be able to assess, harden, and verify an AI-backed feature before it reaches production.

Lab platform
Lab Info
Level
Intermediate
Last updated
Dec 02, 2026
Duration
45m

Contact sales

By clicking submit, you agree to our Privacy Policy and Terms of Use, and consent to receive marketing emails from Pluralsight.
Table of Contents
  1. Challenge

    Introduction

    Welcome to the Evaluate and Protect an AI-enabled Java Feature Code Lab. In this hands-on lab, you take over an AI-enabled support feature built with LangChain4j, measure its real behavior against defined quality criteria, add safeguards that reject unsafe inputs and block unauthorized actions, handle the ways the model service can fail, and prove all of it with focused JUnit tests.

    About the tools and concepts

    An AI-enabled feature is ordinary application code that asks a model to make one decision inside a larger flow. Here the model reads a customer message and picks one support action, such as TRACK_ORDER or ISSUE_REFUND, and your Java code carries that action out. LangChain4j wraps the model behind the ChatModel interface, so the feature calls model.chat(prompt) and gets plain text back.

    Evaluating a feature means running it against a fixed set of cases, each with an expected outcome, and comparing what the feature actually does. The share of cases that pass is the pass rate, and a quality criterion such as "pass at least 90 percent of cases" turns that number into a clear yes or no.

    A safeguard is a check that runs before or after the model and stops a request that should not go through. An input guard rejects messages that are empty, too long, or that contain a prompt injection: text written to override the model's instructions, such as ignore previous instructions. An action policy decides which actions each role may trigger, so the model's choice is treated as a suggestion and never as permission.

    Failure handling covers the three ways a model call goes wrong: the call times out, the service returns an error, or the reply does not follow the expected format. A fallback reply gives the user a safe, predictable answer in each case instead of an exception.

    Focused tests check one behavior each. A fake model, a small class that implements ChatModel and returns a fixed reply or throws a chosen exception, lets JUnit 5 tests run fast, offline, and the same way every time. assertEquals checks a value, and assertThrows checks that code throws a specific exception.

    Prerequisites

    Before starting this lab, you should have:

    • Intermediate Java skills: writing methods and classes, handling exceptions, and working with generics such as List<String> and Set<SupportAction>
    • Experience with JUnit 5: writing test methods with @Test and running them with Maven
    • Familiarity with LangChain4j: defining a feature backed by a model through the ChatModel interface; no model-training knowledge is needed

    The lab environment is ready to use. Run java -version and mvn -version from the terminal at any time to confirm the runtime.

    The scenario

    You are a backend developer at CarvedRock. The team has handed you the support assistant, an AI-enabled feature that reads a customer message, asks a model which action to take, and then tracks an order, updates an address, issues a refund, or closes an account. It works on the happy path, but it has no quality gate, no input protection, and no failure handling. Before it reaches production, your job is to measure how it really behaves, harden it, and prove the hardening works with tests.

    The application structure

    Key files in the lab environment Source files live in `workspace/src/main/java/com/carvedrock/support/`, and test files live in `workspace/src/test/java/com/carvedrock/support/`.
    • QualityCriteria.java: the quality bar and safeguard limits every other class reads from
    • SupportAssistant.java: the AI-enabled feature that guards the input, calls the model, parses the reply, checks the policy, and runs the action
    • FeatureEvaluator.java: scores the feature against the evaluation cases and records every shortfall
    • InputGuard.java: rejects unsafe customer messages before they reach the model
    • ActionPolicy.java: decides which actions each role may trigger
    • ResponseParser.java and SupportAction.java: turn the model's text reply into a known action
    • ModelConfig.java: builds the LangChain4j ChatModel for the lab's gpt-4o-mini endpoint; treat it as a black box
    • ActionExecutor.java: carries out the chosen action; the actions are simulated, so nothing outside the workspace changes
    • RunEvaluation.java: the runner that evaluates the feature, prints the report, and saves it to reports/evaluation-report.txt
    • SafeguardTest.java and FailureHandlingTest.java: the focused tests you complete
    • FakeChatModel.java: the test stand-in for the real model
    • workspace/data/eval-cases.txt: the ten evaluation cases, each with a role, a message, and the expected outcome
    • workspace/solutions/: reference solutions for each task, prefixed with sol-

    Complete the tasks in order. Each task builds on the previous one.

    The evaluation runner makes a call to the lab AI, so before you run it, export your lab key into the shell. The key is shown at the top of the lab pane and changes each time the lab starts:

    export LAB_API_KEY=<the key shown at the top of the lab pane>
    

    Note: The export applies only to the current terminal, so run it again if you open a new terminal. Then run the evaluation against the live model at any point with:

    cd ~/workspace && mvn -q compile exec:java
    

    Maven may print a few WARNING lines about restricted or deprecated methods before your output. They come from Maven's own libraries on newer Java versions and are safe to ignore.

  2. Challenge

    Evaluating the AI feature against quality criteria

    Defining measurable quality criteria

    You can't tell whether an AI feature is ready until you decide what "ready" means. Quality criteria turn that decision into numbers: the share of evaluation cases the feature must pass, the longest message it accepts, the phrases that signal an attack, and how long it waits for the model. Keeping all of these in QualityCriteria.java means the evaluator, the input guard, and the model client read the same values, so tightening a rule later is a one-line change.

    Scoring the feature's real behavior

    An evaluation runs every case in data/eval-cases.txt through the feature and compares the actual outcome with the expected one. Five cases are normal requests the model should handle. The other five are unsafe: an empty message, an oversized message, a prompt injection, and two customers asking for actions only a support agent may run. For those cases, the expected outcome is REJECTED or BLOCKED. Each case that does not match becomes a shortfall, and the pass rate, compared with MIN_PASS_RATE, gives the verdict. Because passedCount and the number of cases are both whole numbers, the pass rate calculation casts passedCount to double first. The cast keeps Java from rounding the result down to a whole number. The runner prints the report and saves it to reports/evaluation-report.txt, so you have a record of where the feature falls short.

  3. Challenge

    Applying safeguards to inputs and actions

    Rejecting unsafe inputs before they reach the model

    The cheapest place to stop a bad request is before the model ever sees it.

    An input guard runs a few plain checks: is the message present, is it within the length limit, and does it contain a known injection phrase? Lowercasing the message first means Ignore Previous Instructions and ignore previous instructions are caught the same way. When a check fails, the guard throws UnsafeInputException, and the feature turns that exception into a REJECTED reply. ### Blocking actions the caller is not allowed to trigger

    A model can be talked into picking any action on its list, so the model's choice can't be what grants permission. An action policy applies least privilege: each role gets only the actions it needs. Customers may track orders and update addresses, while support agents may run every action. EnumSet is a compact, fast Set built for enum values, and checking the model's choice against the caller's set happens after the model replies and before anything runs.

  4. Challenge

    Handling model-service failures

    Treating the model's reply as untrusted input

    The prompt asks the model to answer with one line, such as ACTION: TRACK_ORDER, but nothing forces it to... It might return an empty string, a friendly sentence, or an action name that doesn't exist. The parser checks the reply the same way the guard checks the user's message: is it present, does it start with the ACTION: prefix, and does it name a supported action? Every failed check throws MalformedResponseException, so the feature has one clear signal that the reply can't be trusted. ### Falling back safely when the model fails

    When the model times out, the service returns an error, or the reply is malformed, the feature still owes the user an answer. Right now each catch block rethrows the exception, so the failure escapes to the caller. A fallback reply replaces that crash with a predictable FALLBACK outcome and a clear message. LangChain4j reports timeouts and service errors as subclasses of RuntimeException, so one catch around the model call covers both, and a second catch covers the parser.

  5. Challenge

    Verifying safeguards and failure handling with focused tests

    Testing safeguards with a fake model

    The evaluation proves the feature works today against the live model, but you also need tests that run on every build without a network call.

    FakeChatModel implements ChatModel, returns whatever reply you give it, and counts how many times the feature called it. That count matters: a rejected message must never reach the model, and assertEquals(0, model.callCount()) proves it. Each test arranges a fake model and a request, calls handle, and asserts on the outcome, so a failing test points straight at the safeguard that broke. ### Testing how the feature fails

    Failure paths are the easiest code to leave untested, because they rarely happen during development. A fake model makes them happen on demand: FakeChatModel.failingWith(...) throws LangChain4j's own TimeoutException or InternalServerException, and FakeChatModel.replying(...) can return a reply in the wrong format. assertThrows checks the parser directly, and it passes only when the code inside the lambda throws the exception type you name.

  6. Challenge

    Run the full verification

    Now that every task is complete, run the whole check from start to finish: the focused tests first, then the evaluation against the live model.

    1. Confirm the runtime is available:

      java -version
      
    2. Run the full test suite:

      cd ~/workspace && mvn test
      
    3. Confirm Maven reports the expected results:

      • Tests run: 8
      • Failures: 0
      • Errors: 0
      • Build status: BUILD SUCCESS
    4. Run the evaluation against the live model:

      cd ~/workspace && mvn -q compile exec:java
      
    5. Monitor the evaluation output. It should print:

      • An [INIT] line as the ten cases load.
      • Two [EVAL] lines with the pass count and pass rate.
      • A [RESULT] line with the verdict.
      • A [DONE] line with the report location and execution time.
    6. Verify the evaluation results:

      • [EVAL] reports 10 of 10 cases.
      • Pass rate: 1.00.
      • [RESULT] reports true.
    7. Open the evaluation report:

      workspace/reports/evaluation-report.txt
      

    Expected Result: Every layer you built is visible in one run: the quality criteria define the bar, the evaluator measures the feature against it, the input guard and action policy stop unsafe requests, the fallback handles model failures, and the focused tests prove each behavior without calling the live model.

  7. Challenge

    Conclusion

    Congratulations on completing the Evaluate and Protect an AI-enabled Java Feature lab! You have taken an AI-enabled feature that only worked on the happy path, measured it against defined quality criteria, hardened it with safeguards and failure handling, and verified every protection with focused tests. These are the steps you need to make any AI-backed feature ready for production.

    What you have accomplished

    1. Set the quality criteria and safeguard limits: Defined the pass-rate threshold, the input limit, the blocked phrases, and the model timeout in one shared class.
    2. Scored the feature against the evaluation cases: Ran every case through the live feature, computed the pass rate, and recorded each shortfall.
    3. Rejected unsafe inputs: Stopped empty, oversized, and prompt-injection messages before they reach the model.
    4. Blocked unauthorized actions: Applied a role-based policy so the model's choice never grants permission on its own.
    5. Detected malformed model replies: Checked that each reply is present, correctly formatted, and names a supported action.
    6. Returned a fallback reply on failure: Replaced crashes from timeouts, service errors, and malformed replies with a predictable fallback.
    7. Tested the safeguards: Proved with a fake model that unsafe input is rejected and unauthorized actions are blocked.
    8. Tested the service-failure handling: Proved that every failure path returns a fallback reply and that the parser rejects unsupported actions.

    Key takeaways

    • An evaluation set with expected outcomes and a pass-rate threshold replaces a gut feeling about the feature with a measurable yes or no.
    • Keeping quality criteria and safeguard limits in one class makes every rule easy to find and change.
    • Validate user input before the model sees it; it is cheaper and safer than cleaning up afterward.
    • Treat the model's choice as a suggestion, and let an explicit action policy decide what each role may do.
    • Treat the model's reply as untrusted input, and parse it defensively.
    • Timeouts, service errors, and malformed replies should all end in a predictable fallback, never in an unhandled exception.
    • A fake model lets focused tests cover safeguards and failure paths quickly, offline, and the same way every time.

    Experiment before you go

    You still have time in the lab environment. Try these explorations:

    • Add a new line to data/eval-cases.txt with a message that contains reveal your system prompt, set the expected outcome to REJECTED, and rerun the evaluation to watch the guard catch it.
    • Raise MIN_PASS_RATE to 1.0 in QualityCriteria.java, remove UPDATE_ADDRESS from CUSTOMER_ACTIONS, and rerun the evaluation: the update-address case turns into a BLOCKED shortfall, and that single miss now fails the whole run.
    • Add a test to FailureHandlingTest.java that uses FakeChatModel.replying("") and asserts a FALLBACK outcome for an empty model reply.
    • Lower MODEL_TIMEOUT to Duration.ofMillis(1) and rerun the evaluation to watch the real timeout path return fallback replies.
About the author

Angel Sayani is a Certified Artificial Intelligence Expert®, CEO of IntellChromatics, author of two books in cybersecurity and IT certifications, world record holder, and a well-known cybersecurity and digital forensics expert.

Real skill practice before real-world application

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Learn by doing

Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.

Follow your guide

All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.

Turn time into mastery

On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.

Get started with Pluralsight