- Lab
-
Libraries: If you want this lab, consider one of these libraries.
Build an AI-enabled Java Feature with LangChain4j
Turn a language model into a dependable part of your Java application in this hands-on lab. Use LangChain4j to build a support ticket triage feature, map the model's response to a typed Java record, and validate required fields before your application relies on them. Then test successful processing and model-service failure handling with mocked responses. Ideal for back-end Java developers who want practical experience building reliable, AI-enabled features.
Lab Info
Table of Contents
-
Challenge
Step 1: Explore the ticket triage project
Welcome to the lab. Today, you're a back-end developer at a fitness center that runs an online store, and you're tasked with adding an AI-enabled triage feature to its support system. Support agents read and route every incoming customer ticket by hand, and the backlog keeps growing.
You will use LangChain4j to send each ticket to a language model, map the model's response to a typed Java record, and validate that record before the routing code relies on it. You will then prove with tests that the feature behaves predictably when the model answers well and when the model service fails. These are the same steps you follow to add a model-backed feature to any Java service.
The environment provides these files:
src/main/java/com/example/triage/ModelConfig.javabuilds the LangChain4jChatModel.src/main/resources/prompts/ticket-triage.txtis the prompt template for the triage request.src/main/java/com/example/triage/TicketRouter.javaroutes a triage result to a support queue.src/main/java/com/example/triage/TriageApp.javais the command-line entry point that runs the feature.
You create or complete these files:
src/main/java/com/example/triage/TicketTriageAssistant.javais the AI Service interface. You create it.src/main/java/com/example/triage/TicketTriageService.javacalls the model and returns the triage result.src/main/java/com/example/triage/TicketTriage.javais the record that holds the triage result.src/main/java/com/example/triage/TicketTriageValidator.javachecks the required fields.src/test/java/com/example/triage/TicketTriageServiceTest.javaholds the tests with mocked model responses.
Notes:
- The project is a Maven project in the
workspacedirectory. Source files are insrc/main/java/com/example/triage, and tests are insrc/test/java/com/example/triage. - The lab works on Java 17, 21, and 25. The lab environment provides one of these versions.
- Run all commands in the Terminal, which opens in the
workspacedirectory. - Press
Enterafter each command to run it.
The model is a simulated model service that runs inside the lab environment at
http://localhost:8089. You start it before you run the feature for the first time. It returns the same response for the same ticket every time, so you do not need an API key.If a later command reports that it cannot reach the model service, start the service again with the following command, then run the failed command again:
nohup java sim/SimulatedModelService.java > /tmp/model-sim.log 2>&1 &What you'll accomplish
- Connect a provided LangChain4j configuration and prompt template with an AI Service.
- Map the model's response to a Java record and validate its required fields.
- Test the success path and a model-service failure with mocked responses.
- Add a fallback that sends a ticket to manual review when the model service fails.
Explore the provided code
Before you write code, get to know the two provided pieces that the feature is built on: the model configuration and the prompt template.
-
Confirm the Java version:
java -versionExpected result: The first line of the output shows a version that starts with
17,21, or25. -
In the editor, open
src/main/java/com/example/triage/ModelConfig.javaand review thechatModel()method.The method builds an
OpenAiChatModeland returns it as aChatModel, the LangChain4j interface for a chat-based language model. ThebaseUrlsetting points the model at the simulated model service. -
Open
src/main/resources/prompts/ticket-triage.txtand review the prompt template.The template tells the model to answer with a JSON object that has
category,priority, andsummaryfields. The{{ticketText}}placeholder is a template variable. LangChain4j replaces it with the ticket text on every call.
With the configuration and the template in mind, you are ready to connect them. Continue to the next step.
-
Challenge
Step 2: Implement the model-backed triage feature
The project already contains a LangChain4j configuration and a prompt template. In this step, you connect them with an AI Service, which is a Java interface that LangChain4j implements for you at runtime.
By the end of the step, the application sends a sample ticket to the simulated model service and prints the raw response.
What you'll accomplish
- Declare an AI Service interface that loads the prompt template.
- Build the assistant with
AiServicesand call it from the service. - Run the feature and inspect the raw response from the simulated model service. The interface describes the call. Next, you ask LangChain4j to build an object that makes it. Everything is wired up, so it is time to send a sample ticket to the simulated model service. The feature now reaches the model and returns its answer as raw text. In the next step, you turn that text into a typed Java object.
-
Challenge
Step 3: Map the response to a Java object and validate required fields
The feature works, but it returns a
Stringthat the rest of the application would have to parse. In this step, you'll let LangChain4j map the response to a Java record, and then you'll validate that record.Validation matters because a model can leave a field out, and LangChain4j maps a missing field to
nullwithout raising an error.What you'll accomplish
- Complete the
TicketTriagerecord so that it matches the model's response. - Return a typed
TicketTriageinstead of aString. - Reject a response with a missing category, a missing priority, or a blank summary.
- Validate every result before the routing code receives it. The record is ready. Now you tell the assistant to return it.
The AI Service reads the return type of the
triagemethod, asks the model for a response in that shape, and parses the response into the record. If the response is not valid JSON, or a category or priority is not a value that the enum defines, the call fails with an exception. Changing a return type is all it takes for LangChain4j to parse the response and build the record for you. The vague ticket shows the problem with trusting the model's output: a missing field arrives asnull. A validator closes that gap.TicketTriageValidatorchecks that a result has every field the routing code relies on. The validator exists, but nothing calls it yet. The service is the right place to validate, because every result passes through it before it reaches the routing code. An incomplete response is now rejected before the routing code can use it. In the next step, you prove this behavior with tests that do not need a running model. - Complete the
-
Challenge
Step 4: Verify success and failure handling with mocked responses
Tests for a model-backed feature should not depend on a running model. In this step, you replace the
ChatModelwith a mock that returns the response you choose, so that each test is fast and repeatable.The AI Service calls the
chat(ChatRequest)method on theChatModel, so the tests stub that method to control the response.You test the success path, a response with a missing field, and a model service that fails.
What you'll accomplish
- Replace the chat model with a Mockito mock in a JUnit test.
- Test a complete response and a response with a missing field.
- Write a test for a model-service failure and watch it fail.
- Add a manual review fallback that makes the test pass. The success path is covered. Next, you test what happens when the model leaves a field out. The test feeds the service a response with no
priorityand expects the validator to reject it. Incomplete responses are handled. The last case is a model service that does not answer at all. You write this test before the code that satisfies it, so that you can watch it fail for the right reason. The failing test tells you exactly what is missing: the service has no plan for a model failure. A fallback keeps the support workflow moving when the model service is down. The ticket goes to a support agent instead of being lost. All three tests pass. Finish with a full run of the suite and one last live check. ### Wrap-up
You're now done with the lab. In it, you:
- Built a model-backed triage feature with a LangChain4j AI Service.
- Mapped the model's response to a Java record.
- Validated the required fields before the routing code used them.
- Verified the success and failure paths with mocked responses.
To keep exploring:
- Add a test for a response with a blank
summary, and confirm that the validator rejects it. - Run the feature on
tickets/return.txtand compare the result with the shipping ticket. - Move the role description from the prompt template into a
@SystemMessageannotation on the interface, and run the tests again.
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.