Dialogue Acts and Conversation Structure › Code Implementation
Language AI HandbookAll chapters The following Python example uses a fixed transcript and hand-labeled inputs. It can run on a CPU without a public corpus or a model endpoint. The slot extractor deliberately supports a restricted set of English words and patterns so that you can follow its behavior by hand.
Setup and data structures
We define the absent marker and a record with the turn ID, speaker, text, annotated reply target, and toy act label.
PythonIn [3]Expand
import re
from dataclasses import dataclass
from typing import Optional
ABSENT = "<absent>"
SLOTS = ("day", "time", "size", "room")
BOOKING_PARTICIPANTS = frozenset({"A", "B"})
@dataclass
class Turn:
turn_id: int
speaker: str
text: str
reply_to: Optional[int] = None
act: Optional[str] = NoneThe record stores the same fields for all ten turns. In this experiment an annotator supplies the act and reply fields. The absent marker identifies slots that lack a value.
The dialogue
We encode the ten-turn dialogue as a list of Turn objects.
PythonIn [4]Expand
dialogue = [
Turn(
1, "A", "Can I book a study room for Thursday at 3pm?", None, "request"
),
Turn(2, "B", "Do you need a small room or a large room?", 1, "clarify"),
Turn(3, "A", "The first one, please.", 2, "inform"),
Turn(4, "B", "Room 204 is free then.", 1, "offer"),
Turn(5, "A", "Great, book it.", 4, "accept"),
Turn(6, "C", "Sorry, is 204 free at 4pm too?", 4, "question"),
Turn(7, "B", "No, 204 is booked at 4.", 6, "answer"),
Turn(8, "B", "Actually, 204 is taken at 3. How about 205?", 4, "repair"),
Turn(9, "A", "That works, thanks.", 8, "accept"),
Turn(10, "B", "Booked.", 9, "acknowledge"),
]ConsoleOut [5]Expand
[1] A (request): Can I book a study room for Thursday at 3pm? [2] B (clarify) -> turn 1: Do you need a small room or a large room? [3] A (inform) -> turn 2: The first one, please. [4] B (offer) -> turn 1: Room 204 is free then. [5] A (accept) -> turn 4: Great, book it. [6] C (question) -> turn 4: Sorry, is 204 free at 4pm too? [7] B (answer) -> turn 6: No, 204 is booked at 4. [8] B (repair) -> turn 4: Actually, 204 is taken at 3. How about 205? [9] A (accept) -> turn 8: That works, thanks. [10] B (acknowledge) -> turn 9: Booked.
The printout confirms the structure: each turn has a speaker, an act, and (except for the first) a reply-to link. The reply_to values encode the graph described earlier. The act labels encode the small inventory. Both are inputs in this example.
Slot extraction
We define a context-free slot extractor. It scans the text for day names, times with am/pm, size adjectives, and three-digit room numbers. The time pattern also matches strings such as 99:99pm. It removes ordinary spaces from a match and leaves other whitespace intact.
PythonIn [6]Expand
def extract_slots(text):
"""Context-free slot extraction: scan the utterance in isolation."""
slots = {}
for day in ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]:
if day.lower() in text.lower():
slots["day"] = day
m = re.search(r"\b(\d{1,2}(?::\d{2})?\s*(?:am|pm))\b", text, re.I)
if m:
slots["time"] = m.group(1).lower().replace(" ", "")
for size in ["small", "medium", "large"]:
if re.search(rf"\b{size}\b", text, re.I):
slots["size"] = size
m = re.search(r"\b(\d{3})\b", text)
if m:
slots["room"] = m.group(1)
return slotsThe extractor returns a dictionary containing the fields it recognizes in the current message. It leaves unmatched fields out of the returned dictionary. The tracker decides what to do with those omissions.
Context-free tracker
The context-free tracker applies the extractor to each turn and overwrites the state.
PythonIn [7]Expand
def track_context_free(dialogue):
state = {s: ABSENT for s in SLOTS}
history = []
for turn in dialogue:
for k, v in extract_slots(turn.text).items():
state[k] = v
history.append(dict(state))
return state, historyThe tracker returns both the final state and the state after each turn. The history is useful for visualization and debugging. The history is a list of copies, so later updates do not mutate earlier snapshots. That matters if we want to inspect where the tracker went wrong.
Conversation membership
We define a function that determines which turns belong to the booking conversation. A turn belongs if its speaker is A or B and its reply-to chain stays within the conversation.
PythonIn [8]Expand
def conversation_membership(dialogue, participants):
in_conv = {}
for turn in dialogue:
if turn.speaker not in participants:
in_conv[turn.turn_id] = False
elif turn.reply_to is None:
in_conv[turn.turn_id] = True
else:
in_conv[turn.turn_id] = in_conv.get(turn.reply_to, False)
return in_convThe function visits parents before their replies. Turn 6 is written by Cleo, who is outside the pair. Turn 7 is written by Ben and inherits the exclusion of turn 6. The rule assumes unique turn IDs and a transcript in which each reply target appears earlier.
Context-aware tracker
The context-aware tracker uses conversation membership, reply-to routing, and repair replacement.
PythonIn [9]Expand
def linked_choice(turn, by_id):
"""Read 'first one' or 'second one' against a linked size question."""
if turn.act != "inform" or turn.reply_to is None:
return {}
question = by_id[turn.reply_to]
if question.act != "clarify":
return {}
match = re.search(r"\b(first|second)\s+one\b", turn.text, re.I)
options = re.findall(r"\b(?:small|medium|large)\b", question.text.lower())
if match and len(options) == 2:
position = {"first": 0, "second": 1}[match.group(1).lower()]
return {"size": options[position]}
return {}We route the short answer before applying updates. The helper reads the options in their order in the antecedent. A repeated option or a more complex answer would need a richer parser. When calling linked_choice directly on an inform turn with a reply link, include the target in by_id. The tracker checks membership first, which excludes replies with missing targets. It preserves the old state when a turn supplies no update.
PythonIn [10]Expand
def track_context_aware(dialogue):
state = dict.fromkeys(SLOTS, ABSENT)
history = []
by_id = {turn.turn_id: turn for turn in dialogue}
in_conv = conversation_membership(dialogue, BOOKING_PARTICIPANTS)
for turn in dialogue:
if in_conv[turn.turn_id] and turn.act in {
"request",
"inform",
"offer",
"repair",
}:
updates = extract_slots(turn.text)
updates.update(linked_choice(turn, by_id))
if turn.act == "repair":
rooms = re.findall(r"\b(\d{3})\b", turn.text)
if rooms:
updates["room"] = rooms[-1]
state.update(updates)
history.append(dict(state))
return state, historyAt turn 3 the helper uses the link to turn 2 and reads 'small' as the first offered size. At turn 8 the room pattern finds both 204 and 205. The repair rule uses the last match because this transcript puts the replacement last. It is a parser for the fixture's wording. An arbitrary correction could name the candidate first or mention more than two rooms.
Evaluation
We define the gold state and compute the metrics.
PythonIn [11]Expand
gold = {"day": "Thursday", "time": "3pm", "size": "small", "room": "205"}
cf_state, cf_hist = track_context_free(dialogue)
ca_state, ca_hist = track_context_aware(dialogue)
def joint_match(pred, gold):
return int(all(pred[s] == gold[s] for s in SLOTS))
def per_slot(pred, gold):
return {s: int(pred[s] == gold[s]) for s in SLOTS}ConsoleOut [12]Expand
Gold: {'day': 'Thursday', 'time': '3pm', 'size': 'small', 'room': '205'}
Context-free: {'day': 'Thursday', 'time': '4pm', 'size': 'large', 'room': '204'}
Context-aware: {'day': 'Thursday', 'time': '3pm', 'size': 'small', 'room': '205'}
Joint match (context-free): 0
Joint match (context-aware): 1
Per-slot (context-free): {'day': 1, 'time': 0, 'size': 0, 'room': 0}
Per-slot (context-aware): {'day': 1, 'time': 1, 'size': 1, 'room': 1}The context-free tracker gets the day right. It leaves 'large' in the size slot after the clarification, adopts 4pm from Cleo's question, and keeps 204 after the retraction. It matches one of four final values, so its joint match is 0. The context-aware tracker matches all four and its joint match is 1. This is one conversation with oracle labels and links.
The heatmap compares each snapshot to the hand-labeled state for that prefix. We write the expected changes directly from the dialogue. A missing value is marked ABS even when it is expected at that point. The initial candidate 204 is a match from turn 4 through turn 7. It becomes stale when turn 8 proposes room 205.
VisualizationOut [14]Expand

Visualizing the reply-to structure
The reply-to graph shows how turns are linked. The side thread from Cleo hangs off turn 4 but does not belong to the booking conversation.
VisualizationOut [15]Expand

Turn 6 links to turn 4, and turn 7 links to turn 6. The toy membership rule excludes both from the booking state. Ben appears in both threads, which is why the rule also reads the parent rather than looking only at the current speaker.
Visualizing final slot matches
Each bar records a single slot's final match indicator. The aggregate fraction across slots is reported above.
VisualizationOut [16]Expand

The four bar pairs show one binary match per tracker and slot. The context-free tracker matches only the day. The context-aware tracker matches every slot under the supplied annotations.
Next-speaker prediction
The next-speaker baseline uses the two participant pairs. It derives booking membership from the supplied speakers and reply links, then predicts the other participant in the corresponding pair. We score the predictions against the next post in the full channel. The fixture yields nine scored positions because turn 10 has no observed successor.
PythonIn [17]Expand
def predict_next_speaker(dialogue):
in_conv = conversation_membership(dialogue, BOOKING_PARTICIPANTS)
predictions = []
for i, turn in enumerate(dialogue[:-1]):
nxt = dialogue[i + 1]
if in_conv[turn.turn_id]:
# predict the other participant in the booking conversation
other = "B" if turn.speaker == "A" else "A"
predictions.append((turn.turn_id, other, nxt.speaker))
else:
# predict the other participant in the side thread
other = "B" if turn.speaker == "C" else "C"
predictions.append((turn.turn_id, other, nxt.speaker))
return predictionsConsoleOut [18]Expand
Next-speaker accuracy: 7/9 = 0.78 after turn 1: predicted B, actual B [OK] after turn 2: predicted A, actual A [OK] after turn 3: predicted B, actual B [OK] after turn 4: predicted A, actual A [OK] after turn 5: predicted B, actual C [MISS] after turn 6: predicted B, actual B [OK] after turn 7: predicted C, actual B [MISS] after turn 8: predicted A, actual A [OK] after turn 9: predicted B, actual B [OK]
The baseline matches seven of the nine full-channel transitions. It misses when Cleo starts the side inquiry after turn 5 and when Ben returns to the booking thread after turn 7. If the target is instead the next message within each thread, the alternation rule matches all eight observed within-thread transitions in this fixture.
The chart marks each predicted and observed next speaker, making the two misses visible among the nine trials.
VisualizationOut [20]Expand

Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!