Spaces:
Runtime error

File size: 9,658 Bytes
64fb1e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93117c2
64fb1e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
"""
Layer 1, Step 2: Conversational directive detection.
Runs BEFORE intent router. When workflow is active and a directive resolves,
the intent router is skipped β€” the Workflow Engine handles the directive directly.
"""
from dataclasses import dataclass
from enum import Enum
import re
import logging

logger = logging.getLogger(__name__)

DIRECTIVE_CONFIDENCE_THRESHOLD = 0.75


class ConversationalDirective(Enum):
    CONFIRM          = "confirm"          # "yes", "go ahead", "do it"
    CANCEL_PENDING   = "cancel_pending"   # "no", "wait", "never mind", "stop"
    REPEAT           = "repeat"           # "what?", "say that again", "pardon"
    CLARIFY          = "clarify"          # "what do you mean", "I don't understand"
    INTERRUPT        = "interrupt"        # barge-in (VAD handles audio; this handles text)
    CORRECT          = "correct"          # "no I said", "I meant", "actually it's"
    ESCALATE         = "escalate"         # "human", "agent", "manager", "talk to someone"
    REPAIR           = "repair"           # "no I meant X", "that's not what I asked"
    ACKNOWLEDGEMENT  = "acknowledgement"  # "got it", "makes sense", "okay cool"
    NONE             = "none"


@dataclass
class DirectiveResult:
    directive: ConversationalDirective
    confidence: float


# Pattern sets β€” order matters; first match wins for overlapping patterns
_CONFIRM_PATTERNS = [
    r'\byes\b', r'\byep\b', r'\bgo ahead\b', r'\bdo it\b', r'\bconfirm\b',
    r'\bthat\'s right\b', r'\bcorrect\b', r'\bright\b', r'\bsure\b',
    r'\bplease do\b', r'\bproceed\b', r'\bokay\b', r'\bok\b',
]
_CANCEL_PATTERNS = [
    r'\bno\b', r'\bnope\b', r'\bnever mind\b', r'\bnevermind\b',
    r'\bcancel that\b', r'\bforget it\b', r'\bstop\b', r'\bwait\b',
    r'\bdon\'t\b', r'\bdont\b', r'\bhold on\b', r'\bnot now\b',
    r'\bactually no\b',
]
_REPEAT_PATTERNS = [
    r'\bwhat\?\b', r'\bpardon\b', r'\bsay that again\b', r'\brepeat\b',
    r'\bwhat did you say\b', r'\bcan you repeat\b', r'\bsay again\b',
]
_CLARIFY_PATTERNS = [
    r'\bwhat do you mean\b', r'\bi don\'t understand\b', r'\bconfused\b',
    r'\bwhat are you talking about\b', r'\bhuh\b', r'\bi\'m not sure what\b',
    r'\bexplain that\b',
    # r'\bwhat\b' removed β€” matches every question ("what is wavvy" β†’ false CLARIFY)
]
_CORRECT_PATTERNS = [
    r'\bno i said\b', r'\bi meant\b', r'\bactually it\'s\b', r'\bactually\b',
    r'\bi mean\b', r'\bno not\b', r'\bI said\b',
]
_ESCALATE_PATTERNS = [
    r'\bhuman\b', r'\bagent\b', r'\bmanager\b', r'\badmin\b',
    r'\breal person\b', r'\btalk to\b', r'\bspeak to\b',
    r'\bconnect me\b', r'\bconnect me with\b',
    r'\btransfer\b', r'\brepresentative\b', r'\bcustomer support\b',
    r'\boperator\b', r'\bsomeone else\b', r'\banother person\b',
    r'\blet me talk\b', r'\bi want a human\b', r'\bi need a human\b',
    r'\bget me a person\b', r'\bget me a human\b', r'\bget me someone\b',
    r'\bput me through\b',
    r'\bwith someone\b', r'\bwith a person\b',
]

