BasilTh commited on
Commit
238d37f
Β·
1 Parent(s): cd7eb0b

Deploy updated SLM customer-support chatbot

Browse files
Files changed (1) hide show
  1. SLM_CService.py +105 -49
SLM_CService.py CHANGED
@@ -1,25 +1,30 @@
1
  # ── SLM_CService.py ───────────────────────────────────────────────────────────
2
- # Customer-support-only chatbot with strict NSFW blocking + robust FSM.
3
 
4
  import os
5
  import re
6
  from typing import List, Dict
7
 
 
8
  os.environ["OMP_NUM_THREADS"] = "1"
 
9
  os.environ.pop("HF_HUB_OFFLINE", None)
10
 
11
- # Unsloth must come before transformers/peft
12
  import unsloth # noqa: E402
 
13
  import torch
14
  from transformers import AutoTokenizer, BitsAndBytesConfig, pipeline
15
  from peft import PeftModel
16
  from langchain.memory import ConversationBufferMemory
17
 
18
- # ──────────────────────────────────────────────────────────────────────────────
19
- REPO = "ThomasBasil/bitext-qlora-tinyllama"
20
- BASE = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
 
 
21
 
22
- GEN_KW = dict(
23
  max_new_tokens=160,
24
  do_sample=True,
25
  top_p=0.9,
@@ -28,21 +33,26 @@ GEN_KW = dict(
28
  no_repeat_ngram_size=4,
29
  )
30
 
31
- bnb_cfg = BitsAndBytesConfig(
32
  load_in_4bit=True,
33
  bnb_4bit_quant_type="nf4",
34
  bnb_4bit_use_double_quant=True,
35
- bnb_4bit_compute_dtype=torch.float16,
36
  )
37
 
38
- # ---- Tokenizer & model -------------------------------------------------------
 
 
 
 
 
39
  tokenizer = AutoTokenizer.from_pretrained(REPO, use_fast=False)
40
  if tokenizer.pad_token_id is None and tokenizer.eos_token_id is not None:
41
  tokenizer.pad_token_id = tokenizer.eos_token_id
42
  tokenizer.padding_side = "left"
43
  tokenizer.truncation_side = "right"
44
 
45
- # Unsloth returns (model, tokenizer) β†’ unpack
46
  model, _ = unsloth.FastLanguageModel.from_pretrained(
47
  model_name=BASE,
48
  load_in_4bit=True,
@@ -52,11 +62,11 @@ model, _ = unsloth.FastLanguageModel.from_pretrained(
52
  )
53
  unsloth.FastLanguageModel.for_inference(model)
54
 
55
- # Apply your PEFT adapter from repo root
56
  model = PeftModel.from_pretrained(model, REPO)
57
  model.eval()
58
 
59
- # Text-generation pipeline (pass gen params at call time)
60
  chat_pipe = pipeline(
61
  "text-generation",
62
  model=model,
@@ -65,52 +75,74 @@ chat_pipe = pipeline(
65
  return_full_text=False,
66
  )
67
 
68
- # ──────────────────────────────────────────────────────────────────────────────
69
- # Moderation & blocking (strict)
 
70
  from transformers import TextClassificationPipeline
71
 
72
  SEXUAL_TERMS = [
 
73
  "sex","sexual","porn","nsfw","fetish","kink","bdsm","nude","naked","anal",
74
  "blowjob","handjob","cum","breast","boobs","vagina","penis","semen","ejaculate",
75
  "doggy","missionary","cowgirl","69","kamasutra","dominatrix","submissive","spank",
 
76
  "sex position","have sex","make love","how to flirt","dominant in bed",
77
  ]
 
78
  def _bad_words_ids(tok, terms: List[str]) -> List[List[int]]:
79
- ids=set()
 
80
  for t in terms:
81
- for v in (t, " "+t):
82
  toks = tok(v, add_special_tokens=False).input_ids
83
- if toks: ids.add(tuple(toks))
 
84
  return [list(t) for t in ids]
 
85
  BAD_WORD_IDS = _bad_words_ids(tokenizer, SEXUAL_TERMS)
86
 
 
87
  nsfw_cls: TextClassificationPipeline = pipeline(
88
- "text-classification", model="eliasalbouzidi/distilbert-nsfw-text-classifier", truncation=True,
 
 
89
  )
90
  toxicity_cls: TextClassificationPipeline = pipeline(
91
- "text-classification", model="unitary/toxic-bert", truncation=True, return_all_scores=True,
 
 
 
92
  )
 
93
  def is_sexual_or_toxic(text: str) -> bool:
94
  t = (text or "").lower()
95
- if any(k in t for k in SEXUAL_TERMS): return True
 
96
  try:
97
  res = nsfw_cls(t)[0]
98
- if (res.get("label","").lower()=="nsfw") and float(res.get("score",0))>0.60: return True
99
- except Exception: pass
 
 
100
  try:
101
  scores = toxicity_cls(t)[0]
102
- if any(s["score"]>0.60 and s["label"].lower() in
103
  {"toxic","severe_toxic","obscene","threat","insult","identity_hate"} for s in scores):
104
  return True
105
- except Exception: pass
 
106
  return False
107
 
108
  REFUSAL = ("Sorry, I can’t help with that. I’m only for store support "
109
  "(orders, shipping, ETA, tracking, returns, warranty, account).")
110
 
111
- # ──────────────────────────────────────────────────────────────────────────────
112
- # Memory + globals
113
- memory = ConversationBufferMemory(return_messages=True)
 
 
 
 
114
 
115
  SYSTEM_PROMPT = (
116
  "You are a customer-support assistant for our store. Only handle account, "
@@ -126,12 +158,16 @@ ALLOWED_KEYWORDS = (
126
  )
127
 
128
  # Robust order detection:
 
 
129
  ORDER_RX = re.compile(
130
  r"(?:#\s*([\d]{3,12})|order(?:\s*(?:no\.?|number|id))?\s*#?\s*([\d]{3,12}))",
131
  flags=re.I,
132
  )
 
133
  def extract_order(text: str):
134
- if not text: return None
 
135
  m = ORDER_RX.search(text)
136
  return (m.group(1) or m.group(2)) if m else None
137
 
@@ -153,47 +189,56 @@ def handle_gratitude(_=None): return "You’re welcome! Anything else I can help
153
  def handle_escalation(_=None): return "I can connect you with a human agent. Would you like me to do that?"
154
  def handle_ask_action(o): return (f"I’ve saved order #{o}. What would you like to do β€” status, ETA, tracking link, or cancel?")
155
 
 
156
  stored_order = None
157
  pending_intent = None
158
 
159
  def reset_state():
 
160
  global stored_order, pending_intent
161
  stored_order = None
162
  pending_intent = None
163
- try: memory.clear()
164
- except Exception: pass
 
 
165
  return True
166
 
167
- # ---- chat templating ---------------------------------------------------------
168
- def _lc_to_messages() -> List[Dict[str,str]]:
 
 
169
  msgs = [{"role": "system", "content": SYSTEM_PROMPT}]
170
- hist = memory.load_memory_variables({}).get("chat_history", []) or []
171
  for m in hist:
172
  role = "user" if getattr(m, "type", "") == "human" else "assistant"
173
  msgs.append({"role": role, "content": getattr(m, "content", "")})
174
  return msgs
175
 
176
  def _generate_reply(user_input: str) -> str:
 
177
  messages = _lc_to_messages() + [{"role": "user", "content": user_input}]
178
  prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
179
  out = chat_pipe(
180
  prompt,
181
  eos_token_id=tokenizer.eos_token_id,
182
  pad_token_id=tokenizer.pad_token_id,
183
- bad_words_ids=BAD_WORD_IDS,
184
  **GEN_KW,
185
  )[0]["generated_text"]
186
  return out.strip()
187
 
188
- # ---- main entry --------------------------------------------------------------
 
 
189
  def chat_with_memory(user_input: str) -> str:
190
  global stored_order, pending_intent
191
  ui = (user_input or "").strip()
192
  if not ui:
193
  return "How can I help with your order today?"
194
 
195
- # Fresh session guard
196
- hist = memory.load_memory_variables({}).get("chat_history", []) or []
197
  if len(hist) == 0:
198
  stored_order = None
199
  pending_intent = None
@@ -206,20 +251,24 @@ def chat_with_memory(user_input: str) -> str:
206
 
207
  low = ui.lower()
208
 
209
- # 2) Quick intents
210
  if any(tok in low for tok in ["thank you","thanks","thx"]):
211
  reply = handle_gratitude()
212
  memory.save_context({"input": ui}, {"output": reply})
213
  return reply
214
 
215
- # 3) PENDING-INTENT SHORT-CIRCUIT (fix for "It's #26790" case)
216
  new_o = extract_order(ui)
217
  if pending_intent:
218
  if new_o:
219
  stored_order = new_o
220
- fn = {"status": handle_status, "eta": handle_eta,
221
- "track": handle_track, "link": handle_link,
222
- "cancel": handle_cancel}[pending_intent]
 
 
 
 
223
  reply = fn(stored_order)
224
  pending_intent = None
225
  memory.save_context({"input": ui}, {"output": reply})
@@ -229,7 +278,7 @@ def chat_with_memory(user_input: str) -> str:
229
  memory.save_context({"input": ui}, {"output": reply})
230
  return reply
231
 
232
- # 4) If message provides an order number (no pending intent yet), save it & ask action
233
  if new_o:
234
  stored_order = new_o
235
  reply = handle_ask_action(stored_order)
@@ -242,7 +291,7 @@ def chat_with_memory(user_input: str) -> str:
242
  memory.save_context({"input": ui}, {"output": reply})
243
  return reply
244
 
245
- # 6) Intent classification
246
  if any(k in low for k in ["status","where is my order","check status"]):
247
  intent = "status"
248
  elif any(k in low for k in ["how long","eta","delivery time"]):
@@ -260,18 +309,24 @@ def chat_with_memory(user_input: str) -> str:
260
  else:
261
  intent = "fallback"
262
 
263
- # 7) Handle intents
264
  if intent in ("status","eta","track","link","cancel"):
265
  if not stored_order:
266
  pending_intent = intent
267
  reply = "Sureβ€”what’s your order number (e.g., #12345)?"
268
  else:
269
- fn = {"status": handle_status,"eta": handle_eta,"track": handle_track,
270
- "link": handle_link,"cancel": handle_cancel}[intent]
 
 
 
 
 
271
  reply = fn(stored_order)
272
  memory.save_context({"input": ui}, {"output": reply})
273
  return reply
274
 
 
275
  if intent == "warranty_policy":
276
  reply = handle_warranty_policy()
277
  memory.save_context({"input": ui}, {"output": reply})
@@ -282,8 +337,9 @@ def chat_with_memory(user_input: str) -> str:
282
  memory.save_context({"input": ui}, {"output": reply})
283
  return reply
284
 
285
- # 8) LLM fallback (on-topic) + post-check
286
  reply = _generate_reply(ui)
287
- if is_sexual_or_toxic(reply): reply = REFUSAL
 
288
  memory.save_context({"input": ui}, {"output": reply})
289
  return reply
 
1
  # ── SLM_CService.py ───────────────────────────────────────────────────────────
2
+ # Customer-support-only chatbot with strict NSFW blocking + robust FSM + proper reset.
3
 
4
  import os
5
  import re
6
  from typing import List, Dict
7
 
8
+ # Keep OpenMP logs quiet
9
  os.environ["OMP_NUM_THREADS"] = "1"
10
+ # Ensure we don't accidentally force offline mode
11
  os.environ.pop("HF_HUB_OFFLINE", None)
12
 
13
+ # ── Import order matters: Unsloth should come before transformers/peft.
14
  import unsloth # noqa: E402
15
+
16
  import torch
17
  from transformers import AutoTokenizer, BitsAndBytesConfig, pipeline
18
  from peft import PeftModel
19
  from langchain.memory import ConversationBufferMemory
20
 
21
+ # ==============================
22
+ # Config
23
+ # ==============================
24
+ REPO = "ThomasBasil/bitext-qlora-tinyllama" # your adapter + tokenizer live at repo root
25
+ BASE = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" # base model
26
 
27
+ GEN_KW = dict( # generation params (passed at call time)
28
  max_new_tokens=160,
29
  do_sample=True,
30
  top_p=0.9,
 
33
  no_repeat_ngram_size=4,
34
  )
35
 
36
+ bnb_cfg = BitsAndBytesConfig( # 4-bit QLoRA-style loading (needs GPU)
37
  load_in_4bit=True,
38
  bnb_4bit_quant_type="nf4",
39
  bnb_4bit_use_double_quant=True,
40
+ bnb_4bit_compute_dtype=torch.float16, # T4/A10G-friendly
41
  )
42
 
43
+ # Memory key FIX: use the same key for saving & reading history
44
+ MEMORY_KEY = "chat_history"
45
+
46
+ # ==============================
47
+ # Load tokenizer & model
48
+ # ==============================
49
  tokenizer = AutoTokenizer.from_pretrained(REPO, use_fast=False)
50
  if tokenizer.pad_token_id is None and tokenizer.eos_token_id is not None:
51
  tokenizer.pad_token_id = tokenizer.eos_token_id
52
  tokenizer.padding_side = "left"
53
  tokenizer.truncation_side = "right"
54
 
55
+ # Unsloth returns (model, tokenizer) -> unpack
56
  model, _ = unsloth.FastLanguageModel.from_pretrained(
57
  model_name=BASE,
58
  load_in_4bit=True,
 
62
  )
63
  unsloth.FastLanguageModel.for_inference(model)
64
 
65
+ # Attach your PEFT adapter from repo root
66
  model = PeftModel.from_pretrained(model, REPO)
67
  model.eval()
68
 
69
+ # Text-generation pipeline (pass GEN_KW at call time, not as generate_kwargs)
70
  chat_pipe = pipeline(
71
  "text-generation",
72
  model=model,
 
75
  return_full_text=False,
76
  )
77
 
78
+ # ==============================
79
+ # Moderation (strict)
80
+ # ==============================
81
  from transformers import TextClassificationPipeline
82
 
83
  SEXUAL_TERMS = [
84
+ # single words
85
  "sex","sexual","porn","nsfw","fetish","kink","bdsm","nude","naked","anal",
86
  "blowjob","handjob","cum","breast","boobs","vagina","penis","semen","ejaculate",
87
  "doggy","missionary","cowgirl","69","kamasutra","dominatrix","submissive","spank",
88
+ # phrases
89
  "sex position","have sex","make love","how to flirt","dominant in bed",
90
  ]
91
+
92
  def _bad_words_ids(tok, terms: List[str]) -> List[List[int]]:
93
+ """Build bad_words_ids for generation; include both 'term' and ' term' variants."""
94
+ ids = set()
95
  for t in terms:
96
+ for v in (t, " " + t):
97
  toks = tok(v, add_special_tokens=False).input_ids
98
+ if toks:
99
+ ids.add(tuple(toks))
100
  return [list(t) for t in ids]
101
+
102
  BAD_WORD_IDS = _bad_words_ids(tokenizer, SEXUAL_TERMS)
103
 
104
+ # Lightweight classifiers (optional but helpful defense-in-depth)
105
  nsfw_cls: TextClassificationPipeline = pipeline(
106
+ "text-classification",
107
+ model="eliasalbouzidi/distilbert-nsfw-text-classifier",
108
+ truncation=True,
109
  )
110
  toxicity_cls: TextClassificationPipeline = pipeline(
111
+ "text-classification",
112
+ model="unitary/toxic-bert",
113
+ truncation=True,
114
+ return_all_scores=True,
115
  )
116
+
117
  def is_sexual_or_toxic(text: str) -> bool:
118
  t = (text or "").lower()
119
+ if any(k in t for k in SEXUAL_TERMS):
120
+ return True
121
  try:
122
  res = nsfw_cls(t)[0]
123
+ if (res.get("label","").lower() == "nsfw") and float(res.get("score",0)) > 0.60:
124
+ return True
125
+ except Exception:
126
+ pass
127
  try:
128
  scores = toxicity_cls(t)[0]
129
+ if any(s["score"] > 0.60 and s["label"].lower() in
130
  {"toxic","severe_toxic","obscene","threat","insult","identity_hate"} for s in scores):
131
  return True
132
+ except Exception:
133
+ pass
134
  return False
135
 
136
  REFUSAL = ("Sorry, I can’t help with that. I’m only for store support "
137
  "(orders, shipping, ETA, tracking, returns, warranty, account).")
138
 
139
+ # ==============================
140
+ # Memory + Globals
141
+ # ==============================
142
+ memory = ConversationBufferMemory(
143
+ memory_key=MEMORY_KEY, # ← FIX: explicit memory key
144
+ return_messages=True,
145
+ )
146
 
147
  SYSTEM_PROMPT = (
148
  "You are a customer-support assistant for our store. Only handle account, "
 
158
  )
159
 
160
  # Robust order detection:
161
+ # - "#67890" / "# 67890"
162
+ # - "order 67890", "order no. 67890", "order number 67890", "order id 67890"
163
  ORDER_RX = re.compile(
164
  r"(?:#\s*([\d]{3,12})|order(?:\s*(?:no\.?|number|id))?\s*#?\s*([\d]{3,12}))",
165
  flags=re.I,
166
  )
167
+
168
  def extract_order(text: str):
169
+ if not text:
170
+ return None
171
  m = ORDER_RX.search(text)
172
  return (m.group(1) or m.group(2)) if m else None
173
 
 
189
  def handle_escalation(_=None): return "I can connect you with a human agent. Would you like me to do that?"
190
  def handle_ask_action(o): return (f"I’ve saved order #{o}. What would you like to do β€” status, ETA, tracking link, or cancel?")
191
 
192
+ # >>> state that must reset <<<
193
  stored_order = None
194
  pending_intent = None
195
 
196
  def reset_state():
197
+ """Called by app.py Reset button to clear memory + globals."""
198
  global stored_order, pending_intent
199
  stored_order = None
200
  pending_intent = None
201
+ try:
202
+ memory.clear() # wipe the buffer
203
+ except Exception:
204
+ pass
205
  return True
206
 
207
+ # ==============================
208
+ # Chat templating helpers
209
+ # ==============================
210
+ def _lc_to_messages() -> List[Dict[str, str]]:
211
  msgs = [{"role": "system", "content": SYSTEM_PROMPT}]
212
+ hist = memory.load_memory_variables({}).get(MEMORY_KEY, []) or [] # ← use same key
213
  for m in hist:
214
  role = "user" if getattr(m, "type", "") == "human" else "assistant"
215
  msgs.append({"role": role, "content": getattr(m, "content", "")})
216
  return msgs
217
 
218
  def _generate_reply(user_input: str) -> str:
219
+ # Format with HF chat template so the model respects roles/system
220
  messages = _lc_to_messages() + [{"role": "user", "content": user_input}]
221
  prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
222
  out = chat_pipe(
223
  prompt,
224
  eos_token_id=tokenizer.eos_token_id,
225
  pad_token_id=tokenizer.pad_token_id,
226
+ bad_words_ids=BAD_WORD_IDS, # block sexual tokens at generation time
227
  **GEN_KW,
228
  )[0]["generated_text"]
229
  return out.strip()
230
 
231
+ # ==============================
232
+ # Main entry
233
+ # ==============================
234
  def chat_with_memory(user_input: str) -> str:
235
  global stored_order, pending_intent
236
  ui = (user_input or "").strip()
237
  if not ui:
238
  return "How can I help with your order today?"
239
 
240
+ # Fresh session guard: if memory empty, also clear globals
241
+ hist = memory.load_memory_variables({}).get(MEMORY_KEY, []) or []
242
  if len(hist) == 0:
243
  stored_order = None
244
  pending_intent = None
 
251
 
252
  low = ui.lower()
253
 
254
+ # 2) Quick intents (gratitude / returns)
255
  if any(tok in low for tok in ["thank you","thanks","thx"]):
256
  reply = handle_gratitude()
257
  memory.save_context({"input": ui}, {"output": reply})
258
  return reply
259
 
260
+ # 3) PENDING-INTENT SHORT-CIRCUIT (fixes "It's #26790" case)
261
  new_o = extract_order(ui)
262
  if pending_intent:
263
  if new_o:
264
  stored_order = new_o
265
+ fn = {
266
+ "status": handle_status,
267
+ "eta": handle_eta,
268
+ "track": handle_track,
269
+ "link": handle_link,
270
+ "cancel": handle_cancel,
271
+ }[pending_intent]
272
  reply = fn(stored_order)
273
  pending_intent = None
274
  memory.save_context({"input": ui}, {"output": reply})
 
278
  memory.save_context({"input": ui}, {"output": reply})
279
  return reply
280
 
281
+ # 4) If message provides an order number (no pending intent yet), save & ask action
282
  if new_o:
283
  stored_order = new_o
284
  reply = handle_ask_action(stored_order)
 
291
  memory.save_context({"input": ui}, {"output": reply})
292
  return reply
293
 
294
+ # 6) Intent classification (deterministic handlers first)
295
  if any(k in low for k in ["status","where is my order","check status"]):
296
  intent = "status"
297
  elif any(k in low for k in ["how long","eta","delivery time"]):
 
309
  else:
310
  intent = "fallback"
311
 
312
+ # 7) Handle intents that need an order number
313
  if intent in ("status","eta","track","link","cancel"):
314
  if not stored_order:
315
  pending_intent = intent
316
  reply = "Sureβ€”what’s your order number (e.g., #12345)?"
317
  else:
318
+ fn = {
319
+ "status": handle_status,
320
+ "eta": handle_eta,
321
+ "track": handle_track,
322
+ "link": handle_link,
323
+ "cancel": handle_cancel,
324
+ }[intent]
325
  reply = fn(stored_order)
326
  memory.save_context({"input": ui}, {"output": reply})
327
  return reply
328
 
329
+ # 8) Policy intents (no order needed)
330
  if intent == "warranty_policy":
331
  reply = handle_warranty_policy()
332
  memory.save_context({"input": ui}, {"output": reply})
 
337
  memory.save_context({"input": ui}, {"output": reply})
338
  return reply
339
 
340
+ # 9) LLM fallback (still on-topic) + post-check
341
  reply = _generate_reply(ui)
342
+ if is_sexual_or_toxic(reply):
343
+ reply = REFUSAL
344
  memory.save_context({"input": ui}, {"output": reply})
345
  return reply