🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Dialogue Systems: State, Policy, and Response

Conversational NLPTask-Oriented and Open-Domain DialogueđŸŸĸ Free Lesson

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

ModuleInputOutputTypical model
Speech recognitionAudioTextEnd-to-end ASR
Intent classifierUtteranceIntent label plus confidenceFine-tuned encoder
Slot fillerUtteranceBIO tags per tokenToken classifier
Dialogue state trackerTurns so farCurrent frameRules or learned update
PolicyCurrent frameNext system actionRules, search, or RL
Knowledge baseFrame constraintsCandidate resultsSQL or vector search
Response generatorAction plus resultsSurface textTemplates or LM
Text to speechTextAudioNeural 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.

python
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.

python
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 styleStrengthsWeaknesses
Rule-based if-thenTransparent, testableBrittle outside enumerated cases
Finite-state machineGuarantees progressCannot handle unexpected slots
Slot-filling heuristicSimple, robustNo lookahead or clarification
Neural policy learned from dataHandles wide action spacesNeeds logs, may drift
Reinforcement learnedOptimises long-term rewardReward 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.

python
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

MetricWhat it measuresKnown weakness
Task success rateGoals completed end to endNeeds a simulator or user study
turns to successEfficiencyPenalises legitimate clarification
PerplexityFluencyUnrelated to correctness
BLEU against referencesn-gram overlap with one phrasingRewards surface match, not meaning
Distinct-nLexical diversityRewards noise if pushed too far
Human coherence ratingJudged plausibilityExpensive, moderate agreement
Hallucinated slot rateMade-up entitiesThe 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

Generate the action and the results in the policy layer, then have the generator realise them. A model free to phrase prices in its own words will eventually phrase one that does not exist.

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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Continue Learning

Suggested next tutorials based on this topic

Need Expert NLP Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement