GNGiseldo Neo and Alana NeoBooks
Introduction to Programming in Java21 / 25

Stateful Chatbots: Maintaining Context

State machines and continuous dialogue

20.1 Learning objectives

By the end of this chapter, you should be able to:

  • explain why state is important in chatbots;
  • implement a finite state machine for a chatbot;
  • maintain conversation context across multiple messages;
  • use pending actions to handle confirmations and prerequisites;
  • implement incremental slot filling;
  • handle negations in dialogue.

20.2 Why does state matter?

Stateful vs. stateless conversation.

Figure 20.1. Stateful vs. stateless conversation.

Consider these two interactions:

Stateless:

User: I want to buy a coffee
Bot: Okay, what kind of coffee?
User: With milk
Bot: Okay, what kind of coffee?  // <- Does not remember the previous message!

Stateful:

User: I want to buy a coffee
Bot: Okay, what kind of coffee?
User: With milk
Bot: Got it! A coffee with milk. What size?

The difference is that a stateful chatbot keeps track of information about the ongoing conversation, enabling more natural and useful dialogues.

20.3 Finite State Machines

A Finite State Machine (FSM) is a mathematical model used to design systems that can be in one of a finite number of states at any given time. In chatbots, we use an FSM to:

  1. Control the flow of the conversation
  2. Manage context
  3. Define which messages are valid at each moment

20.3.1 Basic FSM concepts

  • State: Represents a specific point in the conversation
  • Transition: A change from one state to another, usually triggered by a user message
  • Event/Input: A user action that triggers a transition
  • Action/Output: The bot’s response or action performed during a transition

20.3.2 Example 1: Simple state machine for coffee ordering

Complete source file: CoffeeOrderBot.java.

import java.util.*;

public class CoffeeOrderBot {

    // State definitions
    public enum State {
        INIT,          // Initial state
        CHOOSE_COFFEE, // Choosing the coffee type
        CHOOSE_SIZE,   // Choosing the size
        CHOOSE_MILK,   // Choosing whether to add milk
        CONFIRM,       // Confirming the order
        COMPLETE       // Order complete
    }

    // Event type definitions (user messages)
    public enum Event {
        START_ORDER,
        SELECT_COFFEE,
        SELECT_SIZE,
        SELECT_MILK,
        CONFIRM,
        CANCEL,
        UNKNOWN
    }

    // Current bot state
    private State currentState;

    // Order data
    private String coffeeType;
    private String size;
    private boolean withMilk;

    // Transition rules: (current state, event) -> response template
    private static final Map<State, Map<Event, String>> TRANSITION_RULES = new EnumMap<>(State.class);

    static {
        // Rules for the INIT state
        Map<Event, String> initRules = new EnumMap<>(Event.class);
        initRules.put(Event.START_ORDER, "Okay, what kind of coffee would you like? (Espresso, Latte, Cappuccino)");
        TRANSITION_RULES.put(State.INIT, initRules);

        // Rules for the CHOOSE_COFFEE state
        Map<Event, String> coffeeRules = new EnumMap<>(Event.class);
        coffeeRules.put(Event.SELECT_COFFEE, "Got it! Now, what size? (Small, Medium, Large)");
        TRANSITION_RULES.put(State.CHOOSE_COFFEE, coffeeRules);

        // Rules for the CHOOSE_SIZE state
        Map<Event, String> sizeRules = new EnumMap<>(Event.class);
        sizeRules.put(Event.SELECT_SIZE, "With milk or without milk? (With, Without)");
        TRANSITION_RULES.put(State.CHOOSE_SIZE, sizeRules);

        // Rules for the CHOOSE_MILK state
        Map<Event, String> milkRules = new EnumMap<>(Event.class);
        milkRules.put(Event.SELECT_MILK, "Please confirm: {1} {0}, {2}. (Yes, No)");
        TRANSITION_RULES.put(State.CHOOSE_MILK, milkRules);

        // Rules for the CONFIRM state
        Map<Event, String> confirmRules = new EnumMap<>(Event.class);
        confirmRules.put(Event.CONFIRM, "Perfect! Your coffee is being prepared.");
        confirmRules.put(Event.CANCEL, "Order canceled.");
        TRANSITION_RULES.put(State.CONFIRM, confirmRules);
    }

