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

Intents and Entities: Understanding the User

Intent classification and information extraction

19.1 Learning Objectives

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

  • explain what intents and entities are in chatbots;
  • implement a basic intent classifier in Java;
  • extract entities from user messages;
  • use regular expressions to recognize user intents;
  • apply word vectors for semantic similarity (conceptually);
  • integrate intents and entities into a chatbot.

19.2 What Are Intents and Entities?

Intents and Entities: the building blocks of understanding.

Figure 19.1. Intents and Entities: the building blocks of understanding.

An intent represents the goal or action the user wants to accomplish. It categorizes what the user wants.

Examples of intents:

  • greet: "Hello", "Hi", "Good morning"
  • book_flight: "I want to book a flight", "I need an airline ticket"
  • search_restaurant: "Where is a good restaurant?", "I want to eat pizza"
  • ask_weather: "What's the weather like?", "Is it going to rain today?"

An entity is a specific piece of information relevant to the intent. Entities supply the details needed to carry out the action.

Examples of entities:

  • For the book_flight intent: origin, destination, date, time
  • For the search_restaurant intent: cuisine_type, location, price_range
  • For the ask_weather intent: location, date

19.3 Recognizing Intents with Regular Expressions

A straightforward way to classify intents is using regular expressions. Although not as flexible as machine learning models, regex-based classification is computationally lightweight and easy to build and debug.

19.3.1 Example 1: Regex-Based Intent Classifier

Complete source in IntentClassifier.java:

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

public class IntentClassifier {

    // Enum representing the supported intents
    public enum Intent {
        GREETING,         // Greetings
        GOODBYE,          // Farewells
        THANKS,           // Expressions of gratitude
        WEATHER_QUESTION, // Weather questions
        FOOD_ORDER,       // Food orders
        FLIGHT_BOOKING,   // Flight bookings
        UNKNOWN           // Unknown intent
    }

    // Map of regex patterns for each intent
    private static final Map<Intent, List<Pattern>> INTENT_PATTERNS = new EnumMap<>(Intent.class);

    static {
        // Greetings
        INTENT_PATTERNS.put(Intent.GREETING, Arrays.asList(
            Pattern.compile("\\b(hi|hello|good morning|good afternoon|good evening|hey|what's up)\\b", Pattern.CASE_INSENSITIVE),
            Pattern.compile("^hi!?$", Pattern.CASE_INSENSITIVE)
        ));

        // Farewells
        INTENT_PATTERNS.put(Intent.GOODBYE, Arrays.asList(
            Pattern.compile("\\b(bye|goodbye|see you|farewell|cya)\\b", Pattern.CASE_INSENSITIVE),
            Pattern.compile("^see ya( later)?!?$", Pattern.CASE_INSENSITIVE)
        ));

        // Expressions of gratitude
        INTENT_PATTERNS.put(Intent.THANKS, Arrays.asList(
            Pattern.compile("\\b(thanks|thank you|thx|appreciate it|cheers)\\b", Pattern.CASE_INSENSITIVE)
        ));

        // Weather questions
        INTENT_PATTERNS.put(Intent.WEATHER_QUESTION, Arrays.asList(
            Pattern.compile("\\b(weather|forecast|rain|sunny|cold|hot|temperature)\\b", Pattern.CASE_INSENSITIVE),
            Pattern.compile("how is the weather|what's the weather", Pattern.CASE_INSENSITIVE)
        ));

        // Food orders
        INTENT_PATTERNS.put(Intent.FOOD_ORDER, Arrays.asList(
            Pattern.compile("\\b(want|order|like|get)\\b.*\\b(food|eat|pizza|burger|hamburger|sushi|sandwich)\\b", Pattern.CASE_INSENSITIVE),
            Pattern.compile("\\b(hungry|eat|pizza|burger)\\b", Pattern.CASE_INSENSITIVE)
        ));

        // Flight bookings
        INTENT_PATTERNS.put(Intent.FLIGHT_BOOKING, Arrays.asList(
            Pattern.compile("\\b(book|buy|ticket|flight|airplane|airline|fly)\\b", Pattern.CASE_INSENSITIVE)
        ));
    }