# REPAIR β€” user correcting a misunderstood or wrong previous response.
# Detected BEFORE ESCALATE so "no I meant support pricing" doesn't become ESCALATE.
# Pattern: explicit correction marker followed by clarification content.
_REPAIR_PATTERNS = [
    r'\bno[,\s]+(?:i\s+meant|that\'?s\s+not|i\s+said)\b',
    r'\bactually[,\s]+(?:i\s+meant|i\s+wanted|i\s+was\s+asking)\b',
    r'\bwait[,\s]+(?:i\s+meant|that\'?s\s+wrong|no)\b',
    r'\bthat(?:\'s|\s+is)\s+not\s+what\s+i\s+(?:said|meant|asked)\b',
    r'\bsorry[,\s]+i\s+meant\b',
    r'\bno[,\s]+not\s+that\b',
    r'\bi\s+(?:don\'?t|didn\'?t)\s+(?:want|mean|say)\s+(?:a\s+)?demo\b',
]

# REPAIR uses a lower threshold β€” patterns are long and precise; one match is strong evidence.
_REPAIR_CONFIDENCE_THRESHOLD = 0.65

# CANCEL β€” bare single/two-word cancellation utterances.
# After normalization "no stop" β†’ "no" (denial map), so "no" alone must cancel at threshold.
# Pattern-based CANCEL handles multi-word phrases ("no cancel that", "never mind").
_CANCEL_UTTERANCES = frozenset([
    "no", "nope", "nah", "stop", "cancel", "abort",
    "never mind", "nevermind", "forget it", "hold on",
])

# CONFIRM β€” bare single/two-word utterances that are unambiguous confirmations.
# Checked as whole-utterance exact matches (after normalization) at high confidence.
# Pattern-based CONFIRM catches longer phrases ("yes please go ahead", "go ahead").
_CONFIRM_UTTERANCES = frozenset([
    "yes", "yep", "yup", "yeah", "sure", "go ahead",
    "do it", "confirm", "proceed", "please do", "that's right",
])

# ACKNOWLEDGEMENT β€” conversational continuers that require no LLM or KB response.
# Must be whole-utterance matches (not substring) β€” check via exact normalized match.
_ACKNOWLEDGEMENT_UTTERANCES = frozenset([
    "got it", "makes sense", "okay cool", "nice", "great",
    "sounds good", "understood", "perfect", "awesome",
    "i see", "fair enough", "that makes sense", "okay", "ok",
    "cool", "alright", "good to know", "noted",
    # Positive feedback phrases commonly said after a satisfying answer
    "good to hear that", "good to hear", "glad to hear that", "glad to hear",
    "happy to hear that", "nice to know", "that's helpful", "that helps",
    "that's good", "that's great", "that's interesting", "interesting",
    "that makes sense", "that's clear", "that's useful", "very helpful",
    "helpful", "thanks", "thank you", "thanks for that",
])


def _match_confidence(text: str, patterns: list[str]) -> float:
    lower = text.lower()
    matches = sum(1 for p in patterns if re.search(p, lower))
    if matches == 0:
        return 0.0
    # More matches = higher confidence, capped at 0.95
    return min(0.5 + (matches * 0.2), 0.95)