    public CoffeeOrderBot() {
        currentState = State.INIT;
        resetOrder();
    }

    private void resetOrder() {
        coffeeType = null;
        size = null;
        withMilk = false;
    }

    // Classifies the user's message into an event
    private Event classifyEvent(String message) {
        message = message.toLowerCase().trim();

        switch (currentState) {
            case INIT:
            case COMPLETE:
                if (message.contains("coffee") || message.contains("buy") || message.contains("order")) {
                    return Event.START_ORDER;
                }
                break;

            case CHOOSE_COFFEE:
                if (message.contains("espresso")) return Event.SELECT_COFFEE;
                if (message.contains("latte")) return Event.SELECT_COFFEE;
                if (message.contains("cappuccino")) return Event.SELECT_COFFEE;
                break;

            case CHOOSE_SIZE:
                if (message.contains("small")) return Event.SELECT_SIZE;
                if (message.contains("medium")) return Event.SELECT_SIZE;
                if (message.contains("large")) return Event.SELECT_SIZE;
                break;

            case CHOOSE_MILK:
                if (message.contains("without") || message.contains("no")) return Event.SELECT_MILK;
                if (message.contains("with") || message.contains("yes")) return Event.SELECT_MILK;
                break;

            case CONFIRM:
                if (message.contains("yes") || message.contains("ok") || message.contains("confirm")) return Event.CONFIRM;
                if (message.contains("no") || message.contains("cancel")) return Event.CANCEL;
                if (message.contains("coffee") || message.contains("buy") || message.contains("order")) {
                    return Event.START_ORDER;
                }
                break;
        }

        return Event.UNKNOWN;
    }

    // Processes the message and updates the state
    public String process(String message) {
        Event event = classifyEvent(message);

        // Update order data based on the event
        switch (currentState) {
            case CHOOSE_COFFEE:
                if (event == Event.SELECT_COFFEE) {
                    coffeeType = message.trim();
                }
                break;

            case CHOOSE_SIZE:
                if (event == Event.SELECT_SIZE) {
                    size = message.trim();
                }
                break;

            case CHOOSE_MILK:
                if (event == Event.SELECT_MILK) {
                    String lower = message.toLowerCase();
                    withMilk = !lower.contains("without") && !lower.contains("no")
                            && (lower.contains("with") || lower.contains("yes"));
                }
                break;
        }

        // Apply transition rules
        Map<Event, String> stateRules = TRANSITION_RULES.get(currentState);
        if (stateRules != null && stateRules.containsKey(event)) {
            String response = stateRules.get(event);

            // Format the confirmation message
            if (currentState == State.CHOOSE_MILK && event == Event.SELECT_MILK) {
                String milkText = withMilk ? "with milk" : "without milk";
                response = response.replace("{0}", coffeeType)
                                   .replace("{1}", size)
                                   .replace("{2}", milkText);
            }

            // Update the state
            switch (currentState) {
                case INIT:
                    if (event == Event.START_ORDER) currentState = State.CHOOSE_COFFEE;
                    break;

                case CHOOSE_COFFEE:
                    if (event == Event.SELECT_COFFEE) currentState = State.CHOOSE_SIZE;
                    break;

                case CHOOSE_SIZE:
                    if (event == Event.SELECT_SIZE) currentState = State.CHOOSE_MILK;
                    break;

                case CHOOSE_MILK:
                    if (event == Event.SELECT_MILK) currentState = State.CONFIRM;
                    break;

                case CONFIRM:
                    if (event == Event.CONFIRM) currentState = State.COMPLETE;
                    if (event == Event.CANCEL) currentState = State.INIT;
                    break;

                case COMPLETE:
                    if (event == Event.START_ORDER) {
                        currentState = State.CHOOSE_COFFEE;
                        resetOrder();
                    }
                    break;
            }

            return response;
        }

        // If there is no transition rule for this event in the current state
        switch (currentState) {
            case CONFIRM:
            case COMPLETE:
                if (event == Event.START_ORDER) {
                    currentState = State.CHOOSE_COFFEE;
                    resetOrder();
                    return "Okay, starting a new order. What kind of coffee would you like? (Espresso, Latte, Cappuccino)";
                }
                break;
        }

        return "I didn't understand. Could you repeat that or enter a valid option?";
    }

