Dialogue Systems
Prerequisites
- !Intent classification as a labelling task
- !How LLM prompts carry conversation history
- !Latency budgets for interactive products
What You'll Learn
- 1Separate task-oriented and open-ended dialogue by what success means
- 2Represent dialogue acts and use them to make turns machine-checkable
- 3Track slots with explicit confirmation policy for destructive actions
- 4Evaluate dialogue by task completion and recovery, not by single-turn accuracy
Two products wearing the same interface
A task-oriented system books a table, resets a password, or files a claim. Success is objective: the task completed, in how many turns, at what cost. An open-ended system â a writing companion, a tutor â is judged on the quality of the exchange itself, where there is no terminal state and the notion of "finished" is a product decision rather than a model property.
The distinction drives architecture. Task-oriented systems need state, validation, and a policy that decides when to act; their models can be small and their behaviour auditable. Open-ended systems need long-range coherence, persona stability, and safety filtering across arbitrary content; their models must be large and their behaviour is sampled rather than scripted. Bolting both onto one loop produces the familiar failure: a scripted flow that cannot improvise, or an improvising model that cannot complete a transaction reliably.
| Concern | Task-oriented | Open-ended |
|---|---|---|
| Success metric | Task completion, turns, cost | Helpfulness, coherence, safety |
| State | Explicit slots and intents | Conversation summary plus history |
| Actions | Tools with side effects | Mostly text generation |
| Failure mode | Wrong action taken | Drift, contradiction, sycophancy |
| Evaluation | Simulated users, log replay | Human preference, rubric scoring |
| Latency tolerance | Sub-second for turns | Seconds acceptable |
Most production assistants are hybrids: an open-ended front end with a task-oriented core for the transactions that carry risk. Keep the two subsystems' contracts explicit â the generative layer proposes, the task layer validates and executes â so that a fluent sentence can never by itself trigger a refund.
Dialogue acts make turns checkable
A turn is not just text; it is an act with parameters. The classic set includes inform (provide information), request (ask for a slot), confirm (verify understanding), acknowledge, reject, and apologise. Encoding acts turns a fuzzy conversation into a typed exchange that a policy can reason about and a test harness can assert on.
The practical payoff appears in three places. A response can be validated against the state: asking for a slot that is already filled is a detectable bug rather than a user annoyance. Turn-level tests become possible â assert that a reset-password flow issues exactly one confirmation act before the destructive step. And logging acts rather than raw text gives you an aggregation that is actually diagnosable: "forty percent of turns are re-prompts for the same slot" names a design flaw, while "the model said things" does not.
For LLM-driven dialogue, the same idea appears as a structured output: ask the model for an act, slots and a message, then validate the act against the current state before rendering the message. The text becomes presentation; the act becomes the contract.
Tracking state without losing the thread
State is the minimum information needed to decide the next act. For task dialogue it is a slot map plus a status per slot; getting confirmation policy right on destructive actions matters more than any natural-language flourish.
from dataclasses import dataclass, field
@dataclass
class DialogueState:
intent: str | None = None
slots: dict = field(default_factory=dict)
confirmed: set = field(default_factory=set)
pending_confirmation: str | None = None
turn: int = 0
attempts: dict = field(default_factory=dict)
VALIDATORS = {
"email": lambda v: "@" in v and "." in v.split("@")[-1],
"account_id": lambda v: v.isdigit() and len(v) == 8,
"amount": lambda v: v.replace(".", "", 1).isdigit() and float(v) > 0,
}
DESTRUCTIVE = {"reset_password", "close_account", "refund"}
def update_state(state: DialogueState, turn: dict) -> DialogueState:
"""turn: {"act": str, "slots": {name: value}, "text": str}."""
state.turn += 1
act, slots = turn.get("act", "inform"), turn.get("slots", {})
if act == "request":
state.intent = state.intent or turn.get("text", "")[:64]
for name, value in slots.items():
validator = VALIDATORS.get(name)
if validator and not validator(str(value)):
state.attempts[name] = state.attempts.get(name, 0) + 1
if state.attempts[name] >= 3:
state.slots[name] = None # stop looping; escalate instead
continue
state.slots[name] = value
state.attempts[name] = 0
if state.intent in DESTRUCTIVE:
needed = set(state.slots)
if needed and needed == state.confirmed:
state.pending_confirmation = None
elif not state.pending_confirmation:
state.pending_confirmation = "confirm_intent"
return state
def next_act(state: DialogueState) -> tuple[str, dict]:
"""Policy: validate, confirm, then execute â in that order."""
if state.pending_confirmation == "confirm_intent":
return "confirm", {"intent": state.intent, "slots": dict(state.slots)}
missing = [s for s in ("email", "account_id") if state.slots.get(s) is None]
if state.intent in DESTRUCTIVE and state.confirmed != set(state.slots):
return "confirm", {"intent": state.intent, "slots": dict(state.slots)}
if missing:
return "request", {"slot": missing[0]}
return "execute", {"intent": state.intent, "slots": dict(state.slots)}
Two policy rules earn their complexity. Destructive intents never execute on first fill â they confirm intent and values together, in one turn, rather than asking "are you sure?" three times. And repeated validation failures escalate after a bounded number of attempts: the third bad account number ends the loop and routes to a human, because a bot that asks four times for the same field is a churn machine.
Context management: what deserves a place in the window
Every turn adds tokens, and naively appending history exhausts the window while degrading instruction-following long before the limit arrives. What goes in must therefore be chosen, not accumulated.
Keep the current instruction and the last few turns verbatim â recency carries conversational reference like "the second one". Compress the middle: a rolling summary of earlier turns that records decisions, entities and commitments, written whenever the summary drifts from the recent exchange. And retrieve specific turns on demand when a later question depends on them â "what did I say the address was" should fetch that turn rather than rely on the model having noticed it in a truncated history.
Three failure signatures tell you which piece is missing. The system contradicts an early decision: the summary dropped it. The system misresolves a pronoun: the recent window was truncated too aggressively. The system answers "I don't see that in our conversation": retrieval did not fire. Treat context management as a subsystem with its own tests rather than as string concatenation.
â ī¸Summaries are lossy, so keep the commitments verbatim
Dates, amounts, IDs and anything the user agreed to must survive compression byte-for-byte. A summary that paraphrases a booking date into "next week" hands the model room to invent one.
A small window assembler makes those rules explicit and testable:
import re
COMMITMENT = re.compile(
r"\b(\d{1,2}[/-]\d{1,2}[/-]\d{2,4}|\$\s?\d+(?:\.\d+)?|"
r"\b\d{8}\b|#[A-Z]{2,}\d+)\b",
re.IGNORECASE,
)
def build_window(history: list[dict], summary: str, max_tokens: int = 4000,
est_tokens_per_turn: int = 60) -> list[dict]:
"""Verbatim recent turns, summarised middle, commitments preserved."""
recent_budget = max_tokens // 3
keep = max(1, recent_budget // est_tokens_per_turn)
recent = history[-keep:]
older = history[:-keep]
commitments = []
for turn in older:
for match in COMMITMENT.findall(turn["text"]):
commitments.append(f"{turn['role']}: {match}")
messages = []
if summary or commitments:
preface = "Earlier context: " + (summary or "").strip()
if commitments:
preface += " | Values stated earlier: " + "; ".join(commitments)
messages.append({"role": "system", "content": preface[:1500]})
messages.extend(recent)
return messages
transcript = [
{"role": "user", "text": "Move $250.00 to account 12345678 on 12/04"},
{"role": "assistant", "text": "Which account should receive it?"},
{"role": "user", "text": "The savings account ending 4410"},
]
print(len(build_window(transcript, "User asked to schedule a transfer", 60)))
The commitment regex is intentionally crude: its job is to pin literal values into the preface even after the original turns age out of the window, so a later "confirm 12/04" refers to a real date rather than a plausible one.
Recovery is where dialogue systems are judged
Users do not fail politely. They correct, repeat, change their mind mid-task, and answer questions that were never asked. The system's response to being wrong defines the experience more than its first-attempt accuracy.
The repair toolkit is small and worth implementing deliberately. Clarification asks a targeted question when intent confidence is low, constrained to the decision that would actually change the next act â asking about everything is a cross-examination. Confirmation restates what was understood before an irreversible step. Repair after error accepts the correction as an explicit act, discards the affected slot rather than patching it, and avoids re-asking slots the user has already supplied. Graceful degradation moves to a human or a fallback flow when attempts exceed a threshold, carrying the state so the user does not restart.
Track how often each path fires. A healthy task-oriented system sees clarification on a small, stable share of turns; a rising repair rate means the intent model or the prompts drifted, which users experience first as the bot "getting dumber" and abandon before your metrics move.
Evaluating dialogue honestly
Single-turn accuracy describes almost nothing about a conversation. Task completion rate â did the user reach the goal at all â plus turns to completion and intervention rate describe most of it, and all three can be measured with a simulated-user harness that replays scenarios against your policy.
Build that harness early: a script of user goals, a simulator that follows them with realistic typos and digressions, and assertions on the resulting transcript â the confirmation act fired, the right tool was called with the right arguments, no forbidden action occurred. Add human review for the open-ended dimension, scored with a rubric rather than a vibe: correctness of facts, coherence with prior turns, and appropriateness of tone. Finally, mine real transcripts for the two logs that pay for themselves â turns where the user repeated themselves, and turns where the user went silent. Both mark the exact points where understanding broke, and neither requires anyone to sit in a lab.
Common Mistakes
Letting a generated sentence trigger a destructive action
Fix: Route execution through a validating policy that checks slots and confirmation, never through the text layer
Appending full history until the context window fills
Fix: Combine verbatim recent turns, a commitment-preserving summary and on-demand retrieval of older turns
Re-asking for a slot the user already gave you
Fix: Update state from every act and clear the affected slot entirely when the user corrects it
Evaluating with single-turn accuracy
Fix: Measure task completion, turns to completion and intervention rate with a simulated-user harness
Best Practices
- Separate the act contract from the message so tests can assert on behaviour
- Confirm once, properly, before irreversible actions â and never three times in a row
- Bound retries per slot and escalate to a human with state attached
- Summarize with verbatim commitments: IDs, dates and amounts survive compression unchanged
- Log acts, repairs and silent drop-offs; those three series diagnose most dialogue regressions
Key Takeaways
- Task-oriented and open-ended dialogue share an interface but not an architecture, a metric or a failure mode
- Dialogue acts turn conversation into a typed exchange you can validate, test and aggregate
- Confirmation policy and bounded retries on destructive actions matter more than phrasing quality
- Context must be curated â verbatim recency, commitment-safe summary, retrieval on demand
- Evaluate with simulated users on completion and turns, and mine repair and silence logs for real regressions