- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech
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 Info
Table of Contents
-
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_ORDERorISSUE_REFUND, and your Java code carries that action out. LangChain4j wraps the model behind theChatModelinterface, so the feature callsmodel.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
ChatModeland returns a fixed reply or throws a chosen exception, lets JUnit 5 tests run fast, offline, and the same way every time.assertEqualschecks a value, andassertThrowschecks 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>andSet<SupportAction> - Experience with JUnit 5: writing test methods with
@Testand running them with Maven - Familiarity with LangChain4j: defining a feature backed by a model through the
ChatModelinterface; no model-training knowledge is needed
The lab environment is ready to use. Run
java -versionandmvn -versionfrom 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 fromSupportAssistant.java: the AI-enabled feature that guards the input, calls the model, parses the reply, checks the policy, and runs the actionFeatureEvaluator.java: scores the feature against the evaluation cases and records every shortfallInputGuard.java: rejects unsafe customer messages before they reach the modelActionPolicy.java: decides which actions each role may triggerResponseParser.javaandSupportAction.java: turn the model's text reply into a known actionModelConfig.java: builds the LangChain4jChatModelfor the lab'sgpt-4o-miniendpoint; treat it as a black boxActionExecutor.java: carries out the chosen action; the actions are simulated, so nothing outside the workspace changesRunEvaluation.java: the runner that evaluates the feature, prints the report, and saves it toreports/evaluation-report.txtSafeguardTest.javaandFailureHandlingTest.java: the focused tests you completeFakeChatModel.java: the test stand-in for the real modelworkspace/data/eval-cases.txt: the ten evaluation cases, each with a role, a message, and the expected outcomeworkspace/solutions/: reference solutions for each task, prefixed withsol-
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:javaMaven may print a few
WARNINGlines about restricted or deprecated methods before your output. They come from Maven's own libraries on newer Java versions and are safe to ignore. - Intermediate Java skills: writing methods and classes, handling exceptions, and working with generics such as
-
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.javameans 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.txtthrough 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 isREJECTEDorBLOCKED. Each case that does not match becomes a shortfall, and the pass rate, compared withMIN_PASS_RATE, gives the verdict. BecausepassedCountand the number of cases are both whole numbers, the pass rate calculation castspassedCounttodoublefirst. The cast keeps Java from rounding the result down to a whole number. The runner prints the report and saves it toreports/evaluation-report.txt, so you have a record of where the feature falls short. -
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 Instructionsandignore previous instructionsare caught the same way. When a check fails, the guard throwsUnsafeInputException, and the feature turns that exception into aREJECTEDreply. ### Blocking actions the caller is not allowed to triggerA 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.
EnumSetis a compact, fastSetbuilt for enum values, and checking the model's choice against the caller's set happens after the model replies and before anything runs. -
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 theACTION:prefix, and does it name a supported action? Every failed check throwsMalformedResponseException, so the feature has one clear signal that the reply can't be trusted. ### Falling back safely when the model failsWhen 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
catchblock rethrows the exception, so the failure escapes to the caller. A fallback reply replaces that crash with a predictableFALLBACKoutcome and a clear message. LangChain4j reports timeouts and service errors as subclasses ofRuntimeException, so onecatcharound the model call covers both, and a secondcatchcovers the parser. -
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.
FakeChatModelimplementsChatModel, 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, andassertEquals(0, model.callCount())proves it. Each test arranges a fake model and a request, callshandle, and asserts on the outcome, so a failing test points straight at the safeguard that broke. ### Testing how the feature failsFailure 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 ownTimeoutExceptionorInternalServerException, andFakeChatModel.replying(...)can return a reply in the wrong format.assertThrowschecks the parser directly, and it passes only when the code inside the lambda throws the exception type you name. -
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.
-
Confirm the runtime is available:
java -version -
Run the full test suite:
cd ~/workspace && mvn test -
Confirm Maven reports the expected results:
- Tests run: 8
- Failures: 0
- Errors: 0
- Build status: BUILD SUCCESS
-
Run the evaluation against the live model:
cd ~/workspace && mvn -q compile exec:java -
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.
- An
-
Verify the evaluation results:
[EVAL]reports 10 of 10 cases.- Pass rate: 1.00.
[RESULT]reports true.
-
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.
-
-
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
- 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.
- Scored the feature against the evaluation cases: Ran every case through the live feature, computed the pass rate, and recorded each shortfall.
- Rejected unsafe inputs: Stopped empty, oversized, and prompt-injection messages before they reach the model.
- Blocked unauthorized actions: Applied a role-based policy so the model's choice never grants permission on its own.
- Detected malformed model replies: Checked that each reply is present, correctly formatted, and names a supported action.
- Returned a fallback reply on failure: Replaced crashes from timeouts, service errors, and malformed replies with a predictable fallback.
- Tested the safeguards: Proved with a fake model that unsafe input is rejected and unauthorized actions are blocked.
- 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.txtwith a message that containsreveal your system prompt, set the expected outcome toREJECTED, and rerun the evaluation to watch the guard catch it. - Raise
MIN_PASS_RATEto1.0inQualityCriteria.java, removeUPDATE_ADDRESSfromCUSTOMER_ACTIONS, and rerun the evaluation: theupdate-addresscase turns into aBLOCKEDshortfall, and that single miss now fails the whole run. - Add a test to
FailureHandlingTest.javathat usesFakeChatModel.replying("")and asserts aFALLBACKoutcome for an empty model reply. - Lower
MODEL_TIMEOUTtoDuration.ofMillis(1)and rerun the evaluation to watch the real timeout path return fallback replies.
About the author
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.