    public State getCurrentState() {
        return currentState;
    }

    public static void main(String[] args) {
        CoffeeOrderBot bot = new CoffeeOrderBot();
        Scanner scanner = new Scanner(System.in);

        System.out.println("Coffee Order Bot. Type 'exit' to quit.");

        while (true) {
            System.out.print("User: ");
            String input = scanner.nextLine();

            if (input.equalsIgnoreCase("exit")) {
                break;
            }

            String response = bot.process(input);
            System.out.println("Bot: " + response);

            if (bot.getCurrentState() == State.COMPLETE) {
                System.out.println("Order complete! Type 'order' to start a new order.");
            }
        }

        scanner.close();
    }
}

20.4 Pending Actions

In many dialogues, we need to handle confirmations or prerequisite steps before continuing. For example:

User: I want to buy a coffee
Bot: Okay, but first you need to log in. What is your phone number?
User: 555-12345
Bot: Perfect! Welcome back. What product would you like to buy?

Here, the bot had to complete an action (logging in) before resuming the main flow. We call this a pending action.

20.4.1 Example 2: Pending actions

import java.util.*;

public class PendingActionBot {

    public enum State {
        INIT,
        AUTH_REQUIRED,    // Authentication needed
        AUTHENTICATED,    // User authenticated
        CHOOSE_PRODUCT,
        CONFIRM_ORDER,
        ORDER_COMPLETE
    }

    public enum PendingAction {
        NONE,
        AUTHENTICATE
    }

    private State currentState;
    private PendingAction pendingAction;
    private String pendingMessage; // Message to show after the pending action completes

    // User data
    private String phoneNumber;
    private String selectedProduct;

    public PendingActionBot() {
        currentState = State.INIT;
        pendingAction = PendingAction.NONE;
    }

    private void setPendingAction(PendingAction action, String message) {
        pendingAction = action;
        pendingMessage = message;
    }

    private void clearPendingAction() {
        pendingAction = PendingAction.NONE;
        pendingMessage = null;
    }

    public String process(String message) {
        // If there is a pending action, handle it first
        if (pendingAction != PendingAction.NONE) {
            switch (pendingAction) {
                case AUTHENTICATE:
                    // Check whether the message is a phone number
                    if (isPhoneNumber(message)) {
                        phoneNumber = message;
                        String nextMessage = pendingMessage;
                        clearPendingAction();
                        currentState = State.AUTHENTICATED;
                        return "Perfect! Welcome back. " + nextMessage;
                    } else {
                        return "Please enter a valid phone number.";
                    }
            }
        }

        // Normal processing
        message = message.toLowerCase().trim();

        switch (currentState) {
            case INIT:
                if (message.contains("buy") || message.contains("order")) {
                    // Check whether the user is authenticated
                    if (phoneNumber == null) {
                        setPendingAction(PendingAction.AUTHENTICATE, "What product would you like to buy?");
                        return "Okay, but first you need to log in. What is your phone number?";
                    } else {
                        currentState = State.CHOOSE_PRODUCT;
                        return "What product would you like to buy?";
                    }
                }
                break;

            case AUTHENTICATED:
            case CHOOSE_PRODUCT:
                if (message.contains("coffee") || message.contains("book") || message.contains("phone")) {
                    selectedProduct = message;
                    currentState = State.CONFIRM_ORDER;
                    return String.format("You want to buy: %s. Confirm? (Yes/No)", selectedProduct);
                }
                break;

            case CONFIRM_ORDER:
                if (message.contains("yes") || message.contains("ok")) {
                    currentState = State.ORDER_COMPLETE;
                    return String.format("Order confirmed: %s. Thank you!", selectedProduct);
                } else if (message.contains("no") || message.contains("cancel")) {
                    currentState = State.CHOOSE_PRODUCT;
                    selectedProduct = null;
                    return "Order canceled. What other product would you like?";
                }
                break;

            case ORDER_COMPLETE:
                if (message.contains("buy") || message.contains("order")) {
                    currentState = State.CHOOSE_PRODUCT;
                    selectedProduct = null;
                    return "What product would you like to buy?";
                }
                break;
        }

        return "I didn't understand. Could you repeat that?";
    }