    public static Intent classify(String message) {
        String normalizedMessage = message.toLowerCase().trim();

        for (Map.Entry<Intent, List<Pattern>> entry : INTENT_PATTERNS.entrySet()) {
            Intent intent = entry.getKey();
            List<Pattern> patterns = entry.getValue();

            for (Pattern pattern : patterns) {
                if (pattern.matcher(normalizedMessage).find()) {
                    return intent;
                }
            }
        }

        return Intent.UNKNOWN;
    }

    public static void main(String[] args) {
        System.out.println(classify("Hello, how are you?"));          // GREETING
        System.out.println(classify("See you later!"));               // GOODBYE
        System.out.println(classify("Thanks for your help"));         // THANKS
        System.out.println(classify("What's the weather like today?")); // WEATHER_QUESTION
        System.out.println(classify("I want a pizza"));               // FOOD_ORDER
        System.out.println(classify("I need to book a flight"));      // FLIGHT_BOOKING
        System.out.println(classify("What is the capital of France?")); // UNKNOWN
    }
}

19.4 Extracting Entities

Now that we can classify intents, let’s extract structured entities from user messages.

19.4.1 Example 2: Regex-Based Entity Extraction

Complete source in EntityExtractor.java:

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

public class EntityExtractor {

    public static class Entity {
        public final String type;
        public final String value;
        public final int start;
        public final int end;

        public Entity(String type, String value, int start, int end) {
            this.type = type;
            this.value = value;
            this.start = start;
            this.end = end;
        }

        @Override
        public String toString() {
            return String.format("Entity{type='%s', value='%s', start=%d, end=%d}", type, value, start, end);
        }
    }

    // Map of regex patterns for entities
    private static final Map<String, Pattern> ENTITY_PATTERNS = new LinkedHashMap<>();

    static {
        // Locations (major cities and countries)
        ENTITY_PATTERNS.put("location", Pattern.compile(
            "\\b(new york|los angeles|chicago|san francisco|miami|boston|seattle|austin|" +
            "london|paris|tokyo|berlin|madrid|rome|toronto|sydney|sao paulo|rio de janeiro|" +
            "brazil|portugal|usa|united states|japan|china|germany|france|england|spain|italy)\\b",
            Pattern.CASE_INSENSITIVE
        ));

        // Food types
        ENTITY_PATTERNS.put("food_type", Pattern.compile(
            "\\b(pizza|burger|hamburger|sushi|sandwich|steak|pasta|salad|bread|cake|coffee|juice|water|soda|beer)\\b",
            Pattern.CASE_INSENSITIVE
        ));

        // Dates (simple format)
        ENTITY_PATTERNS.put("date", Pattern.compile(
            "\\b(today|tomorrow|yesterday|monday|tuesday|wednesday|thursday|friday|saturday|sunday|" +
            "\\d{1,2}/\\d{1,2}/\\d{4})\\b",
            Pattern.CASE_INSENSITIVE
        ));

        // Times
        ENTITY_PATTERNS.put("time", Pattern.compile(
            "\\b(\\d{1,2}:\\d{2}(?:\\s?[ap]m)?|\\d{1,2}\\s?[ap]m|morning|afternoon|evening|night|noon|midnight)\\b",
            Pattern.CASE_INSENSITIVE
        ));

        // Numbers (for quantities, prices, etc.)
        ENTITY_PATTERNS.put("number", Pattern.compile("\\b\\d+\\b"));

        // Proper names (capitalized words)
        ENTITY_PATTERNS.put("person", Pattern.compile("\\b[A-Z][a-z]+(?: [A-Z][a-z]+)*\\b"));
    }

    public static List<Entity> extract(String message) {
        List<Entity> entities = new ArrayList<>();

        for (Map.Entry<String, Pattern> entry : ENTITY_PATTERNS.entrySet()) {
            String entityType = entry.getKey();
            Pattern pattern = entry.getValue();
            Matcher matcher = pattern.matcher(message);

            while (matcher.find()) {
                String value = matcher.group();
                int start = matcher.start();
                int end = matcher.end();
                entities.add(new Entity(entityType, value, start, end));
            }
        }

        return entities;
    }

