Two families that share a name
A dialogue system that books a flight and a chatbot that discusses films are both called conversational agents, and almost nothing about how they are built or evaluated is shared. Task-oriented systems have a defined success condition â the booking completed, the refund issued â and are therefore measurable against an objective, which makes them amenable to supervised learning, deterministic policies, and regression tests. Open-domain systems have no success condition beyond the user continuing to talk, which makes them generative modelling problems where fluency and engagement stand in for correctness and where the failure modes are hallucination and drift rather than a failed database query.
Collapsing the two leads to bad architecture decisions in both directions. Bolt a large language model onto a booking flow and you inherit hallucinated prices with no way to test for them. Bolt a slot-filling pipeline onto small talk and users hit a wall the moment they say anything off-script. Most production systems are therefore hybrids: a task-oriented core for anything with a database consequence, a generative layer for small talk and apology, and a router that decides which is active on each turn.
This lesson builds the task-oriented stack first, then the open-domain one, and finishes with the evaluation problem that makes both harder than their supervised-learning counterparts suggest.
The pipeline, module by module
| Module | Input | Output | Typical model |
|---|---|---|---|
| Speech recognition | Audio | Text | End-to-end ASR |
| Intent classifier | Utterance | Intent label plus confidence | Fine-tuned encoder |
| Slot filler | Utterance | BIO tags per token | Token classifier |
| Dialogue state tracker | Turns so far | Current frame | Rules or learned update |
| Policy | Current frame | Next system action | Rules, search, or RL |
| Knowledge base | Frame constraints | Candidate results | SQL or vector search |
| Response generator | Action plus results | Surface text | Templates or LM |
| Text to speech | Text | Audio | Neural TTS |
The boundaries matter more than the models. A policy that emits request(price_range) rather than a sentence keeps the decision about what to do separate from the decision about how to say it, which means the same policy works unchanged whether the surface realiser is a template, a rule-based generator, or a language model â and it remains testable without any generation in the loop.
Joint intent classification and slot filling
Intent is a sentence-level label; slots are token-level labels; and the two interact, because knowing the intent narrows the plausible slot vocabulary. Most modern systems therefore share a single encoder and attach two heads, which lets the token representations carry information in both directions.
import torch
import torch.nn as nn
from transformers import AutoModel
class JointModel(nn.Module):
def __init__(self, name="distilbert-base-uncased",
intents=8, slots=12, dropout=0.1):
super().__init__()
self.encoder = AutoModel.from_pretrained(name)
d = self.encoder.config.hidden_size
self.drop = nn.Dropout(dropout)
self.intent_head = nn.Linear(d, intents)
self.slot_head = nn.Linear(d, slots)
def forward(self, input_ids, attention_mask):
h = self.encoder(input_ids=input_ids,
attention_mask=attention_mask).last_hidden_state
h = self.drop(h)
intent_logits = self.intent_head(h[:, 0, :]) # CLS for sentence label
slot_logits = self.slot_head(h) # per token
return intent_logits, slot_logits
def loss_fn(intent_logits, slot_logits, intent_y, slot_y, ignore_index=-100):
intent_loss = nn.functional.cross_entropy(intent_logits, intent_y)
slot_loss = nn.functional.cross_entropy(
slot_logits.view(-1, slot_logits.size(-1)),
slot_y.view(-1), ignore_index=ignore_index)
return intent_loss + slot_loss
Two training details decide whether this beats two separate models. Padding positions must be masked in the slot loss via ignore_index, or the model spends its capacity predicting O for pad tokens. And a joint loss weight â typically the intent term down-weighted relative to slots, since slots dominate in token count â is worth tuning rather than assuming the default 1:1 ratio is right.
State tracking that survives ellipsis
Users rarely restate their constraints. They say a city, then a date, then something cheap, then yes, that one, and the system must carry every earlier constraint forward while updating only what changed. That accumulation is the dialogue state, and the tracker is the component responsible for it.
from dataclasses import dataclass, field
from typing import Any
@dataclass
class Frame:
intent: str | None = None
slots: dict[str, Any] = field(default_factory=dict)
offered: list[dict] = field(default_factory=list)
turn: int = 0
class RuleTracker:
def __init__(self):
self.state = Frame()
def update(self, utterance: str) -> Frame:
text = utterance.lower()
self.state.turn += 1
if "book" in text or "reserve" in text:
self.state.intent = "book"
elif "show" in text or "find" in text:
self.state.intent = "search"
for cue, slot in [("london", "city"), ("paris", "city"),
("tomorrow", "date"), ("friday", "date"),
("cheap", "price"), ("luxury", "price")]:
if cue in text:
self.state.slots[slot] = cue
if "yes" in text and self.state.offered:
self.state.intent = "confirm"
return self.state
def required_slot(self) -> str | None:
needed = {"book": ["city", "date", "price"],
"search": ["city", "price"]}.get(self.state.intent, [])
return next((s for s in needed if s not in self.state.slots), None)
tracker = RuleTracker()
for turn in ["show me hotels in london", "something cheap",
"for tomorrow", "yes that one"]:
st = tracker.update(turn)
print(turn, "->", st.intent, st.slots, "ask next:", tracker.required_slot())
The required_slot computation is the part most toy implementations skip, and it is what makes the system proactive. Without it the bot waits to be told; with it the bot asks the one question that unblocks the transaction, which is the behaviour users actually experience as competence.
Policy as an explicit decision layer
Given a frame, the policy selects the next action. Hand-written policies remain common and defensible for narrow domains, because they are exhaustive, testable, and free of the distribution-shift surprises a learned policy brings. Learned policies earn their place when the action space is large or the optimal strategy is hard to enumerate.
| Policy style | Strengths | Weaknesses |
|---|---|---|
| Rule-based if-then | Transparent, testable | Brittle outside enumerated cases |
| Finite-state machine | Guarantees progress | Cannot handle unexpected slots |
| Slot-filling heuristic | Simple, robust | No lookahead or clarification |
| Neural policy learned from data | Handles wide action spaces | Needs logs, may drift |
| Reinforcement learned | Optimises long-term reward | Reward design is hard, unsafe to ship |
A pragmatic design is a rule-based policy with an explicit fallback: when the frame is incomplete the system requests a slot; when the frame is complete it queries and offers; when confidence falls below a threshold it asks a clarifying question rather than guessing. That fallback is also where you log, and those logs are the training data for any learned policy you later adopt.
Open-domain generation
Open-domain systems throw away the frame and generate the next utterance directly from the dialogue history. The engineering shifts from state tracking to context management and sampling control: the history must be truncated or summarised to fit the context window, and decoding parameters must be tuned to balance variety against coherence.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
class OpenDomainBot:
def __init__(self, name="microsoft/DialoGPT-medium", max_hist=4):
self.tok = AutoTokenizer.from_pretrained(name)
self.tok.pad_token = self.tok.eos_token
self.model = AutoModelForCausalLM.from_pretrained(name)
self.max_hist = max_hist
self.history = None
def respond(self, user_text, top_p=0.9, temperature=0.8):
new_ids = self.tok.encode(user_text + self.tok.eos_token,
return_tensors="pt")
ids = torch.cat([self.history, new_ids], dim=-1) if self.history is not None else new_ids
if ids.size(-1) > 512:
ids = ids[:, -512:]
out = self.model.generate(
ids, max_new_tokens=60, do_sample=True,
top_p=top_p, temperature=temperature,
pad_token_id=self.tok.eos_token_id,
no_repeat_ngram_size=3)
reply = self.tok.decode(out[0, ids.size(-1):], skip_special_tokens=True)
self.history = out
return reply
bot = OpenDomainBot()
for turn in ["hi there", "i had a rough day", "yeah the meeting ran long"]:
print("user:", turn)
print("bot: ", bot.respond(turn))
The no_repeat_ngram_size argument is the cheapest available defence against the classic degeneration loop where a model repeats the same phrase indefinitely, and capping history length is what keeps latency bounded across a long session. Neither addresses factual grounding â a generative bot that states a price is asserting something no decoder setting can verify, which is exactly why the task-oriented core exists.
Evaluation is weaker here than elsewhere
| Metric | What it measures | Known weakness |
|---|---|---|
| Task success rate | Goals completed end to end | Needs a simulator or user study |
| turns to success | Efficiency | Penalises legitimate clarification |
| Perplexity | Fluency | Unrelated to correctness |
| BLEU against references | n-gram overlap with one phrasing | Rewards surface match, not meaning |
| Distinct-n | Lexical diversity | Rewards noise if pushed too far |
| Human coherence rating | Judged plausibility | Expensive, moderate agreement |
| Hallucinated slot rate | Made-up entities | The metric that actually matters |
The row that deserves attention is the last one. A task-oriented bot that invents a hotel name has failed completely, and no automatic fluency metric will catch it. Instrumenting the generator to assert that every entity it emits came from the knowledge base result set converts a qualitative worry into a countable regression test.
â ī¸Never let a generative model state a database fact
Common Mistakes
Letting the response generator decide what the system does next
Fix: Keep policy and realisation separate so the action layer stays testable without generation in the loop.
Evaluating a dialogue system with BLEU alone
Fix: BLEU measures surface overlap with one reference phrasing; report task success and hallucinated-entity rate alongside.
Forgetting padding positions in the joint slot loss
Fix: Mask them with ignore_index, otherwise the model optimises predictions for pad tokens.
Shipping a learned policy without a rule-based fallback
Fix: Keep an explicit fallback for low-confidence states; it is also where you log the data the learned policy will need.
Best Practices
- Separate policy from surface realisation so the same decision layer serves any generator
- Implement required-slot computation explicitly so the bot asks the unblocking question
- Assert at generation time that every entity emitted appears in the knowledge base result
- Log every turn with the frame, action, and confidence â that log is your future training set
Interview Questions
Q1: What distinguishes a task-oriented dialogue system from an open-domain one?
Task-oriented systems have a measurable success condition tracked in an explicit dialogue state, while open-domain systems have no objective beyond engagement and are therefore generative modelling problems.
Q2: Why keep the policy separate from response generation?
So the action decision remains deterministic, testable, and reusable across surface realisers, and so a generative model can never invent a database fact.
Q3: How do you handle ellipsis like 'something cheap' after a city was mentioned?
The state tracker accumulates slots across turns, so new utterances update only the slots they mention while earlier constraints persist in the frame.
Key Takeaways
- Task-oriented and open-domain systems need different architectures and different metrics
- Joint intent and slot models share an encoder and outperform two separate models when losses are weighted properly
- Dialogue state tracking is what makes an assistant feel competent, because users rarely restate constraints
- Policy must stay separate from realisation to remain testable
- Hallucinated entities are the failure that matters most, and they are caught by assertion, not by BLEU