    private boolean isPhoneNumber(String message) {
        // Simple check: digits and hyphens only
        return message.matches("^[\\d-]+$");
    }

    public static void main(String[] args) {
        PendingActionBot bot = new PendingActionBot();
        Scanner scanner = new Scanner(System.in);

        System.out.println("Pending Action Bot. Type 'exit' to quit.");

        while (true) {
            System.out.print("User: ");
            String input = scanner.nextLine();

            if (input.equalsIgnoreCase("exit")) {
                break;
            }

            String response = bot.process(input);
            System.out.println("Bot: " + response);
        }

        scanner.close();
    }
}

20.5 Incremental Slot Filling

In the context of chatbots, slots are the fields of information required to complete an action. Incremental slot filling is the process of collecting these fields step by step throughout the conversation.

For example, for a restaurant reservation, the slots might be:

  • Cuisine type
  • Location
  • Price range
  • Date
  • Time
  • Number of people

20.5.1 Example 3: Slot filling

import java.util.*;

public class SlotFillingBot {

    public enum State {
        INIT,
        COLLECTING_SLOTS,
        CONFIRMING,
        COMPLETE
    }

    public static class Slot {
        public final String name;
        public final String question;
        public String value;

        public Slot(String name, String question) {
            this.name = name;
            this.question = question;
            this.value = null;
        }

        public boolean isFilled() {
            return value != null;
        }
    }

    private State currentState;
    private List<Slot> slots;
    private int currentSlotIndex;

    public SlotFillingBot() {
        currentState = State.INIT;

        // Define the required slots
        slots = new ArrayList<>();
        slots.add(new Slot("food_type", "What kind of cuisine do you prefer? (Italian, Chinese, Brazilian, Japanese)"));
        slots.add(new Slot("location", "In which area would you like the restaurant? (Downtown, North, South, East, West)"));
        slots.add(new Slot("price_range", "What price range? (Cheap, Medium, Expensive)"));
        slots.add(new Slot("date", "For what date? (Today, Tomorrow, Monday, etc.)"));
        slots.add(new Slot("time", "What time? (12:00, 19:00, etc.)"));
        slots.add(new Slot("people", "For how many people?"));

        currentSlotIndex = 0;
    }

    private boolean allSlotsFilled() {
        for (Slot slot : slots) {
            if (!slot.isFilled()) {
                return false;
            }
        }
        return true;
    }

    private Slot getNextSlot() {
        if (currentSlotIndex < slots.size()) {
            return slots.get(currentSlotIndex);
        }
        return null;
    }

    private Slot findSlotByName(String name) {
        for (Slot slot : slots) {
            if (slot.name.equals(name)) {
                return slot;
            }
        }
        return null;
    }

    private boolean fillSlotFromMessage(String message, Slot slot) {
        message = message.toLowerCase().trim();

        switch (slot.name) {
            case "food_type":
                if (message.contains("italian")) {
                    slot.value = "Italian";
                    return true;
                } else if (message.contains("chinese")) {
                    slot.value = "Chinese";
                    return true;
                } else if (message.contains("brazilian")) {
                    slot.value = "Brazilian";
                    return true;
                } else if (message.contains("japanese")) {
                    slot.value = "Japanese";
                    return true;
                }
                break;

            case "location":
                if (message.contains("downtown") || message.contains("center")) {
                    slot.value = "Downtown";
                    return true;
                } else if (message.contains("north")) {
                    slot.value = "North";
                    return true;
                } else if (message.contains("south")) {
                    slot.value = "South";
                    return true;
                } else if (message.contains("east")) {
                    slot.value = "East";
                    return true;
                } else if (message.contains("west")) {
                    slot.value = "West";
                    return true;
                }
                break;

            case "price_range":
                if (message.contains("cheap") || message.contains("budget") || message.contains("affordable")) {
                    slot.value = "Cheap";
                    return true;
                } else if (message.contains("medium") || message.contains("moderate")) {
                    slot.value = "Medium";
                    return true;
                } else if (message.contains("expensive") || message.contains("luxury")) {
                    slot.value = "Expensive";
                    return true;
                }
                break;

            case "date":
                // Simple date capture
                slot.value = message;
                return true;

            case "time":
                // Simple time capture
                slot.value = message;
                return true;

            case "people":
                // Number of people
                try {
                    int num = Integer.parseInt(message);
                    if (num > 0) {
                        slot.value = String.valueOf(num);
                        return true;
                    }
                } catch (NumberFormatException e) {
                    // Not a valid number
                }
                break;
        }

        return false;
    }