    public static void main(String[] args) {
        String message = "I want to book a flight to New York tomorrow at 15:00";
        List<Entity> entities = extract(message);

        System.out.println("Message: " + message);
        System.out.println("Entities found:");
        for (Entity entity : entities) {
            System.out.println("  " + entity);
        }
    }
}

19.4.2 Example 3: Contextual Entity Extraction

Sometimes we need sentence context to extract entities accurately. For example, in "I want to fly from New York to London", we need to identify which city is the origin and which is the destination.

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

public class ContextualEntityExtractor {

    public static class Entity {
        public final String type;
        public final String value;
        public final String role; // role of the entity (origin, destination, etc.)

        public Entity(String type, String value, String role) {
            this.type = type;
            this.value = value;
            this.role = role;
        }

        @Override
        public String toString() {
            return String.format("Entity{type='%s', value='%s', role='%s'}", type, value, role);
        }
    }

    public static List<Entity> extractFlightInfo(String message) {
        List<Entity> entities = new ArrayList<>();
        String lowerMessage = message.toLowerCase();

        // Pattern for "from [origin] to [destination]"
        Pattern fromToPattern = Pattern.compile(
            "from ([a-z]+(?: [a-z]+)*?) to ([a-z]+(?: [a-z]+)*?)(?:\\s+(?:today|tomorrow|yesterday|\\d{1,2}/\\d{1,2}/\\d{4})|$)",
            Pattern.CASE_INSENSITIVE
        );
        Matcher matcher = fromToPattern.matcher(lowerMessage);

        if (matcher.find()) {
            String origin = matcher.group(1);
            String destination = matcher.group(2);
            entities.add(new Entity("location", origin, "origin"));
            entities.add(new Entity("location", destination, "destination"));
        } else {
            // Fallback pattern for "to [destination]"
            Pattern toPattern = Pattern.compile(
                "to ([a-z]+(?: [a-z]+)*?)(?:\\s+(?:today|tomorrow|yesterday|\\d{1,2}/\\d{1,2}/\\d{4})|$)",
                Pattern.CASE_INSENSITIVE
            );
            matcher = toPattern.matcher(lowerMessage);

            if (matcher.find()) {
                String destination = matcher.group(1);
                entities.add(new Entity("location", destination, "destination"));
            }
        }

        // Extract date
        Pattern datePattern = Pattern.compile(
            "\\b(today|tomorrow|yesterday|\\d{1,2}/\\d{1,2}/\\d{4})\\b",
            Pattern.CASE_INSENSITIVE
        );
        matcher = datePattern.matcher(lowerMessage);

        while (matcher.find()) {
            entities.add(new Entity("date", matcher.group(), "date"));
        }

        return entities;
    }

    public static void main(String[] args) {
        String message = "I want a flight from New York to London tomorrow";
        List<Entity> entities = extractFlightInfo(message);

        System.out.println("Message: " + message);
        System.out.println("Contextual entities:");
        for (Entity entity : entities) {
            System.out.println("  " + entity);
        }
    }
}

19.5 Integration: Intents + Entities

Now let’s combine intent classification and entity extraction to build a more complete system. See also the modular version integrating IntentClassifier and EntityExtractor in MessageProcessor.java.

19.5.1 Example 4: Complete Message Processor

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

public class MessageProcessor {

    public enum Intent {
        GREETING, GOODBYE, THANKS, WEATHER_QUESTION,
        FOOD_ORDER, FLIGHT_BOOKING, UNKNOWN
    }

    public static class Entity {
        public final String type;
        public final String value;

        public Entity(String type, String value) {
            this.type = type;
            this.value = value;
        }

        @Override
        public String toString() {
            return type + "=" + value;
        }
    }

    public static class ProcessedMessage {
        public final Intent intent;
        public final List<Entity> entities;
        public final String originalMessage;

        public ProcessedMessage(Intent intent, List<Entity> entities, String originalMessage) {
            this.intent = intent;
            this.entities = entities;
            this.originalMessage = originalMessage;
        }
    }