def detect_directive(text: str) -> DirectiveResult:
    """
    Returns DirectiveResult{directive, confidence}.

    Priority order (first match at threshold wins):
      1. ESCALATE  β€” always, regardless of workflow state
      2. REPAIR    β€” explicit correction before CORRECT/CANCEL to avoid misclassification
      3. ACKNOWLEDGEMENT β€” whole-utterance continuers (no LLM/KB needed)
      4. CORRECT   β€” "no I said X"
      5. CANCEL_PENDING / CONFIRM  β€” yes/no workflow responses
      6. REPEAT / CLARIFY

    Voice edge cases:
    - "yeah no" β†’ CANCEL_PENDING (denial overrides affirmative)
    - "stop stop wait" β†’ CANCEL_PENDING
    - "yeah sure I guess" β†’ low confidence CONFIRM
    - "got it" β†’ ACKNOWLEDGEMENT (no LLM, no KB, optional brief verbal ack)
    """
    if not text or not text.strip():
        return DirectiveResult(ConversationalDirective.NONE, 0.0)

    lower = text.lower().strip()

    # ESCALATE is always detected β€” never blocked by workflow state
    esc = _match_confidence(lower, _ESCALATE_PATTERNS)
    if esc >= DIRECTIVE_CONFIDENCE_THRESHOLD:
        return DirectiveResult(ConversationalDirective.ESCALATE, esc)

    # REPAIR β€” explicit correction; lower threshold since patterns are precise multi-word
    # phrases that rarely false-positive, and "no I meant X" yields exactly 1 match (0.70)
    repair = _match_confidence(lower, _REPAIR_PATTERNS)
    if repair >= _REPAIR_CONFIDENCE_THRESHOLD:
        return DirectiveResult(ConversationalDirective.REPAIR, repair)

    # ACKNOWLEDGEMENT β€” whole-utterance match only (not substring)
    # Strip trailing punctuation for clean lookup
    clean = lower.rstrip(".,!?")
    if clean in _ACKNOWLEDGEMENT_UTTERANCES:
        return DirectiveResult(ConversationalDirective.ACKNOWLEDGEMENT, 0.95)

    # CANCEL β€” bare single-word denials at high confidence
    # "no stop" normalizes to "no" via denial map; "no" alone must still cancel.
    if clean in _CANCEL_UTTERANCES:
        return DirectiveResult(ConversationalDirective.CANCEL_PENDING, 0.95)

    # CONFIRM β€” bare confirmations too short to hit pattern threshold
    # e.g. "yes" β†’ 1 pattern match = 0.70 which is below the 0.75 DIRECTIVE threshold;
    # exact-match frozenset ensures these always confirm at 0.95.
    if clean in _CONFIRM_UTTERANCES:
        return DirectiveResult(ConversationalDirective.CONFIRM, 0.95)

    # CORRECT β€” "no I said X" (before CANCEL so it's not swallowed)
    cor = _match_confidence(lower, _CORRECT_PATTERNS)
    if cor >= DIRECTIVE_CONFIDENCE_THRESHOLD:
        return DirectiveResult(ConversationalDirective.CORRECT, cor)

    # CANCEL_PENDING checked before CONFIRM β€” "yeah no" β†’ cancel
    cancel = _match_confidence(lower, _CANCEL_PATTERNS)
    confirm = _match_confidence(lower, _CONFIRM_PATTERNS)

    if cancel >= confirm and cancel >= DIRECTIVE_CONFIDENCE_THRESHOLD:
        return DirectiveResult(ConversationalDirective.CANCEL_PENDING, cancel)
    if confirm >= DIRECTIVE_CONFIDENCE_THRESHOLD:
        return DirectiveResult(ConversationalDirective.CONFIRM, confirm)

    rep = _match_confidence(lower, _REPEAT_PATTERNS)
    if rep >= DIRECTIVE_CONFIDENCE_THRESHOLD:
        return DirectiveResult(ConversationalDirective.REPEAT, rep)

    cla = _match_confidence(lower, _CLARIFY_PATTERNS)
    if cla >= DIRECTIVE_CONFIDENCE_THRESHOLD:
        return DirectiveResult(ConversationalDirective.CLARIFY, cla)

    # Return best sub-threshold result (caller decides whether to use it)
    candidates = [
        (ConversationalDirective.CANCEL_PENDING, cancel),
        (ConversationalDirective.CONFIRM, confirm),
        (ConversationalDirective.REPEAT, rep),
        (ConversationalDirective.CLARIFY, cla),
    ]
    best_dir, best_conf = max(candidates, key=lambda x: x[1])
    if best_conf > 0:
        return DirectiveResult(best_dir, best_conf)

    return DirectiveResult(ConversationalDirective.NONE, 0.0)