    public String process(String message) {
        message = message.toLowerCase().trim();

        switch (currentState) {
            case INIT:
                if (message.contains("restaurant") || message.contains("eat") || message.contains("dinner")) {
                    currentState = State.COLLECTING_SLOTS;
                    return getNextSlot().question;
                }
                break;

            case COLLECTING_SLOTS:
                Slot currentSlot = getNextSlot();

                if (currentSlot == null) {
                    // All slots filled
                    currentState = State.CONFIRMING;
                    return generateConfirmation();
                }

                // Check whether the message fills the current slot
                if (fillSlotFromMessage(message, currentSlot)) {
                    currentSlotIndex++;

                    if (allSlotsFilled()) {
                        currentState = State.CONFIRMING;
                        return generateConfirmation();
                    } else {
                        return getNextSlot().question;
                    }
                } else {
                    // Check whether the message fills another unfilled slot
                    for (Slot slot : slots) {
                        if (!slot.isFilled() && fillSlotFromMessage(message, slot)) {
                            return getNextSlot().question;
                        }
                    }

                    return "I didn't understand. " + currentSlot.question;
                }

            case CONFIRMING:
                if (message.contains("yes") || message.contains("ok") || message.contains("confirm")) {
                    currentState = State.COMPLETE;
                    return generateFinalResponse();
                } else if (message.contains("no") || message.contains("cancel")) {
                    // Restart slot collection
                    for (Slot slot : slots) {
                        slot.value = null;
                    }
                    currentSlotIndex = 0;
                    currentState = State.COLLECTING_SLOTS;
                    return "Okay, let's start over. " + getNextSlot().question;
                } else if (message.contains("change") || message.contains("edit")) {
                    // Allow changing a specific slot
                    for (Slot slot : slots) {
                        if (message.contains(slot.name.toLowerCase())) {
                            slot.value = null;
                            currentSlotIndex = slots.indexOf(slot);
                            currentState = State.COLLECTING_SLOTS;
                            return "Okay, what is the new value for " + slot.name + "?";
                        }
                    }
                    return "Which slot would you like to change? " + getSlotNames();
                }
                return "Would you like to confirm or cancel?";

            case COMPLETE:
                if (message.contains("restaurant") || message.contains("eat") || message.contains("dinner")) {
                    // Reset for a new reservation
                    for (Slot slot : slots) {
                        slot.value = null;
                    }
                    currentSlotIndex = 0;
                    currentState = State.COLLECTING_SLOTS;
                    return getNextSlot().question;
                }
                break;
        }

        return "I didn't understand. Could you be more specific?";
    }

    private String generateConfirmation() {
        StringBuilder sb = new StringBuilder();
        sb.append("Please confirm your reservation: ");

        for (Slot slot : slots) {
            sb.append(String.format("%s: %s, ", slot.name, slot.value));
        }

        String confirmation = sb.toString();
        return confirmation.substring(0, confirmation.length() - 2) + ". (Yes/No)";
    }

    private String generateFinalResponse() {
        StringBuilder sb = new StringBuilder();
        sb.append("Reservation confirmed!\n");

        for (Slot slot : slots) {
            sb.append(String.format("%s: %s\n", slot.name, slot.value));
        }

        return sb.toString();
    }