    // Simplified intent classifier
    private static Intent classifyIntent(String message) {
        message = message.toLowerCase();

        if (message.contains("hi") || message.contains("hello") || message.contains("hey")) {
            return Intent.GREETING;
        } else if (message.contains("bye") || message.contains("goodbye") || message.contains("see you")) {
            return Intent.GOODBYE;
        } else if (message.contains("thanks") || message.contains("thank you")) {
            return Intent.THANKS;
        } else if (message.contains("weather") || message.contains("forecast")) {
            return Intent.WEATHER_QUESTION;
        } else if (message.contains("flight") || message.contains("ticket")) {
            return Intent.FLIGHT_BOOKING;
        } else if (message.contains("food") || message.contains("eat") || message.contains("pizza")) {
            return Intent.FOOD_ORDER;
        }

        return Intent.UNKNOWN;
    }

    // Simplified entity extractor
    private static List<Entity> extractEntities(String message) {
        List<Entity> entities = new ArrayList<>();

        // Locations
        Pattern locationPattern = Pattern.compile(
            "\\b(new york|london|paris|tokyo|chicago)\\b",
            Pattern.CASE_INSENSITIVE
        );
        Matcher matcher = locationPattern.matcher(message);
        while (matcher.find()) {
            entities.add(new Entity("location", matcher.group()));
        }

        // Dates
        Pattern datePattern = Pattern.compile(
            "\\b(today|tomorrow|yesterday|\\d{1,2}/\\d{1,2}/\\d{4})\\b",
            Pattern.CASE_INSENSITIVE
        );
        matcher = datePattern.matcher(message);
        while (matcher.find()) {
            entities.add(new Entity("date", matcher.group()));
        }

        // Food types
        Pattern foodPattern = Pattern.compile(
            "\\b(pizza|burger|sushi)\\b",
            Pattern.CASE_INSENSITIVE
        );
        matcher = foodPattern.matcher(message);
        while (matcher.find()) {
            entities.add(new Entity("food_type", matcher.group()));
        }

        return entities;
    }

    public static ProcessedMessage process(String message) {
        Intent intent = classifyIntent(message);
        List<Entity> entities = extractEntities(message);
        return new ProcessedMessage(intent, entities, message);
    }

    public static String generateResponse(ProcessedMessage processedMessage) {
        Intent intent = processedMessage.intent;
        List<Entity> entities = processedMessage.entities;

        switch (intent) {
            case GREETING:
                return "Hello! How can I help you today?";

            case GOODBYE:
                return "See you later! Have a great day!";

            case THANKS:
                return "You're welcome! Happy to help.";

            case WEATHER_QUESTION:
                String location = "here";
                for (Entity entity : entities) {
                    if (entity.type.equals("location")) {
                        location = entity.value;
                        break;
                    }
                }
                return String.format("The weather in %s is sunny today.", location);

            case FOOD_ORDER:
                String food = "something tasty";
                for (Entity entity : entities) {
                    if (entity.type.equals("food_type")) {
                        food = entity.value;
                        break;
                    }
                }
                return String.format("Got it! I will order a %s for you.", food);

            case FLIGHT_BOOKING:
                String origin = "origin";
                String destination = "destination";
                String date = "today";

                for (Entity entity : entities) {
                    if (entity.type.equals("location")) {
                        if (origin.equals("origin")) {
                            origin = entity.value;
                        } else {
                            destination = entity.value;
                        }
                    } else if (entity.type.equals("date")) {
                        date = entity.value;
                    }
                }
                return String.format("Okay, I will search for flights from %s to %s on %s.",
                    origin, destination, date);

            case UNKNOWN:
            default:
                return "Sorry, I didn't understand. Could you rephrase or be more specific?";
        }
    }

    public static void main(String[] args) {
        String[] messages = {
            "Hello, how are you?",
            "See you later!",
            "Thanks for your help",
            "What's the weather in New York today?",
            "I want to order a pizza",
            "I need a flight from New York to London tomorrow"
        };

        for (String message : messages) {
            System.out.println("User: " + message);
            ProcessedMessage processed = process(message);
            System.out.println("  Intent: " + processed.intent);
            System.out.println("  Entities: " + processed.entities);
            String response = generateResponse(processed);
            System.out.println("Bot: " + response);
            System.out.println();
        }
    }
}

19.6 Word Vectors and Similarity (Conceptual)

In more advanced systems, we use word embeddings (word vectors) to represent words in a multi-dimensional vector space. Words with similar meanings end up with similar vectors.

