Create a Python chatbot with spaCy that does intent classification and named entity recognition. It needs to handle cases where users provide multiple entities in one sentence like "Book a flight from NY to London and a hotel in Paris" and map them to structured JSON.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I'm designing a Python class using spaCy's NER and Matcher to detect multiple travel-related intents—like booking flights and hotels—in one sentence, extracting entities into structured JSON. The approach uses rule-based patterns to identify intents and their parameters, handling complex utterances with multiple entities.
Below is a minimal, self‑contained example of how you could wire up spaCy to do both intent classification (via simple pattern rules for this demo) and named entity recognition, including handling multiple “micro‑intents” in a single utterance. It looks for “book flight from X to Y” and “book/reserve hotel in Z,” and maps what it finds into structured JSON.
python
"""
Minimal spaCy chatbot demo for:
- Intent classification (rule-based for this example)
- Named entity recognition (using spaCy's pre-trained NER)
- Handling multiple entities/intents in one sentence
Before running:
pip install spacy
python -m spacy download en_core_web_sm
"""
import spacy
from spacy.matcher import Matcher
class TravelChatbot:
def __init__(self):
self.nlp = spacy.load("en_core_web_sm")
# Define some simple rule-based patterns for "intents"
self.matcher = Matcher(self.nlp.vocab)
# Pattern: "book a flight from <GPE> to <GPE>"
flight_pattern = [
{"LEMMA": {"IN": ["book", "reserve"]}, "OP": "*"},
{"LOWER": {"IN": ["a", "the"]}, "OP": "?"},
{"LOWER": "flight", "OP": "?"},
{"LOWER": "from"},
{"ENT_TYPE": "GPE"},
{"LOWER": "to"},
{"ENT_TYPE": "GPE"},
]
# Pattern: "book a hotel in <GPE>"
hotel_pattern = [
{"LEMMA": {"IN": ["book", "reserve"]}, "OP": "*"},
{"LOWER": {"IN": ["a", "the"]}, "OP": "?"},
{"LOWER": "hotel"},
{"LOWER": "in"},
{"ENT_TYPE": "GPE"},
]
self.matcher.add("BOOK_FLIGHT", [flight_pattern])
self.matcher.add("BOOK_HOTEL", [hotel_pattern])
def parse(self, text: str):
doc = self.nlp(text)
matches = self.matcher(doc)
intents = []
# Sort matches to process in order of appearance
matches = sorted(matches, key=lambda m: m[1])
for match_id, start, end in matches:
span = doc[start:end]
intent_label = self.nlp.vocab.strings[match_id]
if intent_label == "BOOK_FLIGHT":
origin = None
destination = None
# Extract the two GPE entities in order within the span
gpes = [ent.text for ent in span.ents if ent.label_ == "GPE"]
if len(gpes) >= 2:
origin, destination = gpes[0], gpes[1]
intents.append({
"type": "book_flight",
"origin": origin,
"destination": destination,
"text_span": span.text,
})
elif intent_label == "BOOK_HOTEL":
location = None
gpes = [ent.text for ent in span.ents if ent.label_ == "GPE"]
if gpes:
location = gpes[0]
intents.append({
"type": "book_hotel",
"location": location,
"text_span": span.text,
})
# If no rule-based intent was found, fall back to a generic “unknown”
if not intents:
intents.append({"type": "unknown", "entities": [
{"text": ent.text, "label": ent.label_} for ent in doc.ents
]})
return {
"text": text,
"intents": intents,
"entities": [{"text": ent.text, "label": ent.label_} for ent in doc.ents],
}
if __name__ == "__main__":
bot = TravelChatbot()
examples = [
"Book a flight from NY to London and a hotel in Paris",
"I need to reserve a hotel in Madrid",
"Can you book a flight from Berlin to Tokyo?",
"hello there"
]
for ex in examples:
parsed = bot.parse(ex)
print(f"USER: {ex}")
print("STRUCTURED JSON:", parsed)
print("-" * 60)
How it works
We load spaCy’s small English model for NER (en_core_web_sm).
We set up two rule-based Matcher patterns to detect “book flight from X to Y” and “book hotel in Z.” These patterns also include optional words to make them a bit more robust.
The parse method runs spaCy, applies the patterns, and for each match, extracts relevant GPE (Geo‑Political Entity) spans from the matched text. This yields a list of “micro‑intents” (e.g., one for the flight and one for the hotel in a single utterance).
We return a JSON‑like dict containing the original text, the intents detected, and all entities spaCy recognized.
In a production system you would likely:
Train a text classification component (TextCategorizer) for robust intent detection,
Expand your pattern coverage and slot extraction,
Maintain conversation state to confirm dates, times, etc.