    private String getSlotNames() {
        StringBuilder sb = new StringBuilder();
        for (Slot slot : slots) {
            sb.append(slot.name).append(", ");
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        SlotFillingBot bot = new SlotFillingBot();
        Scanner scanner = new Scanner(System.in);

        System.out.println("Restaurant Reservation Bot. Type 'exit' to quit.");

        while (true) {
            System.out.print("User: ");
            String input = scanner.nextLine();

            if (input.equalsIgnoreCase("exit")) {
                break;
            }

            String response = bot.process(input);
            System.out.println("Bot: " + response);
        }

        scanner.close();
    }
}

20.6 Handling Negation

In conversations, users frequently use negations such as “I don’t want that”, “Except pizza”, or “Without sugar”. We need to be able to identify and handle these negations accurately.

20.6.1 Example 4: Negation detection

import java.util.*;
import java.util.regex.*;

public class NegationHandler {

    // List of negation words and phrases
    private static final List<String> NEGATION_WORDS = Arrays.asList(
        "not", "no", "don't want", "do not want", "don't like",
        "except", "without", "never", "nothing"
    );

    // Pattern for detecting negation cues
    private static final Pattern NEGATION_PATTERN = Pattern.compile(
        "\\b(not|no|without|except|never|nothing|don't)\\b",
        Pattern.CASE_INSENSITIVE
    );

    public static boolean hasNegation(String message) {
        message = message.toLowerCase().trim();

        for (String negation : NEGATION_WORDS) {
            if (message.contains(negation)) {
                return true;
            }
        }

        return NEGATION_PATTERN.matcher(message).find();
    }

    public static List<String> extractNegatedEntities(String message, List<String> allEntities) {
        List<String> negatedEntities = new ArrayList<>();
        message = message.toLowerCase();

        // Check whether negation is present
        if (!hasNegation(message)) {
            return negatedEntities;
        }

        // For each entity, check whether it appears right after a negation cue
        for (String entity : allEntities) {
            String lowerEntity = entity.toLowerCase();

            Pattern entityPattern = Pattern.compile(
                "\\b(not|no|without|except|never|nothing|don't want)\\s+" + Pattern.quote(lowerEntity) + "\\b",
                Pattern.CASE_INSENSITIVE
            );

            if (entityPattern.matcher(message).find()) {
                negatedEntities.add(entity);
            }
        }

        return negatedEntities;
    }

    public static void main(String[] args) {
        String message1 = "I want to eat pizza but don't want burgers";
        String message2 = "All restaurants except Italian";
        String message3 = "I like coffee without sugar";

        List<String> entities1 = Arrays.asList("pizza", "burgers");
        List<String> entities2 = Arrays.asList("restaurants", "Italian");
        List<String> entities3 = Arrays.asList("coffee", "sugar");

        System.out.println("Message: " + message1);
        System.out.println("Has negation: " + hasNegation(message1));
        System.out.println("Negated entities: " + extractNegatedEntities(message1, entities1));
        System.out.println();

        System.out.println("Message: " + message2);
        System.out.println("Has negation: " + hasNegation(message2));
        System.out.println("Negated entities: " + extractNegatedEntities(message2, entities2));
        System.out.println();

        System.out.println("Message: " + message3);
        System.out.println("Has negation: " + hasNegation(message3));
        System.out.println("Negated entities: " + extractNegatedEntities(message3, entities3));
    }
}

20.6.2 Example 5: Integrating slot filling and negation

import java.util.*;

public class RestaurantBotWithNegation {

    public static class Slot {
        public final String name;
        public final String question;
        public String value;
        public boolean negated;

        public Slot(String name, String question) {
            this.name = name;
            this.question = question;
            this.value = null;
            this.negated = false;
        }

        public boolean isFilled() {
            return value != null;
        }
    }

    private List<Slot> slots;
    private int currentSlotIndex;

    public RestaurantBotWithNegation() {
        slots = new ArrayList<>();
        slots.add(new Slot("food_type", "What kind of cuisine would you like? (Italian, Chinese, etc.)"));
        slots.add(new Slot("exclude_food", "Any type of food you do not want? (or 'none')"));
        slots.add(new Slot("price_range", "What price range? (Cheap, Medium, Expensive)"));

        currentSlotIndex = 0;
    }

    private boolean hasNegation(String message) {
        message = message.toLowerCase();
        return message.contains("not") || message.contains("no ") ||
               message.contains("except") || message.contains("without");
    }