In Java, you can use libraries such as DL4J (Deep Learning for Java) or integrate with pre-trained models. For learning purposes, let’s simulate a simple vector similarity example.

19.6.1 Example 5: Word Similarity (Simplified)

import java.util.*;

public class WordSimilarity {

    // Map of words to vectors (simplified - only 3 dimensions)
    private static final Map<String, double[]> WORD_VECTORS = new HashMap<>();

    static {
        // Illustrative vectors for demonstration
        WORD_VECTORS.put("dog", new double[]{0.8, 0.2, 0.1});
        WORD_VECTORS.put("cat", new double[]{0.7, 0.3, 0.2});
        WORD_VECTORS.put("animal", new double[]{0.75, 0.25, 0.15});
        WORD_VECTORS.put("car", new double[]{0.1, 0.8, 0.3});
        WORD_VECTORS.put("bus", new double[]{0.2, 0.7, 0.4});
        WORD_VECTORS.put("vehicle", new double[]{0.15, 0.75, 0.35});
        WORD_VECTORS.put("computer", new double[]{0.3, 0.1, 0.9});
        WORD_VECTORS.put("phone", new double[]{0.4, 0.2, 0.8});
        WORD_VECTORS.put("technology", new double[]{0.35, 0.15, 0.85});
    }

    // Computes the cosine similarity between two vectors
    public static double cosineSimilarity(double[] vec1, double[] vec2) {
        double dotProduct = 0.0;
        double norm1 = 0.0;
        double norm2 = 0.0;

        for (int i = 0; i < vec1.length; i++) {
            dotProduct += vec1[i] * vec2[i];
            norm1 += Math.pow(vec1[i], 2);
            norm2 += Math.pow(vec2[i], 2);
        }

        norm1 = Math.sqrt(norm1);
        norm2 = Math.sqrt(norm2);

        if (norm1 == 0 || norm2 == 0) {
            return 0.0;
        }

        return dotProduct / (norm1 * norm2);
    }

    public static double getSimilarity(String word1, String word2) {
        double[] vec1 = WORD_VECTORS.getOrDefault(word1.toLowerCase(), new double[]{0, 0, 0});
        double[] vec2 = WORD_VECTORS.getOrDefault(word2.toLowerCase(), new double[]{0, 0, 0});

        return cosineSimilarity(vec1, vec2);
    }

    public static void main(String[] args) {
        System.out.println("Similarity between 'dog' and 'cat': " +
            getSimilarity("dog", "cat"));
        System.out.println("Similarity between 'dog' and 'animal': " +
            getSimilarity("dog", "animal"));
        System.out.println("Similarity between 'dog' and 'car': " +
            getSimilarity("dog", "car"));
        System.out.println("Similarity between 'car' and 'bus': " +
            getSimilarity("car", "bus"));
        System.out.println("Similarity between 'computer' and 'technology': " +
            getSimilarity("computer", "technology"));
    }
}

19.7 Project Evolution: Chatbot with Intents and Entities

In this chapter, we added:

  1. Intent classification using regular expressions
  2. Entity extraction with contextual patterns
  3. Integration of intents and entities to generate intelligent responses
  4. Word similarity concepts using word vectors

These features allow our chatbot to:

  • Understand what the user wants to do (intent)
  • Identify specific pieces of information (entities)
  • Reply in a much more contextually relevant way

19.8 Verifiable Practice

  1. Implement IntentClassifier with at least 5 different intents.
  2. Create EntityExtractor to recognize at least 3 entity types.
  3. Build ContextualEntityExtractor to extract entities with specific roles.
  4. Integrate everything in MessageProcessor with at least 10 test messages.
  5. (Optional) Implement WordSimilarity and test it with different pairs of words.

Completion criteria:

  • All examples compile with javac --release 21
  • The intent classifier accurately identifies intents
  • The entity extractor finds relevant information
  • The message processor produces appropriate responses
  • The code follows Java naming conventions

Before moving on

You should be able to explain:

  • What are intents and entities?
  • How do you classify intents using regular expressions?
  • How do you extract entities from a message?
  • How do you combine intents and entities to generate responses?
  • How can word similarity help improve chatbots?

19.9 Additional Resources