Club.noww.in
So far in this series, we have explored each major component of an AI agent individually:
· Perception Module
· Planning Module
· Memory
· Action Module
· Orchestrator
Understanding these modules independently is important, but the real value comes from seeing how they collaborate to solve a real problem.
In this post, we will build a simple Travel Booking Agent. This is not a production-ready travel assistant, nor does it connect to real airline or hotel APIs. Instead, its purpose is educational, it demonstrates how the core architectural building blocks of an AI agent work together in a complete ReAct loop.
The agent will accept a travel request such as: "Book my trip to London for 5 days"
It will then:
· Understand the user's intent
· Reason about the next action
· Search for flights
· Search for hotels
· Ask the user for missing information when necessary
· Book the selected options
· Send a confirmation email, and
· Optionally suggest local tour plans
Although the tools are mocked with hardcoded data, the architecture closely resembles what a production AI agent would use. Once you understand this example, replacing the mock tools with real APIs becomes straightforward.
By the end of this post, you will see how the Perception Module, Planning Module, Memory, Action Module, Tool Registry, and Orchestrator work together to create a complete AI agent.
Prerequisites
Ollama
Download llama3.2 model
What We Are Going to Build ?
Our Travel Booking Agent consists of six major architectural components.
· Perception Module: Understanding the User
· Planning Module: Deciding What to Do Next
· Agent Memory: The Agent's Working Memory
· Action Module: Executing the Plan
· Tool Registry: Discovering Available Tools
· Agent Orchestrator: Coordinating the Entire Workflow
Each component has a single responsibility, making the system modular, maintainable, and easy to extend. The following sections explain each module in detail.
1. Goal: Representing the User's Objective
Every AI agent needs a clear objective before it can begin reasoning. Rather than passing raw text throughout the application, our agent converts the user's request into a structured object called Goal.
public record Goal(String description) {}
Although this class appears simple, it represents an important architectural principle. Instead of allowing every module to interpret free-form text differently, the Goal object becomes the shared understanding of what the user wants to accomplish.
For example:
User: I want to visit Paris next month.
Goal: Book a trip to Paris next month.
From this point onward, every module works with the Goal instead of the original user input.
2. Perception Module: Understanding the User
The first responsibility of the agent is understanding the user's request. The Perception Module receives raw text from the console, cleans or normalizes it if necessary, and converts it into a Goal object.
User Input -> Perception Module -> Goal
Sample Code
public class PerceptionModule { public Goal perceive(String rawInput) { return new Goal(normalized); } }
In a real AI system, the Perception Module might perform:
· Intent detection
· Entity extraction
· Language translation
· Spell correction
· Sentiment analysis
· Multimodal processing
For this demo, it simply transforms user input into a Goal. The rest of the agent never interacts with raw console input again.
3. Planning Module: Deciding What to Do Next
Once the goal is known, the agent must determine the next action. The Planning Module is responsible only for reasoning.
It never books flights, searches hotels, or sends emails. Instead, it asks the language model a single question, Given the current goal, memory, and available tools, what should I do next?
Internally it uses two helper classes.
LlmClient
A thin wrapper around LangChain4j that sends prompts to Ollama and returns the raw response.
Planning Module -> LlmClient -> Ollama LLM
PlanParser
The language model produces text, but the rest of the application needs structured data.
The PlanParser converts the LLM response into a PlanResponse.
public record PlanResponse( String status, PlanStep nextStep) {}
Each plan contains a single executable step.
public record PlanStep( String toolName, Map<String,String> parameters, String reasoning) {}
Example:
toolName: FlightSearchTool Parameters: destination = Paris departureDate = 2026-08-15 Reasoning: Search flights before selecting one.
The planner therefore acts as the brain of the agent.
4. Agent Memory: The Agent's Working Memory
An AI agent cannot make intelligent decisions without remembering what has already happened. AgentMemory stores the entire mutable state of the booking workflow.
public class AgentMemory { private Goal goal; private List<Flight> availableFlights; private List<Hotel> availableHotels; private Flight selectedFlight; private Hotel selectedHotel; private boolean flightBooked; private boolean hotelBooked; private boolean emailSent; private boolean tourPlansSuggested; }
As tools execute, they continuously update this shared memory. For example:
FlightSearchTool ↓ availableFlights updated ↓ FlightBookTool ↓ flightBooked = true ↓ EmailTool ↓ emailSent = true
Every planning cycle reads from the latest memory state, enabling the agent to make informed decisions rather than repeating completed actions.
5. Action Module: Executing the Plan
The Planning Module decides what should happen. The Action Module performs it. Its responsibility is straightforward:
· Receive a PlanStep
· Locate the appropriate tool
· Execute the tool
· Update memory, and
· Return the observation
public class ActionModule { public ActionResult execute( PlanStep step, AgentMemory memory) { } }
This strict separation keeps reasoning independent from execution. The planner never directly calls APIs. The action module never decides what should happen next.
6. Tools: The Agent's Capabilities
Tools are the external capabilities that allow the agent to interact with the world. Each tool implements a common interface.
public interface Tool { String getName(); String getDescription(); String getParameterDescription(); ActionResult execute( Map<String,String> params, AgentMemory memory); }
Because every tool follows the same contract, the Action Module can invoke any tool without knowing its internal implementation. For this demo, the Travel Agent includes the following tools:
|
Tool |
Purpose |
|
AskUserTool |
Collect missing information from the user |
|
FlightSearchTool |
Return available flights |
|
FlightBookTool |
Book the selected flight |
|
HotelSearchTool |
Return available hotels |
|
HotelBookTool |
Book the selected hotel |
|
EmailTool |
Send a booking confirmation |
|
SuggestTourPlansTool |
Recommend tour packages |
Notice that every tool is responsible for only one task. This makes tools reusable, independently testable, and easy to replace with real APIs in the future.
7. Tool Registry: Discovering Available Tools
Rather than hardcoding tool implementations inside the Action Module, all tools are registered in a central Tool Registry.
Tool Registry │ ├── FlightSearchTool ├── HotelSearchTool ├── FlightBookTool ├── HotelBookTool ├── EmailTool ├── AskUserTool └── SuggestTourPlansTool
When the planner requests a tool by name, the Action Module simply asks the registry for the corresponding implementation. This design makes adding new tools as simple as registering another implementation, without modifying the Action Module.
8. Agent Orchestrator: Coordinating the Entire Workflow
The Agent Orchestrator is the conductor of the entire system. It does not perform reasoning. It does not execute tools. Instead, it coordinates the complete ReAct loop by invoking the right module at the right time.
Its workflow looks like this:
· Store the user's goal in memory
· Ask the Planning Module for the next step
· Check whether the planner has completed or failed
· Execute the planned action through the Action Module
· Update memory with the action result
· Repeat until the booking workflow is complete
The orchestrator also contains deterministic safeguards. Rather than relying solely on the LLM to signal completion, it checks whether the required business conditions have been satisfied. For example, ensuring the flight and hotel are booked and the confirmation email has been sent. This makes the workflow more reliable and prevents unnecessary planning iterations.
In essence, the orchestrator manages the conversation between all other components, ensuring they work together as a cohesive agent.
The key ideas are:
· Perception converts raw user input into a structured goal.
· Planning reasons about the next action without executing it.
· Memory preserves the agent's state across reasoning cycles.
· Action Module executes one planned step at a time through tools.
· Tool Registry decouples the agent from specific tool implementations.
· Orchestrator coordinates the complete ReAct loop and enforces deterministic workflow completion.
This separation of responsibilities keeps the agent modular, easier to test, and simple to extend. Replacing the mock implementations with real airline, hotel, email, and payment APIs would transform this educational example into the foundation of a production-ready travel assistant.
Follow below step-by-step procedure to build complete working Application.
Step 1: Create new maven project 'travel-agent-example'.
Step 2: Update pom.xml with maven dependencies.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.sample.app</groupId> <artifactId>travel-agent-example</artifactId> <version>1.0.0</version> <name>Travel Agent Demo</name> <description>Console-based ReAct Travel Planner AI Agent using LangChain4j and Ollama</description> <properties> <!-- Java --> <maven.compiler.release>21</maven.compiler.release> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- Dependency Versions --> <langchain4j.version>1.0.0-beta2</langchain4j.version> <jackson.version>2.17.2</jackson.version> <slf4j.version>2.0.13</slf4j.version> <logback.version>1.5.8</logback.version> <junit.version>5.11.0</junit.version> </properties> <dependencies> <!-- ========================= --> <!-- LangChain4j --> <!-- ========================= --> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j</artifactId> <version>${langchain4j.version}</version> </dependency> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j-ollama</artifactId> <version>${langchain4j.version}</version> </dependency> <!-- ========================= --> <!-- JSON --> <!-- ========================= --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <!-- ========================= --> <!-- Logging --> <!-- ========================= --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.version}</version> </dependency> <!-- ========================= --> <!-- Unit Tests --> <!-- ========================= --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <!-- Java Compiler --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.13.0</version> <configuration> <release>21</release> </configuration> </plugin> <!-- Unit Tests --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.5.0</version> </plugin> <!-- Build Executable JAR --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.6.0</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <filters> <filter> <artifact>*:*</artifact> <excludes> <exclude>META-INF/*.SF</exclude> <exclude>META-INF/*.DSA</exclude> <exclude>META-INF/*.RSA</exclude> </excludes> </filter> </filters> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" /> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>com.sample.app.App</mainClass> </transformer> </transformers> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>
Step 3: Define model classes used by Perception, Planning and Action modules.
Create com.sample.app.model package and define following classes.
ActionResult.java
package com.sample.app.model; /** * Represents the outcome of a tool execution performed by the Action Module. * * <p>After each tool runs, the Action Module wraps the result in an ActionResult and passes it back * to the Orchestrator, which writes the observation into AgentMemory. The Planner reads these * observations on the next cycle to decide what to do next — this is the Observe step of the ReAct * loop. * * @param success {@code true} if the tool executed without error. * @param observation A human-readable summary of what happened (e.g., "3 flights found"). This text * is injected verbatim into the next planning prompt. * @param data Optional structured payload (e.g., a {@code List<Flight>}). May be {@code null} when * the tool produces no structured output. */ public record ActionResult(boolean success, String observation, Object data) { /** * Factory method for a successful result with no structured data. * * @param observation human-readable summary * @return successful ActionResult */ public static ActionResult success(String observation) { return new ActionResult(true, observation, null); } /** * Factory method for a successful result with structured data. * * @param observation human-readable summary * @param data structured result payload * @return successful ActionResult */ public static ActionResult success(String observation, Object data) { return new ActionResult(true, observation, data); } /** * Factory method for a failed result. * * @param observation description of what went wrong * @return failed ActionResult */ public static ActionResult failure(String observation) { return new ActionResult(false, observation, null); } }
Flight.java
package com.sample.app.model; /** * Immutable representation of a flight option returned by the Flight Search tool. * * <p>Flight data is mocked; no real flight API is called. * * @param id Unique flight identifier (e.g., "BA-101") * @param airline Airline name (e.g., "British Airways") * @param from Departure airport code (e.g., "JFK") * @param to Arrival airport code (e.g., "LHR") * @param date Departure date as a human-readable string (e.g., "2025-07-28") * @param price Ticket price in USD */ public record Flight(String id, String airline, String from, String to, String date, double price) { /** * Returns a compact display string suitable for console output. * * @return formatted flight description */ public String display() { return String.format("[%s] %s | %s → %s | %s | $%.2f", id, airline, from, to, date, price); } }
Goal.java
package com.sample.app.model; /** * Represents the user's travel goal as understood by the Perception Module. * * <p>A Goal is immutable and carries the original user request after it has been parsed and * normalized by the Perception Module. It is passed into the Planning Module at the start of every * ReAct cycle. * * @param description A concise, normalized description of what the user wants to achieve. */ public record Goal(String description) { /** * Constructs a Goal, validating that the description is not blank. * * @param description the normalized goal description * @throws IllegalArgumentException if description is null or blank */ public Goal { if (description == null || description.isBlank()) { throw new IllegalArgumentException("Goal description must not be blank"); } } public String toString() { return description; } }
Hotel.java
package com.sample.app.model; /** * Immutable representation of a hotel option returned by the Hotel Search tool. * * <p>Hotel data is mocked; no real hotel API is called. * * @param id Unique hotel identifier (e.g., "H-001") * @param name Hotel name (e.g., "The Savoy") * @param location City and area description (e.g., "London, Strand") * @param stars Star rating (1–5) * @param pricePerNight Nightly rate in USD */ public record Hotel(String id, String name, String location, int stars, double pricePerNight) { /** * Returns a compact display string suitable for console output. * * @return formatted hotel description */ public String display() { return String.format( "[%s] %s | %s | %d★ | $%.2f/night", id, name, location, stars, pricePerNight); } }
PlanResponse.java
package com.sample.app.model; /** * The structured response produced by the Planning Module after each LLM call. * * <p>This is the Java representation of the JSON that the LLM must return on every planning cycle. * The expected JSON shape is: * * <pre>{@code * { * "status": "IN_PROGRESS", * "nextStep": { * "toolName": "searchFlights", * "parameters": { "destination": "London" }, * "reasoning": "Need to find available flights first." * } * } * }</pre> * * <p>When the goal is complete the LLM returns {@code "status": "COMPLETED"} and {@code "nextStep": * null}. * * @param status The planning status. One of: {@code IN_PROGRESS}, {@code COMPLETED}, {@code * FAILED}. * @param nextStep The single next action to execute. {@code null} when status is COMPLETED or * FAILED. */ public record PlanResponse(String status, PlanStep nextStep) { /** Convenience constant for the completed status value. */ public static final String STATUS_COMPLETED = "COMPLETED"; /** Convenience constant for the in-progress status value. */ public static final String STATUS_IN_PROGRESS = "IN_PROGRESS"; /** Convenience constant for the failed status value. */ public static final String STATUS_FAILED = "FAILED"; /** * Returns {@code true} if the agent has signalled that the goal is fully complete. * * @return true when status equals COMPLETED */ public boolean isCompleted() { return STATUS_COMPLETED.equalsIgnoreCase(status); } /** * Returns {@code true} if the agent has signalled an unrecoverable failure. * * @return true when status equals FAILED */ public boolean isFailed() { return STATUS_FAILED.equalsIgnoreCase(status); } }
PlanStep.java
package com.sample.app.model; import java.util.Map; /** * Represents a single step generated by the Planning Module for the Action Module to execute. * * <p>A PlanStep is a structured instruction that names one tool and provides the parameters * required to invoke it. The Planning Module generates exactly one PlanStep per cycle (ReAct / * dynamic planning); it never generates an entire workflow at once. * * @param toolName The exact tool name as registered in the ToolRegistry (e.g., "searchFlights"). * Must match a registered key exactly. * @param parameters A map of string key-value pairs passed to the tool at execution time. Keys are * tool-specific (e.g., "destination", "flightId"). * @param reasoning A brief explanation from the LLM describing why this step was chosen. Used for * console output and debugging; never affects execution. */ public record PlanStep(String toolName, Map<String, String> parameters, String reasoning) { /** * Constructs a PlanStep with defensive copies of parameters. * * @param toolName name of the tool to invoke * @param parameters tool-specific parameters * @param reasoning LLM explanation for choosing this step */ public PlanStep { if (toolName == null || toolName.isBlank()) { throw new IllegalArgumentException("PlanStep toolName must not be blank"); } // Defensive immutable copy parameters = parameters != null ? Map.copyOf(parameters) : Map.of(); reasoning = reasoning != null ? reasoning : ""; } }
Step 3: Create package 'com.sample.app.memory' and define AgentMemory class.
AgentMemory.java
package com.sample.app.memory; import com.sample.app.model.Flight; import com.sample.app.model.Goal; import com.sample.app.model.Hotel; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Maintains the complete mutable state of the Travel Agent across all ReAct cycles. * * <p>AgentMemory is the single source of truth for what the agent knows at any point in time. It is * read by the Planning Module to build context-rich prompts, and written by the Orchestrator after * each action result is observed. * * <p>Key state tracked: * * <ul> * <li>The current user {@link Goal} * <li>A chronological list of observations (tool results in natural language) * <li>Available flights and hotels discovered via search tools * <li>The user-selected {@link Flight} and {@link Hotel} * <li>Booking confirmation flags * <li>Whether the confirmation email was sent * </ul> */ public class AgentMemory { private Goal goal; private final List<String> observations = new ArrayList<>(); private List<Flight> availableFlights = new ArrayList<>(); private List<Hotel> availableHotels = new ArrayList<>(); private Flight selectedFlight; private Hotel selectedHotel; private boolean flightBooked; private boolean hotelBooked; private boolean emailSent; private boolean tourPlansSuggested; /** * Returns the current travel goal. * * @return the goal, or {@code null} if not yet set */ public Goal getGoal() { return goal; } /** * Sets the travel goal. Called once by the Perception Module. * * @param goal the interpreted user goal */ public void setGoal(Goal goal) { this.goal = goal; } /** * Appends a new observation to the memory. * * <p>Observations are produced by tools and written here by the Orchestrator. They are fed back * into every planning prompt so the LLM always has full context. * * @param observation a short natural-language summary of what happened */ public void addObservation(String observation) { observations.add(observation); } /** * Returns an unmodifiable view of all recorded observations, in chronological order. * * @return list of observations */ public List<String> getObservations() { return Collections.unmodifiableList(observations); } /** * Stores the list of flights returned by the Flight Search tool. * * @param flights available flights */ public void setAvailableFlights(List<Flight> flights) { this.availableFlights = new ArrayList<>(flights); } /** * Returns the flights discovered by the most recent flight search. * * @return available flights (may be empty) */ public List<Flight> getAvailableFlights() { return Collections.unmodifiableList(availableFlights); } /** * Stores the list of hotels returned by the Hotel Search tool. * * @param hotels available hotels */ public void setAvailableHotels(List<Hotel> hotels) { this.availableHotels = new ArrayList<>(hotels); } /** * Returns the hotels discovered by the most recent hotel search. * * @return available hotels (may be empty) */ public List<Hotel> getAvailableHotels() { return Collections.unmodifiableList(availableHotels); } /** * Records the flight chosen by the user. * * @param flight the user-selected flight */ public void setSelectedFlight(Flight flight) { this.selectedFlight = flight; } /** * Returns the flight the user has chosen, or {@code null} if not yet selected. * * @return selected flight */ public Flight getSelectedFlight() { return selectedFlight; } /** * Records the hotel chosen by the user. * * @param hotel the user-selected hotel */ public void setSelectedHotel(Hotel hotel) { this.selectedHotel = hotel; } /** * Returns the hotel the user has chosen, or {@code null} if not yet selected. * * @return selected hotel */ public Hotel getSelectedHotel() { return selectedHotel; } /** * Marks the selected flight as successfully booked. * * @param booked {@code true} once booking is confirmed */ public void setFlightBooked(boolean booked) { this.flightBooked = booked; } /** * Returns whether the flight has been booked. * * @return {@code true} if the flight booking is confirmed */ public boolean isFlightBooked() { return flightBooked; } /** * Marks the selected hotel as successfully booked. * * @param booked {@code true} once booking is confirmed */ public void setHotelBooked(boolean booked) { this.hotelBooked = booked; } /** * Returns whether the hotel has been booked. * * @return {@code true} if the hotel booking is confirmed */ public boolean isHotelBooked() { return hotelBooked; } /** * Marks the confirmation email as sent. * * @param sent {@code true} once the email has been dispatched */ public void setEmailSent(boolean sent) { this.emailSent = sent; } /** * Returns whether the confirmation email has been sent. * * @return {@code true} if the email was sent */ public boolean isEmailSent() { return emailSent; } /** * Marks tour plans as suggested to the user. * * @param suggested {@code true} once plans have been presented */ public void setTourPlansSuggested(boolean suggested) { this.tourPlansSuggested = suggested; } /** * Returns whether tour plans have been suggested to the user. * * @return {@code true} if plans were already suggested */ public boolean isTourPlansSuggested() { return tourPlansSuggested; } /** * Returns {@code true} when the full booking workflow is complete: flight booked, hotel booked, * and confirmation email sent. * * <p>The Orchestrator uses this for a deterministic exit check so the agent loop does not depend * solely on the LLM signalling COMPLETED. * * @return true if all booking tasks are done */ public boolean isBookingWorkflowComplete() { return flightBooked && hotelBooked && emailSent; } /** * Produces a compact state summary for use inside the LLM planning prompt. * * <p>This string is injected into every planning prompt so the LLM knows exactly what has already * been accomplished without re-reading the full observation history. * * @return multiline status summary */ public String getStateSummary() { StringBuilder sb = new StringBuilder(); sb.append("Flights searched : ") .append(availableFlights.isEmpty() ? "NO" : "YES (" + availableFlights.size() + " found)") .append("\n"); sb.append("Flight selected : ") .append(selectedFlight != null ? selectedFlight.display() : "NO") .append("\n"); sb.append("Flight booked : ").append(flightBooked ? "YES" : "NO").append("\n"); sb.append("Hotels searched : ") .append(availableHotels.isEmpty() ? "NO" : "YES (" + availableHotels.size() + " found)") .append("\n"); sb.append("Hotel selected : ") .append(selectedHotel != null ? selectedHotel.display() : "NO") .append("\n"); sb.append("Hotel booked : ").append(hotelBooked ? "YES" : "NO").append("\n"); sb.append("Confirmation email : ").append(emailSent ? "SENT" : "NOT SENT").append("\n"); sb.append("Tour plans suggested: ").append(tourPlansSuggested ? "YES" : "NO").append("\n"); return sb.toString(); } }
Step 4: Create com.sample.app.tools package and define all the tools here.
Tool.java
package com.sample.app.tools; import java.util.Map; import com.sample.app.memory.AgentMemory; import com.sample.app.model.ActionResult; /** * Contract for every executable tool in the Travel Agent. * * <p>Each implementation represents one discrete capability (e.g., flight search, hotel booking). * Tools are registered in the {@link ToolRegistry} and invoked by the {@link * com.travelagent.action.ActionModule}. * * <p>Tools are the only components permitted to produce side effects (user I/O, mock bookings). * They may read from and write to {@link AgentMemory} as needed. */ public interface Tool { /** * Returns the unique tool name used to identify and invoke this tool. * * <p>This name MUST match exactly the {@code toolName} value the LLM places in its JSON plan * response. Mismatches cause an "unknown tool" error at runtime. * * @return unique tool identifier (e.g., {@code "searchFlights"}) */ String getName(); /** * Returns a concise English description of what this tool does. * * <p>Descriptions are injected into the planning prompt so the LLM can choose the correct tool * for each step. * * @return tool description (one sentence) */ String getDescription(); /** * Returns the parameter schema as a human-readable string for the planning prompt. * * <p>Example: {@code "destination (string), departureDate (string)"} * * @return parameter descriptions */ String getParameterDescription(); /** * Executes the tool with the given parameters and current agent memory. * * @param params parameters extracted from the LLM's plan step * @param memory current agent state; may be read or mutated * @return the result of execution, including an observation string */ ActionResult execute(Map<String, String> params, AgentMemory memory); }
AskUserTool.java
package com.sample.app.tools; import java.util.List; import java.util.Map; import java.util.Scanner; import com.sample.app.memory.AgentMemory; import com.sample.app.model.ActionResult; import com.sample.app.model.Flight; import com.sample.app.model.Hotel; /** * Tool that pauses the agent loop and asks the human user a question. * * <p>This tool is used when the agent needs human input to proceed — for example, to let the user * choose a flight or hotel from the discovered options. It reads from standard input and writes the * selected item back to {@link AgentMemory}. * * <p>The {@code questionType} parameter tells this tool what kind of choice to present: * * <ul> * <li>{@code "flight"} — presents available flights and records the selection * <li>{@code "hotel"} — presents available hotels and records the selection * </ul> */ public class AskUserTool implements Tool { private final Scanner scanner; /** * Constructs an AskUserTool with the given Scanner for reading user input. * * @param scanner the Scanner connected to System.in */ public AskUserTool(Scanner scanner) { this.scanner = scanner; } public String getName() { return "askUser"; } public String getDescription() { return "Asks the human user to make a selection (choose a flight or hotel) and records their choice."; } public String getParameterDescription() { return "questionType (string) - either 'flight' to let user pick a flight, or 'hotel' to let user pick a hotel"; } /** * Presents options to the user and records their selection in memory. * * @param params must contain {@code questionType} = "flight" or "hotel" * @param memory agent memory; selected flight or hotel will be written here * @return successful ActionResult describing the user's choice */ public ActionResult execute(Map<String, String> params, AgentMemory memory) { String questionType = params.getOrDefault("questionType", "flight"); if ("flight".equalsIgnoreCase(questionType)) { return askForFlight(memory); } else if ("hotel".equalsIgnoreCase(questionType)) { return askForHotel(memory); } else { return ActionResult.failure( "Unknown questionType: '" + questionType + "'. Use 'flight' or 'hotel'."); } } /** * Displays available flights, reads one line of user input, and returns either a success (valid * ID) or failure (invalid ID) so the ReAct loop can let the LLM decide whether to call this tool * again. * * @param memory agent memory with available flights * @return success if the user entered a valid flight ID, failure otherwise */ private ActionResult askForFlight(AgentMemory memory) { List<Flight> flights = memory.getAvailableFlights(); if (flights.isEmpty()) { return ActionResult.failure("No flights available to choose from. Run searchFlights first."); } List<String> validIds = flights.stream().map(Flight::id).toList(); System.out.println(); System.out.println(" ┌─────────────────────────────────────────┐"); System.out.println(" │ Please choose your flight: │"); System.out.println(" └─────────────────────────────────────────┘"); for (Flight f : flights) { System.out.println(" " + f.display()); } System.out.print("\n Enter flight ID " + validIds + ": "); String input = scanner.nextLine().trim(); Flight selected = flights.stream().filter(f -> f.id().equalsIgnoreCase(input)).findFirst().orElse(null); if (selected == null) { return ActionResult.failure( "User entered '" + input + "' which is not a valid flight ID. " + "Valid options are: " + validIds + ". Please ask the user to choose again."); } memory.setSelectedFlight(selected); return ActionResult.success("User selected flight: " + selected.display(), selected); } /** * Displays available hotels, reads one line of user input, and returns either a success (valid * ID) or failure (invalid ID) so the ReAct loop can let the LLM decide whether to call this tool * again. * * @param memory agent memory with available hotels * @return success if the user entered a valid hotel ID, failure otherwise */ private ActionResult askForHotel(AgentMemory memory) { List<Hotel> hotels = memory.getAvailableHotels(); if (hotels.isEmpty()) { return ActionResult.failure("No hotels available to choose from. Run searchHotels first."); } List<String> validIds = hotels.stream().map(Hotel::id).toList(); System.out.println(); System.out.println(" ┌─────────────────────────────────────────┐"); System.out.println(" │ Please choose your hotel: │"); System.out.println(" └─────────────────────────────────────────┘"); for (Hotel h : hotels) { System.out.println(" " + h.display()); } System.out.print("\n Enter hotel ID " + validIds + ": "); String input = scanner.nextLine().trim(); Hotel selected = hotels.stream().filter(h -> h.id().equalsIgnoreCase(input)).findFirst().orElse(null); if (selected == null) { return ActionResult.failure( "User entered '" + input + "' which is not a valid hotel ID. " + "Valid options are: " + validIds + ". Please ask the user to choose again."); } memory.setSelectedHotel(selected); return ActionResult.success("User selected hotel: " + selected.display(), selected); } }
EmailTool.java
package com.sample.app.tools; import java.util.Map; import com.sample.app.memory.AgentMemory; import com.sample.app.model.ActionResult; import com.sample.app.model.Flight; import com.sample.app.model.Hotel; /** * Mock tool that sends a booking confirmation email to the user. * * <p>In production this would call an email API (SendGrid, AWS SES, etc.). In this educational demo * it simply prints the email content to the console and marks the email as sent in {@link * AgentMemory}. */ public class EmailTool implements Tool { public String getName() { return "sendEmail"; } public String getDescription() { return "Sends a booking confirmation email summarizing the booked flight and hotel."; } public String getParameterDescription() { return "(no parameters required - reads booking details from memory)"; } /** * Prints a mock confirmation email and marks it as sent in memory. * * @param params not required; booking details come from memory * @param memory must contain booked flight and hotel information * @return successful ActionResult confirming the email was sent */ public ActionResult execute(Map<String, String> params, AgentMemory memory) { Flight flight = memory.getSelectedFlight(); Hotel hotel = memory.getSelectedHotel(); System.out.println(); System.out.println(" ╔══════════════════════════════════════════════════╗"); System.out.println(" ║ 📧 EMAIL SENT ║"); System.out.println(" ╠══════════════════════════════════════════════════╣"); System.out.println(" ║ To : traveller@example.com ║"); System.out.println(" ║ Subject : Your Trip to London — Confirmed! ║"); System.out.println(" ╠══════════════════════════════════════════════════╣"); System.out.println(" ║ Dear Traveller, ║"); System.out.println(" ║ ║"); System.out.println(" ║ Your trip has been confirmed: ║"); if (flight != null) { System.out.printf(" ║ ✈ Flight : %-38s║%n", flight.display()); } if (hotel != null) { System.out.printf(" ║ 🏨 Hotel : %-38s║%n", hotel.display()); } System.out.println(" ║ ║"); System.out.println(" ║ Have a great trip! ║"); System.out.println(" ║ — Travel Agent AI ║"); System.out.println(" ╚══════════════════════════════════════════════════╝"); System.out.println(); memory.setEmailSent(true); return ActionResult.success( "Confirmation email sent to traveller@example.com with full booking details."); } }
FlightBookTool.java
package com.sample.app.tools; import java.util.Map; import com.sample.app.memory.AgentMemory; import com.sample.app.model.ActionResult; import com.sample.app.model.Flight; /** * Mock tool that books the user-selected flight. * * <p>Requires that a flight has already been selected and stored in {@link AgentMemory}. In * production this would call an airline booking API. Here it simply marks the flight as booked in * memory and returns a confirmation observation. */ public class FlightBookTool implements Tool { public String getName() { return "bookFlight"; } public String getDescription() { return "Books the flight that was previously selected by the user. No parameters needed."; } public String getParameterDescription() { return "(no parameters required - books the currently selected flight from memory)"; } /** * Books the currently selected flight from memory. * * @param params not required for this tool * @param memory must contain a selected flight ({@link AgentMemory#getSelectedFlight()}) * @return successful ActionResult with booking confirmation, or failure if no flight selected */ public ActionResult execute(Map<String, String> params, AgentMemory memory) { Flight flight = memory.getSelectedFlight(); if (flight == null) { return ActionResult.failure( "Cannot book flight: no flight has been selected yet. Ask the user to choose one first."); } memory.setFlightBooked(true); String observation = String.format( "Flight booked successfully! Booking reference: CONF-%s. %s", flight.id(), flight.display()); return ActionResult.success(observation); } }
FlightSearchTool.java
package com.sample.app.tools; import java.util.List; import java.util.Map; import com.sample.app.memory.AgentMemory; import com.sample.app.model.ActionResult; import com.sample.app.model.Flight; /** * Mock tool that returns a hardcoded list of available flights. * * <p>In a production agent this would call a real flight search API (Skyscanner, Amadeus, etc.). * For this educational demo all flights are hardcoded. The tool writes the results into {@link * AgentMemory} so the Planner can reference them on subsequent cycles. */ public class FlightSearchTool implements Tool { private static final List<Flight> MOCK_FLIGHTS = List.of( new Flight("BA-101", "British Airways", "JFK", "LHR", "2025-07-28", 650.00), new Flight("VS-202", "Virgin Atlantic", "JFK", "LHR", "2025-07-28", 580.00), new Flight("AA-303", "American Airlines", "JFK", "LHR", "2025-07-29", 510.00)); public String getName() { return "searchFlights"; } public String getDescription() { return "Searches for available flights to the given destination and returns a list of options."; } public String getParameterDescription() { return "destination (string) - the travel destination city name"; } /** * Returns 3 mock flights and stores them in memory. * * @param params must contain key {@code destination} * @param memory agent memory; available flights list will be updated * @return successful ActionResult with observation describing the results */ public ActionResult execute(Map<String, String> params, AgentMemory memory) { String destination = params.getOrDefault("destination", "unknown"); memory.setAvailableFlights(MOCK_FLIGHTS); StringBuilder obs = new StringBuilder(); obs.append("Found ") .append(MOCK_FLIGHTS.size()) .append(" flights to ") .append(destination) .append(":\n"); for (Flight f : MOCK_FLIGHTS) { obs.append(" ").append(f.display()).append("\n"); } return ActionResult.success(obs.toString().trim(), MOCK_FLIGHTS); } }
HotelBookTool.java
package com.sample.app.tools; import java.util.Map; import com.sample.app.memory.AgentMemory; import com.sample.app.model.ActionResult; import com.sample.app.model.Hotel; /** * Mock tool that books the user-selected hotel. * * <p>Requires that a hotel has already been selected and stored in {@link AgentMemory}. In * production this would call a hotel booking API. Here it simply marks the hotel as booked in * memory and returns a confirmation observation. */ public class HotelBookTool implements Tool { public String getName() { return "bookHotel"; } public String getDescription() { return "Books the hotel that was previously selected by the user. No parameters needed."; } public String getParameterDescription() { return "(no parameters required - books the currently selected hotel from memory)"; } /** * Books the currently selected hotel from memory. * * @param params not required for this tool * @param memory must contain a selected hotel ({@link AgentMemory#getSelectedHotel()}) * @return successful ActionResult with booking confirmation, or failure if no hotel selected */ public ActionResult execute(Map<String, String> params, AgentMemory memory) { Hotel hotel = memory.getSelectedHotel(); if (hotel == null) { return ActionResult.failure( "Cannot book hotel: no hotel has been selected yet. Ask the user to choose one first."); } memory.setHotelBooked(true); String observation = String.format( "Hotel booked successfully! Booking reference: HTL-%s. %s", hotel.id(), hotel.display()); return ActionResult.success(observation); } }
HotelSearchTool.java
package com.sample.app.tools; import java.util.List; import java.util.Map; import com.sample.app.memory.AgentMemory; import com.sample.app.model.ActionResult; import com.sample.app.model.Hotel; /** * Mock tool that returns a hardcoded list of available hotels. * * <p>In a production agent this would call a real hotel search API (Booking.com, Hotels.com, etc.). * For this educational demo all hotels are hardcoded. The tool writes results into {@link * AgentMemory} so the Planner can reference them on subsequent cycles. */ public class HotelSearchTool implements Tool { private static final List<Hotel> MOCK_HOTELS = List.of( new Hotel("H-001", "The Savoy", "London, Strand", 5, 450.00), new Hotel("H-002", "Premier Inn Waterloo", "London, Waterloo", 3, 120.00), new Hotel("H-003", "The Hoxton Shoreditch", "London, Shoreditch", 4, 210.00)); public String getName() { return "searchHotels"; } public String getDescription() { return "Searches for available hotels at the destination and returns a list of options."; } public String getParameterDescription() { return "destination (string) - the city to search hotels in"; } /** * Returns 3 mock hotels and stores them in memory. * * @param params should contain key {@code destination} * @param memory agent memory; available hotels list will be updated * @return successful ActionResult with observation describing the results */ public ActionResult execute(Map<String, String> params, AgentMemory memory) { String destination = params.getOrDefault("destination", "unknown"); memory.setAvailableHotels(MOCK_HOTELS); StringBuilder obs = new StringBuilder(); obs.append("Found ") .append(MOCK_HOTELS.size()) .append(" hotels in ") .append(destination) .append(":\n"); for (Hotel h : MOCK_HOTELS) { obs.append(" ").append(h.display()).append("\n"); } return ActionResult.success(obs.toString().trim(), MOCK_HOTELS); } }
SuggestTourPlansTool.java
package com.sample.app.tools; import java.util.LinkedHashMap; import java.util.Map; import com.sample.app.memory.AgentMemory; import com.sample.app.model.ActionResult; /** * Tool that suggests curated tour plans for popular travel destinations. * * <p>Used when the user's goal is to explore travel options or get itinerary ideas rather than * immediately booking a trip. Returns a set of hardcoded tour plans and marks them as suggested in * {@link AgentMemory} so the Planner knows the goal has been fulfilled. * * <p>In production this would call a travel recommendations API or query a knowledge base. For this * demo all plans are hardcoded. */ public class SuggestTourPlansTool implements Tool { private static final Map<String, String[]> TOUR_PLANS = new LinkedHashMap<>(); static { TOUR_PLANS.put( "London Explorer (5 Days)", new String[] { "Day 1 : Arrive, check in, evening walk along the Thames", "Day 2 : Tower of London + Tower Bridge + Borough Market", "Day 3 : British Museum + Covent Garden + West End show", "Day 4 : Kensington Palace + Hyde Park + Notting Hill", "Day 5 : Greenwich Observatory + Cutty Sark, depart" }); TOUR_PLANS.put( "Paris Getaway (4 Days)", new String[] { "Day 1 : Arrive, Eiffel Tower at sunset, Seine river cruise", "Day 2 : Louvre Museum + Tuileries Garden + Champs-Élysées", "Day 3 : Montmartre + Sacré-Cœur + local bistro dinner", "Day 4 : Palace of Versailles day trip, depart evening" }); TOUR_PLANS.put( "Tokyo Adventure (7 Days)", new String[] { "Day 1 : Arrive, Shinjuku exploration", "Day 2 : Senso-ji Temple + Akihabara electronics district", "Day 3 : Tsukiji market + teamLab digital art museum", "Day 4 : Day trip to Nikko (UNESCO shrines)", "Day 5 : Harajuku + Shibuya crossing + Meiji Shrine", "Day 6 : Mt. Fuji day trip from Tokyo", "Day 7 : Ginza shopping, farewell dinner, depart" }); } public String getName() { return "suggestTourPlans"; } public String getDescription() { return "Suggests curated multi-day tour plans for popular travel destinations. " + "Use this when the user wants trip ideas or itineraries rather than booking a specific trip."; } public String getParameterDescription() { return "(no parameters required — returns curated plans for multiple destinations)"; } /** * Prints curated tour plans to the console and records them in memory. * * @param params not required * @param memory agent memory; tourPlansSuggested flag will be set to true * @return successful ActionResult with all suggested plans */ public ActionResult execute(Map<String, String> x, AgentMemory memory) { StringBuilder display = new StringBuilder(); System.out.println(); System.out.println(" ╔══════════════════════════════════════════════════════════╗"); System.out.println(" ║ ✈ SUGGESTED TOUR PLANS ✈ ║"); System.out.println(" ╚══════════════════════════════════════════════════════════╝"); for (Map.Entry<String, String[]> entry : TOUR_PLANS.entrySet()) { System.out.println(); System.out.println(" 📍 " + entry.getKey()); System.out.println(" " + "─".repeat(55)); for (String day : entry.getValue()) { System.out.println(" • " + day); } display.append(entry.getKey()).append(": ").append(entry.getValue().length).append(" days. "); } System.out.println(); memory.setTourPlansSuggested(true); return ActionResult.success( "Suggested " + TOUR_PLANS.size() + " tour plans: " + display.toString().trim() + " User can now choose one to book, or the goal is complete if they only wanted suggestions."); } }
ToolRegistry.java
package com.sample.app.tools; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; /** * Registry that holds all available tools, keyed by their unique name. * * <p>The ToolRegistry is the single source of truth for what tools exist. It is consulted by the * {@link com.travelagent.action.ActionModule} to dispatch plan steps, and by the {@link * com.travelagent.llm.PromptBuilder} to generate the tools section of the planning prompt. * * <p>Tool names in the registry MUST exactly match the names the LLM places in its JSON responses. * Any drift between registry key and LLM output causes a dispatch failure at runtime. */ public class ToolRegistry { private final Map<String, Tool> tools; /** * Constructs a ToolRegistry pre-populated with all travel agent tools. * * @param scanner the Scanner used by {@link AskUserTool} for reading user input */ public ToolRegistry(java.util.Scanner scanner) { Map<String, Tool> map = new LinkedHashMap<>(); register(map, new SuggestTourPlansTool()); register(map, new FlightSearchTool()); register(map, new FlightBookTool()); register(map, new HotelSearchTool()); register(map, new HotelBookTool()); register(map, new AskUserTool(scanner)); register(map, new EmailTool()); this.tools = Collections.unmodifiableMap(map); } /** * Looks up a tool by its registered name. * * @param name the tool name (must be an exact, case-sensitive match) * @return an Optional containing the tool, or empty if not found */ public Optional<Tool> find(String name) { return Optional.ofNullable(tools.get(name)); } /** * Returns all registered tools, in registration order. * * @return unmodifiable collection of tools */ public Collection<Tool> all() { return tools.values(); } private void register(Map<String, Tool> map, Tool tool) { map.put(tool.getName(), tool); } }
Step 5: Create package 'com.sample.app.llm' and define LLM related classes.
LlmClient.java
package com.sample.app.llm; import java.time.Duration; import dev.langchain4j.model.chat.ChatLanguageModel; import dev.langchain4j.model.ollama.OllamaChatModel; /** * Thin wrapper around the LangChain4j {@link ChatLanguageModel} for Ollama. * * <p>This class is the only component that communicates directly with the LLM. * It intentionally exposes a minimal surface: one method that accepts a prompt * string and returns the raw text response. All prompt construction and response * parsing happen in separate classes ({@link PromptBuilder} and {@link PlanParser}). * * <p><strong>Design note:</strong> We use {@code ChatLanguageModel.generate(String)} * directly rather than LangChain4j's {@code AiServices} DSL. This makes the * prompt-build → LLM-call → parse pipeline explicit and visible — which is the * educational point of this project. */ public class LlmClient { /** Default Ollama server URL. */ private static final String DEFAULT_BASE_URL = "http://localhost:11434"; /** Default model to use. Must be pulled in Ollama before running. */ private static final String DEFAULT_MODEL = "llama3.2"; private final ChatLanguageModel chatModel; /** * Constructs an LlmClient connecting to the default local Ollama instance. * Uses model {@value #DEFAULT_MODEL}. */ public LlmClient() { this(DEFAULT_BASE_URL, DEFAULT_MODEL); } /** * Constructs an LlmClient with a custom base URL and model name. * * @param baseUrl Ollama server base URL (e.g., {@code "http://localhost:11434"}) * @param modelName Ollama model name (e.g., {@code "llama3.2"}) */ public LlmClient(String baseUrl, String modelName) { this.chatModel = OllamaChatModel.builder() .baseUrl(baseUrl) .modelName(modelName) .temperature(0.1) // Low temperature = more deterministic JSON output .timeout(Duration.ofSeconds(120)) .build(); } /** * Sends a raw prompt to the LLM and returns the raw text response. * * <p>The caller is responsible for building the prompt ({@link PromptBuilder}) * and parsing the response ({@link PlanParser}). This method performs no * transformation on either input or output. * * @param prompt the full prompt to send to the model * @return the model's raw text response */ public String generate(String prompt) { return chatModel.chat(prompt); } }
PlanParser.java
package com.sample.app.llm; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.sample.app.model.PlanResponse; import com.sample.app.model.PlanStep; /** * Parses the raw LLM text response into a structured {@link PlanResponse}. * * <p>Local LLMs (e.g., Llama 3.2 via Ollama) often wrap JSON in markdown code fences * or prefix it with conversational text, even when instructed not to. This parser * handles those cases defensively before deserializing the JSON. * * <p>Parsing strategy: * <ol> * <li>Strip markdown code fences (```json ... ``` or ``` ... ```)</li> * <li>Extract the first complete JSON object ({@code { ... }}) from the text</li> * <li>Use Jackson's {@link JsonNode} API to extract fields explicitly</li> * <li>Return a fallback {@link PlanResponse} if parsing fails entirely</li> * </ol> * * <p>Using {@link JsonNode} (rather than direct POJO mapping) keeps the parsing * visible and step-by-step — consistent with the educational goal of this project. */ public class PlanParser { private final ObjectMapper objectMapper = new ObjectMapper(); /** * Parses a raw LLM response string into a {@link PlanResponse}. * * <p>If parsing fails for any reason, returns a fallback response with * status {@code IN_PROGRESS} and no next step, which will cause the * orchestrator to surface the error rather than silently continuing. * * @param rawResponse the raw text returned by the LLM * @return the parsed PlanResponse, or a safe fallback if parsing fails */ public PlanResponse parse(String rawResponse) { try { String cleaned = extractJson(rawResponse); JsonNode root = objectMapper.readTree(cleaned); String status = readString(root, "status", PlanResponse.STATUS_IN_PROGRESS); JsonNode nextStepNode = root.get("nextStep"); if (nextStepNode == null || nextStepNode.isNull()) { return new PlanResponse(status, null); } String toolName = readString(nextStepNode, "toolName", ""); String reasoning = readString(nextStepNode, "reasoning", ""); Map<String, String> parameters = readStringMap(nextStepNode, "parameters"); PlanStep planStep = new PlanStep(toolName, parameters, reasoning); return new PlanResponse(status, planStep); } catch (Exception e) { // Return a safe fallback; the orchestrator will print the raw response for debugging return new PlanResponse( "PARSE_ERROR", new PlanStep("_parse_error_", Map.of("rawResponse", rawResponse), e.getMessage()) ); } } /** * Extracts the first complete JSON object from a string that may contain * surrounding prose or markdown code fences. * * @param raw the raw text that may contain JSON * @return the extracted JSON substring * @throws IllegalArgumentException if no JSON object is found */ private String extractJson(String raw) { if (raw == null || raw.isBlank()) { throw new IllegalArgumentException("LLM returned empty response"); } // Step 1: Strip markdown code fences String cleaned = raw.trim(); if (cleaned.startsWith("```")) { int firstNewline = cleaned.indexOf('\n'); if (firstNewline != -1) { cleaned = cleaned.substring(firstNewline + 1); } if (cleaned.endsWith("```")) { cleaned = cleaned.substring(0, cleaned.lastIndexOf("```")); } cleaned = cleaned.trim(); } // Step 2: Find the first '{' and matching '}' to extract a JSON object int start = cleaned.indexOf('{'); if (start == -1) { throw new IllegalArgumentException("No JSON object found in response: " + raw); } int depth = 0; int end = -1; for (int i = start; i < cleaned.length(); i++) { char c = cleaned.charAt(i); if (c == '{') depth++; else if (c == '}') { depth--; if (depth == 0) { end = i; break; } } } if (end == -1) { throw new IllegalArgumentException("Unterminated JSON object in response: " + raw); } return cleaned.substring(start, end + 1); } /** * Safely reads a string field from a JsonNode, returning a default if absent. * * @param node the JSON node to read from * @param fieldName the field name to look up * @param defaultValue value to return if field is absent or null * @return the field value as a String */ private String readString(JsonNode node, String fieldName, String defaultValue) { JsonNode field = node.get(fieldName); if (field == null || field.isNull()) { return defaultValue; } return field.asText(defaultValue); } /** * Reads a JSON object field as a {@code Map<String, String>}. * * @param node the parent JSON node * @param fieldName the field name of the nested object * @return a map of string key-value pairs (empty if field absent or not an object) */ private Map<String, String> readStringMap(JsonNode node, String fieldName) { Map<String, String> result = new HashMap<>(); JsonNode mapNode = node.get(fieldName); if (mapNode == null || !mapNode.isObject()) { return result; } Iterator<Map.Entry<String, JsonNode>> fields = mapNode.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> entry = fields.next(); result.put(entry.getKey(), entry.getValue().asText("")); } return result; } }
PromptBuilder.java
package com.sample.app.llm; import java.util.Collection; import java.util.List; import com.sample.app.memory.AgentMemory; import com.sample.app.tools.Tool; import com.sample.app.tools.ToolRegistry; /** * Builds the planning prompt that is sent to the LLM on every ReAct cycle. * * <p>The prompt is the mechanism by which the agent's current knowledge is * communicated to the LLM. It contains four sections: * <ol> * <li><strong>System Instructions</strong> — role, output format contract, constraints</li> * <li><strong>Available Tools</strong> — name, description, and parameters of every tool</li> * <li><strong>Current State</strong> — what has been booked, what has been observed</li> * <li><strong>Task</strong> — the goal and the question: "what is the ONE next step?"</li> * </ol> * * <p>This class contains no LLM interaction and no business logic — only prompt text assembly. */ public class PromptBuilder { private static final String SYSTEM_INSTRUCTIONS = """ You are a travel planning AI agent executing a ReAct (Reason + Act) loop. Your job is to read the user's GOAL, look at the CURRENT STATE, and decide the SINGLE NEXT ACTION. STRICT OUTPUT RULES: - Respond with valid JSON ONLY. No prose, no markdown fences, no explanation outside the JSON. - Choose exactly ONE tool whose name exactly matches a name in the AVAILABLE TOOLS list. - Use status "IN_PROGRESS" while more steps are needed. - Use status "COMPLETED" with nextStep null when the goal is fully satisfied. HOW TO REASON ABOUT THE GOAL: - If the goal is about SUGGESTING or EXPLORING trip ideas (e.g. "show me tours", "suggest plans", "give me ideas"): → Use suggestTourPlans. After it runs, set status=COMPLETED. - If the goal is about BOOKING a trip (e.g. "book my trip", "I want to fly to X"): → Follow the booking workflow below, in order. - If the goal is ambiguous, prefer suggestTourPlans first and ask the user. BOOKING WORKFLOW (only when goal is to book): Step 1 — searchFlights : find available flights Step 2 — askUser : questionType=flight (let user pick a flight) Step 3 — bookFlight : confirm the chosen flight Step 4 — searchHotels : find available hotels Step 5 — askUser : questionType=hotel (let user pick a hotel) Step 6 — bookHotel : confirm the chosen hotel Step 7 — sendEmail : send confirmation Step 8 — status=COMPLETED RECOVERY RULES: - If a tool returned a failure observation, analyse why and choose the corrective next step. - If askUser failed because of an invalid ID, call askUser again with the same questionType. - Never repeat a step that already succeeded (check CURRENT STATE before deciding). OUTPUT FORMAT: { "status": "IN_PROGRESS", "nextStep": { "toolName": "<exact tool name>", "parameters": { "<key>": "<value>" }, "reasoning": "<one sentence explaining why this step is next>" } } When goal is fully satisfied: { "status": "COMPLETED", "nextStep": null } """; /** * Builds the full planning prompt for the current ReAct cycle. * * @param memory current agent state (goal, observations, booking flags) * @param registry the tool registry used to enumerate available tools * @return the complete prompt string ready to send to the LLM */ public String build(AgentMemory memory, ToolRegistry registry) { StringBuilder prompt = new StringBuilder(); prompt.append("=== SYSTEM INSTRUCTIONS ===\n"); prompt.append(SYSTEM_INSTRUCTIONS); prompt.append("\n"); prompt.append("=== AVAILABLE TOOLS ===\n"); prompt.append(buildToolsSection(registry.all())); prompt.append("\n"); prompt.append("=== CURRENT STATE ===\n"); prompt.append("Goal: ").append(memory.getGoal()).append("\n\n"); prompt.append(memory.getStateSummary()).append("\n"); prompt.append("=== OBSERVATIONS (most recent last) ===\n"); List<String> observations = memory.getObservations(); if (observations.isEmpty()) { prompt.append("No observations yet.\n"); } else { for (int i = 0; i < observations.size(); i++) { prompt.append("[").append(i + 1).append("] ").append(observations.get(i)).append("\n"); } } prompt.append("\n"); prompt.append("=== TASK ===\n"); prompt.append("Based on the current state and observations above, what is the SINGLE NEXT STEP "); prompt.append("to complete the travel goal?\n\n"); prompt.append("Respond with JSON only. No other text.\n"); return prompt.toString(); } /** * Builds the tools section of the prompt, listing each tool with its description * and parameters so the LLM can choose the appropriate one. * * @param tools all registered tools * @return formatted tools section string */ private String buildToolsSection(Collection<Tool> tools) { StringBuilder sb = new StringBuilder(); for (Tool tool : tools) { sb.append("Tool: ").append(tool.getName()).append("\n"); sb.append(" Description : ").append(tool.getDescription()).append("\n"); sb.append(" Parameters : ").append(tool.getParameterDescription()).append("\n"); sb.append("\n"); } return sb.toString(); } }
Step 6: Create 'com.sample.app.util' package and define ConsoleRenderer to render the console messages.
ConsoleRenderer.java
package com.sample.app.util; import com.sample.app.memory.AgentMemory; import com.sample.app.model.ActionResult; import com.sample.app.model.PlanResponse; import com.sample.app.model.PlanStep; /** * Renders formatted ReAct cycle output to the console. * * <p>Every planning cycle is printed in a structured block that makes the * agent's reasoning process explicit and easy to follow. This is the component * that makes this demo "educational" — the reader can watch the agent think, * act, and observe in real time. * * <p>This class contains only presentation logic. It never modifies state, * calls tools, or interacts with the LLM. */ public class ConsoleRenderer { private static final String DIVIDER = "=".repeat(60); private static final String THIN = "-".repeat(60); /** * Prints the application banner on startup. */ public void printBanner() { System.out.println(); System.out.println(DIVIDER); System.out.println(" ✈ TRAVEL PLANNER AI AGENT ✈"); System.out.println(" ReAct Architecture Demo"); System.out.println(DIVIDER); System.out.println(); System.out.println(" Architecture: Perception → Plan → Act → Observe → Re-plan"); System.out.println(" LLM : Ollama (llama3.2)"); System.out.println(" Framework : LangChain4j (raw ChatModel — no AiServices)"); System.out.println(" Services : All mocked — no real APIs"); System.out.println(); System.out.println(DIVIDER); System.out.println(); } /** * Prints the header for a new ReAct cycle. * * @param cycle the cycle number (1-based) * @param memory the current agent memory for state display */ public void printCycleHeader(int cycle, AgentMemory memory) { System.out.println(); System.out.println(DIVIDER); System.out.printf(" Planning Cycle %-3d%n", cycle); System.out.println(DIVIDER); System.out.println(); System.out.println(" GOAL:"); System.out.println(" " + memory.getGoal()); System.out.println(); System.out.println(" CURRENT STATE:"); for (String line : memory.getStateSummary().split("\n")) { System.out.println(" " + line); } } /** * Prints the plan step chosen by the LLM. * * @param plan the plan response returned by the Planner */ public void printPlan(PlanResponse plan) { System.out.println(); System.out.println(" " + THIN); System.out.println(" GENERATED PLAN:"); if (plan.isCompleted()) { System.out.println(" ✅ Status : COMPLETED"); System.out.println(" All tasks are done. Goal achieved!"); return; } if (plan.isFailed() || plan.nextStep() == null) { System.out.println(" ❌ Status : " + plan.status()); return; } PlanStep step = plan.nextStep(); System.out.println(" Status : " + plan.status()); System.out.println(" Tool : " + step.toolName()); System.out.println(" Reasoning : " + step.reasoning()); if (!step.parameters().isEmpty()) { System.out.println(" Parameters:"); step.parameters().forEach((k, v) -> System.out.println(" " + k + " = " + v)); } } /** * Prints the execution phase label before a tool runs. * * @param toolName the name of the tool being executed */ public void printExecuting(String toolName) { System.out.println(); System.out.println(" " + THIN); System.out.println(" EXECUTING: " + toolName + "()"); System.out.println(" " + THIN); } /** * Prints the observation returned by a tool after execution. * * @param result the action result from the tool */ public void printObservation(ActionResult result) { System.out.println(); System.out.println(" OBSERVATION:"); String icon = result.success() ? " ✅" : " ❌"; for (String line : result.observation().split("\n")) { System.out.println(icon + " " + line); icon = " "; // indent continuation lines } } /** * Prints the completion message when the goal is fully achieved. */ public void printCompletion() { System.out.println(); System.out.println(DIVIDER); System.out.println(" 🎉 GOAL COMPLETE — Your trip has been fully booked!"); System.out.println(DIVIDER); System.out.println(); } /** * Prints a warning when the maximum cycle limit is reached. * * @param maxCycles the cycle limit that was hit */ public void printMaxCyclesReached(int maxCycles) { System.out.println(); System.out.println(DIVIDER); System.out.println(" ⚠ MAX CYCLES REACHED (" + maxCycles + ")"); System.out.println(" The agent did not complete the goal within the cycle limit."); System.out.println(" This may indicate a prompt engineering or LLM issue."); System.out.println(DIVIDER); System.out.println(); } /** * Prints an error message. * * @param message the error description */ public void printError(String message) { System.out.println(); System.out.println(" ❌ ERROR: " + message); } /** * Prints the LLM thinking indicator. */ public void printThinking() { System.out.println(); System.out.println(" 🤔 Asking LLM to plan next step..."); } }
Step 7: Create 'com.sample.app.perception' package and define PerceptionModule class.
PerceptionModule.java
package com.sample.app.perception; import com.sample.app.model.Goal; /** * Converts raw user input into a structured {@link Goal}. * * <p>The Perception Module is the agent's entry point for understanding what the user wants. * It sits between the raw console input and the Planning Module. * * <p>In a more sophisticated agent, this module would use an LLM to extract intents, * entities (destination, dates, budget), and constraints from free-form text. For this * educational demo it performs lightweight normalization only, keeping the module * boundary clear without over-engineering. * * <p><strong>Responsibilities:</strong> * <ul> * <li>Validate that input is non-empty</li> * <li>Normalize whitespace and casing</li> * <li>Wrap the result in a {@link Goal} record</li> * </ul> * * <p><strong>Not responsible for:</strong> * <ul> * <li>Planning — that is the Planning Module's job</li> * <li>Calling tools — that is the Action Module's job</li> * <li>Storing state — that is AgentMemory's job</li> * </ul> */ public class PerceptionModule { /** * Parses the raw user input string into a normalized {@link Goal}. * * @param rawInput the unprocessed string typed by the user at the console * @return a Goal representing the user's normalized travel intent * @throws IllegalArgumentException if the input is null or blank */ public Goal perceive(String rawInput) { if (rawInput == null || rawInput.isBlank()) { throw new IllegalArgumentException("User input must not be empty. Please describe your travel goal."); } String normalized = rawInput.trim(); // Ensure the goal ends with a period for clean prompt injection if (!normalized.endsWith(".") && !normalized.endsWith("!") && !normalized.endsWith("?")) { normalized = normalized + "."; } return new Goal(normalized); } }
Step 8: Create 'com.sample.app.planning' package and define Planner class.
Planner.java
package com.sample.app.planning; import com.sample.app.llm.LlmClient; import com.sample.app.llm.PlanParser; import com.sample.app.llm.PromptBuilder; import com.sample.app.memory.AgentMemory; import com.sample.app.model.PlanResponse; import com.sample.app.tools.ToolRegistry; /** * The Planning Module — responsible solely for reasoning about what to do next. * * <p>On every ReAct cycle, the Planner: * <ol> * <li>Reads the current state from {@link AgentMemory}</li> * <li>Builds a context-rich prompt via {@link PromptBuilder}</li> * <li>Sends the prompt to the LLM via {@link LlmClient}</li> * <li>Parses the raw JSON response via {@link PlanParser}</li> * <li>Returns a single {@link PlanResponse} containing ONE next step</li> * </ol> * * <p><strong>Critical constraints — the Planner NEVER:</strong> * <ul> * <li>Executes tools</li> * <li>Calls external APIs</li> * <li>Modifies memory</li> * <li>Generates a complete workflow</li> * </ul> * * <p>It only produces a structured plan for the Action Module to execute. * This separation is what makes the ReAct loop composable and testable. */ public class Planner { private final LlmClient llmClient; private final PromptBuilder promptBuilder; private final PlanParser planParser; private final ToolRegistry toolRegistry; /** * Constructs a Planner with all required collaborators. * * @param llmClient the client for communicating with the LLM * @param promptBuilder builds the planning prompt from memory state * @param planParser parses the LLM JSON response into a PlanResponse * @param toolRegistry provides tool metadata for the prompt's tools section */ public Planner(LlmClient llmClient, PromptBuilder promptBuilder, PlanParser planParser, ToolRegistry toolRegistry) { this.llmClient = llmClient; this.promptBuilder = promptBuilder; this.planParser = planParser; this.toolRegistry = toolRegistry; } /** * Generates the next plan step by querying the LLM with the current agent state. * * <p>This method represents a single "Think" phase in the ReAct loop. It returns * exactly one step to execute — never a full workflow. The Orchestrator calls this * method on every cycle after observing the previous step's result. * * @param memory current agent state including goal, observations, and booking flags * @return a PlanResponse with either the next step or a COMPLETED/FAILED signal */ public PlanResponse plan(AgentMemory memory) { String prompt = promptBuilder.build(memory, toolRegistry); String rawResponse = llmClient.generate(prompt); return planParser.parse(rawResponse); } }
Step 8: Create 'com.sample.app.action' package and define ActionModule.
ActionModule.java
package com.sample.app.action; import com.sample.app.memory.AgentMemory; import com.sample.app.model.ActionResult; import com.sample.app.model.PlanStep; import com.sample.app.tools.Tool; import com.sample.app.tools.ToolRegistry; import java.util.Optional; /** * The Action Module — responsible solely for executing a single plan step. * * <p> * The Action Module reads a {@link PlanStep} produced by the Planning Module, * looks up the corresponding {@link Tool} in the {@link ToolRegistry}, and * executes it. It returns an {@link ActionResult} containing the outcome and an * observation string that the Orchestrator will write into {@link AgentMemory}. * * <p> * <strong>Responsibilities:</strong> * * <ul> * <li>Resolve the tool name from the PlanStep to a concrete Tool instance * <li>Delegate execution to the Tool * <li>Return the ActionResult to the Orchestrator * </ul> * * <p> * <strong>Not responsible for:</strong> * * <ul> * <li>Planning — that is the Planner's job * <li>Storing observations — that is the Orchestrator + AgentMemory's job * <li>Knowing what to execute next — that is the Planner's job * </ul> */ public class ActionModule { private final ToolRegistry toolRegistry; /** * Constructs an ActionModule with the given tool registry. * * @param toolRegistry the registry of all available tools */ public ActionModule(ToolRegistry toolRegistry) { this.toolRegistry = toolRegistry; } /** * Executes the tool specified by the given plan step. * * <p> * If the tool name does not match any registered tool, a failure result is * returned immediately without throwing an exception. This allows the * Orchestrator to record the error as an observation and let the Planner * recover on the next cycle. * * @param step the plan step specifying which tool to run and with what * parameters * @param memory the current agent state; passed to the tool for reading and * writing * @return the result of tool execution, including an observation string */ public ActionResult execute(PlanStep step, AgentMemory memory) { Optional<Tool> toolOpt = toolRegistry.find(step.toolName()); if (toolOpt.isEmpty()) { return ActionResult.failure("Unknown tool: '" + step.toolName() + "'. " + "The LLM requested a tool that is not registered. " + "Registered tools: " + toolRegistry.all().stream().map(Tool::getName).reduce((a, b) -> a + ", " + b).orElse("(none)")); } Tool tool = toolOpt.get(); return tool.execute(step.parameters(), memory); } }
Step 9: Create 'com.sample.app.orchestrator' package and define AgentOrchestrator class.
AgentOrchestrator.java
package com.sample.app.orchestrator; import com.sample.app.action.ActionModule; import com.sample.app.memory.AgentMemory; import com.sample.app.model.ActionResult; import com.sample.app.model.Goal; import com.sample.app.model.PlanResponse; import com.sample.app.model.PlanStep; import com.sample.app.planning.Planner; import com.sample.app.util.ConsoleRenderer; /** * Coordinates the complete ReAct (Reason + Act) loop for the Travel Agent. * * <p>The Orchestrator is the top-level controller that repeatedly executes: * <pre> * Perceive Goal * ↓ * ┌─────────────────────────────┐ * │ 1. THINK → call Planner │ * │ 2. ACT → call Action │ ← repeats until COMPLETED or max cycles * │ 3. OBSERVE → update Memory │ * └─────────────────────────────┘ * ↓ * Goal Complete / Max Cycles * </pre> * * <p>The Orchestrator knows about every module but delegates all decisions: * <ul> * <li><strong>What to do next</strong> → {@link Planner}</li> * <li><strong>How to do it</strong> → {@link ActionModule} + Tools</li> * <li><strong>What happened</strong> → {@link AgentMemory}</li> * <li><strong>How to display it</strong> → {@link ConsoleRenderer}</li> * </ul> * * <p>A maximum cycle cap prevents infinite loops if the LLM fails to signal completion. */ public class AgentOrchestrator { /** Safety cap: prevents the agent from looping forever if the LLM misbehaves. */ private static final int MAX_CYCLES = 100; private final Planner planner; private final ActionModule actionModule; private final AgentMemory memory; private final ConsoleRenderer renderer; /** * Constructs an AgentOrchestrator with all required collaborators. * * @param planner the planning module for generating next steps * @param actionModule the action module for executing plan steps * @param memory the shared agent state * @param renderer the console renderer for formatted output */ public AgentOrchestrator(Planner planner, ActionModule actionModule, AgentMemory memory, ConsoleRenderer renderer) { this.planner = planner; this.actionModule = actionModule; this.memory = memory; this.renderer = renderer; } /** * Runs the full ReAct loop for the given goal until it is completed or the cycle cap is hit. * * <p>Each iteration of the loop represents one full Think-Act-Observe cycle: * <ol> * <li><strong>Think</strong>: The Planner queries the LLM with the current memory state * and receives a single next step as structured JSON.</li> * <li><strong>Act</strong>: The Action Module looks up and executes the tool named * in the plan step.</li> * <li><strong>Observe</strong>: The tool's result (observation) is written into memory * so the Planner has full context on the next cycle.</li> * </ol> * * @param goal the travel goal produced by the Perception Module */ public void run(Goal goal) { memory.setGoal(goal); for (int cycle = 1; cycle <= MAX_CYCLES; cycle++) { // ── Display cycle header ───────────────────────────────────────── renderer.printCycleHeader(cycle, memory); // ── THINK: ask the LLM for the next step ───────────────────────── renderer.printThinking(); PlanResponse plan = planner.plan(memory); renderer.printPlan(plan); // ── Check for terminal states ───────────────────────────────────── if (plan.isCompleted()) { renderer.printCompletion(); return; } if (plan.isFailed()) { renderer.printError("Planner signalled FAILED: " + plan.status()); return; } if (plan.nextStep() == null) { renderer.printError("Planner returned null nextStep without COMPLETED status. Aborting."); return; } // ── Handle parse errors returned as a special tool name ──────────── PlanStep step = plan.nextStep(); if ("_parse_error_".equals(step.toolName())) { renderer.printError("LLM response could not be parsed as JSON."); renderer.printError("Raw response: " + step.parameters().getOrDefault("rawResponse", "(empty)")); renderer.printError("Parse error : " + step.reasoning()); // Record in memory so LLM has context on the next cycle memory.addObservation("Parse error on previous cycle: LLM did not return valid JSON. Please return only JSON."); continue; } // ── ACT: execute the tool ───────────────────────────────────────── renderer.printExecuting(step.toolName()); ActionResult result = actionModule.execute(step, memory); // ── OBSERVE: record result in memory ────────────────────────────── renderer.printObservation(result); memory.addObservation( "Cycle " + cycle + " | Tool: " + step.toolName() + " | " + result.observation() ); // If the tool failed, give the LLM a chance to recover on the next cycle if (!result.success()) { memory.addObservation( "The previous tool failed. Consider whether the same tool should be retried " + "or a prerequisite step is missing." ); } // ── Deterministic exit: do not rely solely on LLM signalling COMPLETED ── // If the booking workflow is fully done, exit immediately. if (memory.isBookingWorkflowComplete()) { renderer.printCompletion(); return; } // If tour plans were suggested and that was the user's goal, exit. if (memory.isTourPlansSuggested() && !memory.isFlightBooked()) { renderer.printCompletion(); return; } } // Loop exhausted without COMPLETED signal renderer.printMaxCyclesReached(MAX_CYCLES); } }
Step 10: Define main application class.
App.java
package com.sample.app; import com.sample.app.action.ActionModule; import com.sample.app.llm.LlmClient; import com.sample.app.llm.PlanParser; import com.sample.app.llm.PromptBuilder; import com.sample.app.memory.AgentMemory; import com.sample.app.model.Goal; import com.sample.app.orchestrator.AgentOrchestrator; import com.sample.app.perception.PerceptionModule; import com.sample.app.planning.Planner; import com.sample.app.tools.ToolRegistry; import com.sample.app.util.ConsoleRenderer; import java.util.Scanner; /** * Entry point for the Travel Planner AI Agent demo. * * <p>This class is responsible for wiring all modules together and starting the agent. There is no * dependency injection framework — all collaborators are constructed and connected here by hand, * making the dependency graph explicit and readable. * * <p>The architecture demonstrated here is the ReAct (Reason + Act) loop: * * <pre> * * User Input (console) * │ * ▼ * PerceptionModule → Goal * │ * ▼ * AgentOrchestrator ─────────────────────────────────────────┐ * │ │ * ▼ │ loop * Planner ─→ LlmClient ─→ Ollama LLM │ * │ ↑ │ * │ PromptBuilder (reads AgentMemory) │ * │ ↓ │ * │ PlanParser (parses JSON response) │ * │ │ * ▼ │ * ActionModule ─→ ToolRegistry ─→ Tool.execute() │ * │ │ * ▼ │ * AgentMemory.addObservation() ─────────────────────────────┘ * </pre> * * <p><strong>Prerequisites:</strong> * * <ul> * <li>Ollama running locally on {@code http://localhost:11434} * <li>Model {@code llama3.2} pulled: {@code ollama pull llama3.2} * </ul> * * <p><strong>Run:</strong> * * <pre> * mvn package * java -jar target/travel-agent-demo-1.0.0-SNAPSHOT.jar * </pre> */ public class App { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); ConsoleRenderer renderer = new ConsoleRenderer(); renderer.printBanner(); // ── 1. Read the user's travel goal ─────────────────────────────────── System.out.print(" Enter your travel goal: "); String rawInput = scanner.nextLine(); System.out.println(); // ── 2. Wire all modules (no framework, no DI container) ────────────── // LLM layer LlmClient llmClient = new LlmClient(); PromptBuilder promptBuilder = new PromptBuilder(); PlanParser planParser = new PlanParser(); // Tool layer ToolRegistry toolRegistry = new ToolRegistry(scanner); // Core modules AgentMemory memory = new AgentMemory(); PerceptionModule perception = new PerceptionModule(); Planner planner = new Planner(llmClient, promptBuilder, planParser, toolRegistry); ActionModule actionModule = new ActionModule(toolRegistry); // Orchestrator (coordinates the ReAct loop) AgentOrchestrator orchestrator = new AgentOrchestrator(planner, actionModule, memory, renderer); // ── 3. Perceive the user's goal ────────────────────────────────────── Goal goal; try { goal = perception.perceive(rawInput); } catch (IllegalArgumentException e) { renderer.printError(e.getMessage()); scanner.close(); return; } System.out.println(" ✅ Goal understood: " + goal); System.out.println(); // ── 4. Run the ReAct loop ───────────────────────────────────────────── orchestrator.run(goal); scanner.close(); } }
Step 11: Create logback.xml file in src/main/resources folder.
Logback.xml
<configuration> <!-- Suppress verbose HTTP and LangChain4j internals; keep console clean --> <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> <target>System.err</target> <encoder> <pattern>%d{HH:mm:ss} [%level] %logger{20} - %msg%n</pattern> </encoder> </appender> <!-- Silence noisy third-party libraries --> <logger name="dev.langchain4j" level="WARN"/> <logger name="okhttp3" level="WARN"/> <logger name="okio" level="WARN"/> <root level="WARN"> <appender-ref ref="CONSOLE"/> </root> </configuration>
Build the Project
Open a terminal and navigate to the project directory where the `pom.xml` file is located. Then execute the following command to build the project.
mvn clean package
If the build completes successfully, Maven generates the application JAR file in the `target` directory.
$ ls ./target/ classes generated-sources generated-test-sources maven-archiver maven-status original-travel-agent-example-1.0.0.jar test-classes travel-agent-example-1.0.0.jar
The main executable JAR is: travel-agent-example-1.0.0.jar
Run the Application
After the project is built successfully, start the application by executing the following command:
java -jar ./target/travel-agent-example-1.0.0.jar
The Travel Agent application will start, and you can begin interacting with it from the console.
$java -jar ./target/travel-agent-example-1.0.0.jar ============================================================ ✈ TRAVEL PLANNER AI AGENT ✈ ReAct Architecture Demo ============================================================ Architecture: Perception → Plan → Act → Observe → Re-plan LLM : Ollama (llama3.2) Framework : LangChain4j (raw ChatModel — no AiServices) Services : All mocked — no real APIs ============================================================ Enter your travel goal: When prompted, enter the following travel goal: Book a 5-day trip to London ✅ Goal understood: Book a 5-day trip to London. ============================================================ Planning Cycle 1 ============================================================ GOAL: Book a 5-day trip to London. CURRENT STATE: Flights searched : NO Flight selected : NO Flight booked : NO Hotels searched : NO Hotel selected : NO Hotel booked : NO Confirmation email : NOT SENT Tour plans suggested: NO 🤔 Asking LLM to plan next step... ------------------------------------------------------------ GENERATED PLAN: Status : IN_PROGRESS Tool : searchFlights Reasoning : Search for available flights to London to begin the booking process. Parameters: destination = London ------------------------------------------------------------ EXECUTING: searchFlights() ------------------------------------------------------------ OBSERVATION: ✅ Found 3 flights to London: [BA-101] British Airways | JFK → LHR | 2025-07-28 | $650.00 [VS-202] Virgin Atlantic | JFK → LHR | 2025-07-28 | $580.00 [AA-303] American Airlines | JFK → LHR | 2025-07-29 | $510.00 ============================================================ Planning Cycle 2 ============================================================ GOAL: Book a 5-day trip to London. CURRENT STATE: Flights searched : YES (3 found) Flight selected : NO Flight booked : NO Hotels searched : NO Hotel selected : NO Hotel booked : NO Confirmation email : NOT SENT Tour plans suggested: NO 🤔 Asking LLM to plan next step... ------------------------------------------------------------ GENERATED PLAN: Status : IN_PROGRESS Tool : askUser Reasoning : Need to ask the user to select a flight from the available options Parameters: questionType = flight ------------------------------------------------------------ EXECUTING: askUser() ------------------------------------------------------------ ┌─────────────────────────────────────────┐ │ Please choose your flight: │ └─────────────────────────────────────────┘ [BA-101] British Airways | JFK → LHR | 2025-07-28 | $650.00 [VS-202] Virgin Atlantic | JFK → LHR | 2025-07-28 | $580.00 [AA-303] American Airlines | JFK → LHR | 2025-07-29 | $510.00 Enter flight ID [BA-101, VS-202, AA-303]: The application will display a list of available flights and prompt you to choose one. Enter the flight number of your preferred option. In this example, I selected the cheapest flight, AA-303. Simply enter: AA-303 Enter flight ID [BA-101, VS-202, AA-303]: AA-303 OBSERVATION: ✅ User selected flight: [AA-303] American Airlines | JFK → LHR | 2025-07-29 | $510.00 ============================================================ Planning Cycle 3 ============================================================ GOAL: Book a 5-day trip to London. CURRENT STATE: Flights searched : YES (3 found) Flight selected : [AA-303] American Airlines | JFK → LHR | 2025-07-29 | $510.00 Flight booked : NO Hotels searched : NO Hotel selected : NO Hotel booked : NO Confirmation email : NOT SENT Tour plans suggested: NO 🤔 Asking LLM to plan next step... ------------------------------------------------------------ GENERATED PLAN: Status : IN_PROGRESS Tool : searchHotels Reasoning : Search for available hotels at the destination to proceed with booking Parameters: destination = London ------------------------------------------------------------ EXECUTING: searchHotels() ------------------------------------------------------------ OBSERVATION: ✅ Found 3 hotels in London: [H-001] The Savoy | London, Strand | 5★ | $450.00/night [H-002] Premier Inn Waterloo | London, Waterloo | 3★ | $120.00/night [H-003] The Hoxton Shoreditch | London, Shoreditch | 4★ | $210.00/night ============================================================ Planning Cycle 4 ============================================================ GOAL: Book a 5-day trip to London. CURRENT STATE: Flights searched : YES (3 found) Flight selected : [AA-303] American Airlines | JFK → LHR | 2025-07-29 | $510.00 Flight booked : NO Hotels searched : YES (3 found) Hotel selected : NO Hotel booked : NO Confirmation email : NOT SENT Tour plans suggested: NO 🤔 Asking LLM to plan next step... ------------------------------------------------------------ GENERATED PLAN: Status : IN_PROGRESS Tool : askUser Reasoning : To continue booking the trip, we need to ask the user to select a hotel. Parameters: questionType = hotel ------------------------------------------------------------ EXECUTING: askUser() ------------------------------------------------------------ ┌─────────────────────────────────────────┐ │ Please choose your hotel: │ └─────────────────────────────────────────┘ [H-001] The Savoy | London, Strand | 5★ | $450.00/night [H-002] Premier Inn Waterloo | London, Waterloo | 3★ | $120.00/night [H-003] The Hoxton Shoreditch | London, Shoreditch | 4★ | $210.00/night Enter hotel ID [H-001, H-002, H-003]: Next, the application displays the list of available hotels along with their ratings and prompts you to choose one. In this example, we select H-001, which has a 5-star rating. Simply enter: H-001 Enter hotel ID [H-001, H-002, H-003]: H-001 OBSERVATION: ✅ User selected hotel: [H-001] The Savoy | London, Strand | 5★ | $450.00/night ============================================================ Planning Cycle 5 ============================================================ GOAL: Book a 5-day trip to London. CURRENT STATE: Flights searched : YES (3 found) Flight selected : [AA-303] American Airlines | JFK → LHR | 2025-07-29 | $510.00 Flight booked : NO Hotels searched : YES (3 found) Hotel selected : [H-001] The Savoy | London, Strand | 5★ | $450.00/night Hotel booked : NO Confirmation email : NOT SENT Tour plans suggested: NO 🤔 Asking LLM to plan next step... ------------------------------------------------------------ GENERATED PLAN: Status : IN_PROGRESS Tool : bookFlight Reasoning : Book the selected flight ------------------------------------------------------------ EXECUTING: bookFlight() ------------------------------------------------------------ OBSERVATION: ✅ Flight booked successfully! Booking reference: CONF-AA-303. [AA-303] American Airlines | JFK → LHR | 2025-07-29 | $510.00 ============================================================ Planning Cycle 6 ============================================================ GOAL: Book a 5-day trip to London. CURRENT STATE: Flights searched : YES (3 found) Flight selected : [AA-303] American Airlines | JFK → LHR | 2025-07-29 | $510.00 Flight booked : YES Hotels searched : YES (3 found) Hotel selected : [H-001] The Savoy | London, Strand | 5★ | $450.00/night Hotel booked : NO Confirmation email : NOT SENT Tour plans suggested: NO 🤔 Asking LLM to plan next step... ------------------------------------------------------------ GENERATED PLAN: Status : IN_PROGRESS Tool : searchHotels Reasoning : Search for available hotels at the destination to find the best option for booking. Parameters: destination = London ------------------------------------------------------------ EXECUTING: searchHotels() ------------------------------------------------------------ OBSERVATION: ✅ Found 3 hotels in London: [H-001] The Savoy | London, Strand | 5★ | $450.00/night [H-002] Premier Inn Waterloo | London, Waterloo | 3★ | $120.00/night [H-003] The Hoxton Shoreditch | London, Shoreditch | 4★ | $210.00/night ============================================================ Planning Cycle 7 ============================================================ GOAL: Book a 5-day trip to London. CURRENT STATE: Flights searched : YES (3 found) Flight selected : [AA-303] American Airlines | JFK → LHR | 2025-07-29 | $510.00 Flight booked : YES Hotels searched : YES (3 found) Hotel selected : [H-001] The Savoy | London, Strand | 5★ | $450.00/night Hotel booked : NO Confirmation email : NOT SENT Tour plans suggested: NO 🤔 Asking LLM to plan next step... ------------------------------------------------------------ GENERATED PLAN: Status : IN_PROGRESS Tool : bookHotel Reasoning : Book hotel that was previously selected by the user to complete the trip booking Parameters: destination = London ------------------------------------------------------------ EXECUTING: bookHotel() ------------------------------------------------------------ OBSERVATION: ✅ Hotel booked successfully! Booking reference: HTL-H-001. [H-001] The Savoy | London, Strand | 5★ | $450.00/night ============================================================ Planning Cycle 8 ============================================================ GOAL: Book a 5-day trip to London. CURRENT STATE: Flights searched : YES (3 found) Flight selected : [AA-303] American Airlines | JFK → LHR | 2025-07-29 | $510.00 Flight booked : YES Hotels searched : YES (3 found) Hotel selected : [H-001] The Savoy | London, Strand | 5★ | $450.00/night Hotel booked : YES Confirmation email : NOT SENT Tour plans suggested: NO 🤔 Asking LLM to plan next step... ------------------------------------------------------------ GENERATED PLAN: Status : IN_PROGRESS Tool : sendEmail Reasoning : Send confirmation email summarizing the booked flight and hotel to complete the booking process ------------------------------------------------------------ EXECUTING: sendEmail() ------------------------------------------------------------ ╔══════════════════════════════════════════════════╗ ║ 📧 EMAIL SENT ║ ╠══════════════════════════════════════════════════╣ ║ To : traveller@example.com ║ ║ Subject : Your Trip to London — Confirmed! ║ ╠══════════════════════════════════════════════════╣ ║ Dear Traveller, ║ ║ ║ ║ Your trip has been confirmed: ║ ║ ✈ Flight : [AA-303] American Airlines | JFK → LHR | 2025-07-29 | $510.00║ ║ 🏨 Hotel : [H-001] The Savoy | London, Strand | 5★ | $450.00/night║ ║ ║ ║ Have a great trip! ║ ║ — Travel Agent AI ║ ╚══════════════════════════════════════════════════╝ OBSERVATION: ✅ Confirmation email sent to traveller@example.com with full booking details. ============================================================ 🎉 GOAL COMPLETE — Your trip has been fully booked! ============================================================ The application completes the booking process and confirms that both the flight and hotel have been booked successfully. Suppose if you ask for a suggestion to plan 5 days trip to London, you will get following kind of response. Suggest 5 days trip plan to London. $java -jar ./target/travel-agent-example-1.0.0.jar ============================================================ ✈ TRAVEL PLANNER AI AGENT ✈ ReAct Architecture Demo ============================================================ Architecture: Perception → Plan → Act → Observe → Re-plan LLM : Ollama (llama3.2) Framework : LangChain4j (raw ChatModel — no AiServices) Services : All mocked — no real APIs ============================================================ Enter your travel goal: Suggest 5 days trip plan to London ✅ Goal understood: Suggest 5 days trip plan to London. ============================================================ Planning Cycle 1 ============================================================ GOAL: Suggest 5 days trip plan to London. CURRENT STATE: Flights searched : NO Flight selected : NO Flight booked : NO Hotels searched : NO Hotel selected : NO Hotel booked : NO Confirmation email : NOT SENT Tour plans suggested: NO 🤔 Asking LLM to plan next step... ------------------------------------------------------------ GENERATED PLAN: Status : IN_PROGRESS Tool : suggestTourPlans Reasoning : To satisfy the goal of suggesting a 5-day trip plan to London, suggestTourPlans is chosen as it provides curated multi-day tour plans for popular travel destinations. ------------------------------------------------------------ EXECUTING: suggestTourPlans() ------------------------------------------------------------ ╔══════════════════════════════════════════════════════════╗ ║ ✈ SUGGESTED TOUR PLANS ✈ ║ ╚══════════════════════════════════════════════════════════╝ 📍 London Explorer (5 Days) ─────────────────────────────────────────────────────── • Day 1 : Arrive, check in, evening walk along the Thames • Day 2 : Tower of London + Tower Bridge + Borough Market • Day 3 : British Museum + Covent Garden + West End show • Day 4 : Kensington Palace + Hyde Park + Notting Hill • Day 5 : Greenwich Observatory + Cutty Sark, depart 📍 Paris Getaway (4 Days) ─────────────────────────────────────────────────────── • Day 1 : Arrive, Eiffel Tower at sunset, Seine river cruise • Day 2 : Louvre Museum + Tuileries Garden + Champs-Élysées • Day 3 : Montmartre + Sacré-Cœur + local bistro dinner • Day 4 : Palace of Versailles day trip, depart evening 📍 Tokyo Adventure (7 Days) ─────────────────────────────────────────────────────── • Day 1 : Arrive, Shinjuku exploration • Day 2 : Senso-ji Temple + Akihabara electronics district • Day 3 : Tsukiji market + teamLab digital art museum • Day 4 : Day trip to Nikko (UNESCO shrines) • Day 5 : Harajuku + Shibuya crossing + Meiji Shrine • Day 6 : Mt. Fuji day trip from Tokyo • Day 7 : Ginza shopping, farewell dinner, depart OBSERVATION: ✅ Suggested 3 tour plans: London Explorer (5 Days): 5 days. Paris Getaway (4 Days): 4 days. Tokyo Adventure (7 Days): 7 days. User can now choose one to book, or the goal is complete if they only wanted suggestions. ============================================================ 🎉 GOAL COMPLETE — Your trip has been fully booked! ============================================================
You can download the Application from this link.
Previous Next Home












English (US)