    private boolean fillSlotFromMessage(String message, Slot slot) {
        message = message.toLowerCase().trim();
        slot.negated = hasNegation(message);

        if (slot.negated) {
            // Extract the negated entity
            String[] words = message.split("\\s+");
            for (int i = 0; i < words.length - 1; i++) {
                if (words[i].equals("not") || words[i].equals("no") ||
                    words[i].equals("except") || words[i].equals("without")) {
                    slot.value = words[i + 1];
                    return true;
                }
            }
        } else {
            // Normal slot filling
            switch (slot.name) {
                case "food_type":
                    if (message.contains("italian")) {
                        slot.value = "Italian";
                        return true;
                    } else if (message.contains("chinese")) {
                        slot.value = "Chinese";
                        return true;
                    }
                    // ... other options
                    break;

                case "exclude_food":
                    if (message.contains("none") || message.contains("nothing")) {
                        slot.value = "None";
                        return true;
                    }
                    // If not negated and not "none", do not accept
                    return false;

                case "price_range":
                    if (message.contains("cheap")) {
                        slot.value = "Cheap";
                        return true;
                    } else if (message.contains("medium")) {
                        slot.value = "Medium";
                        return true;
                    } else if (message.contains("expensive")) {
                        slot.value = "Expensive";
                        return true;
                    }
                    break;
            }
        }

        return false;
    }

    private Slot getNextSlot() {
        if (currentSlotIndex < slots.size()) {
            return slots.get(currentSlotIndex);
        }
        return null;
    }

    public String process(String message) {
        Slot currentSlot = getNextSlot();

        if (currentSlot == null) {
            return generateSummary();
        }

        if (fillSlotFromMessage(message, currentSlot)) {
            currentSlotIndex++;
            currentSlot = getNextSlot();

            if (currentSlot == null) {
                return generateSummary();
            }

            return currentSlot.question;
        }

        return "I didn't understand. " + currentSlot.question;
    }

    private String generateSummary() {
        StringBuilder sb = new StringBuilder();
        sb.append("Reservation summary:\n");

        for (Slot slot : slots) {
            if (slot.isFilled()) {
                String prefix = slot.negated ? "Does NOT want" : "Wants";
                sb.append(String.format("- %s (%s): %s\n", slot.name, prefix, slot.value));
            }
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        RestaurantBotWithNegation bot = new RestaurantBotWithNegation();
        Scanner scanner = new Scanner(System.in);

        System.out.println("Restaurant Bot with Negation. Type 'exit' to quit.");

        while (true) {
            System.out.print("User: ");
            String input = scanner.nextLine();

            if (input.equalsIgnoreCase("exit")) {
                break;
            }

            String response = bot.process(input);
            System.out.println("Bot: " + response);
        }

        scanner.close();
    }
}

20.7 Project evolution: Stateful chatbot

In this chapter, we added:

  1. Finite state machines to control the flow of the conversation
  2. Pending actions to handle prerequisites such as authentication
  3. Incremental slot filling to collect required information step by step
  4. Negation detection to understand user exclusions and preferences

These capabilities allow our chatbot to:

  • Maintain conversation context
  • Collect information in a structured way
  • Handle confirmations and cancellations
  • Understand negations and exceptions
  • Create more natural and useful dialogues

20.8 Verifiable practice

  1. Implement the CoffeeOrderBot state machine (CoffeeOrderBot.java) and test it with a complete conversation.
  2. Create PendingActionBot and verify that it handles pending actions properly.
  3. Build SlotFillingBot and test it with different slot-filling orders.
  4. Implement NegationHandler and verify that it accurately identifies negated entities.
  5. Integrate negation into slot filling with RestaurantBotWithNegation.

Completion criteria:

  • All examples compile cleanly with javac --release 21
  • The state machines transition accurately between states
  • Pending actions execute in the right order
  • Slot filling collects all required information
  • Negation detection works as expected
  • The code follows standard Java naming conventions

Before moving on

You should be able to explain:

  • Why is state important in chatbots?
  • How do you implement a finite state machine?
  • What are pending actions and how are they used?
  • How does incremental slot filling work?
  • How do you detect and handle negation in dialogues?

20.9 Additional resources