SoloVenus commited on
Commit
affc4bd
·
verified ·
1 Parent(s): 96fdac2

crisp support: human takeover and handback via segment, state kept in Crisp, normalize odd spaces

Browse files
Files changed (1) hide show
  1. crisp_watch.py +37 -19
crisp_watch.py CHANGED
@@ -28,6 +28,7 @@ MAX_AGE_MS = 24 * 3600 * 1000
28
  DAILY_CAP = 300
29
  MAX_ANSWERS = 2
30
  CLAIM_WAIT = 3
 
31
  IGNORED_NICKS = {"Crisp Team"}
32
  KB_FILES = {"Tierly": "tierly.md", "Mixly": "mixly.md", "Swatchbox": "swatchbox.md"}
33
  AUTO = {"greeting", "product_question", "troubleshooting"}
@@ -136,7 +137,8 @@ def llm(system: str, user: str) -> str:
136
  timeout=60,
137
  )
138
  res.raise_for_status()
139
- return res.json()["choices"][0]["message"]["content"].strip()
 
140
  except (httpx.HTTPError, KeyError, IndexError) as exc:
141
  raise ModelDown(type(exc).__name__) from exc
142
 
@@ -192,8 +194,6 @@ def send(sid: str, expected: str, text: str) -> None:
192
  timeout=30,
193
  )
194
  res.raise_for_status()
195
- convs[sid]["sent"].append(res.json()["data"]["fingerprint"])
196
- save()
197
 
198
 
199
  def claim(sid: str, fingerprint: int) -> bool:
@@ -208,10 +208,23 @@ def claim(sid: str, fingerprint: int) -> bool:
208
  return crisp("GET", f"conversation/{sid}/meta").get("data", {}).get("venus_claim") == mine
209
 
210
 
 
 
 
 
 
 
 
 
 
 
211
  def release(sid: str) -> None:
212
- data = (crisp("GET", f"conversation/{sid}/meta").get("data")) or {}
213
- data.pop("venus_claim", None)
214
- crisp("PATCH", f"conversation/{sid}/meta", json={"data": data})
 
 
 
215
 
216
 
217
  def slack(conv: dict, title: str, customer: str, sections: list[tuple[str, str]]) -> None:
@@ -241,7 +254,6 @@ def slack(conv: dict, title: str, customer: str, sections: list[tuple[str, str]]
241
 
242
  def handle(conv: dict) -> str:
243
  sid = conv["session_id"]
244
- c = convs.setdefault(sid, {"sent": [], "answers": 0, "handoff": False})
245
  msgs = thread(sid)
246
  if not msgs or msgs[-1]["from"] != "user":
247
  return "nothing new"
@@ -253,12 +265,22 @@ def handle(conv: dict) -> str:
253
  transcript = "\n".join(
254
  f"{'customer' if m['from'] == 'user' else 'support'}: {m['content'][:1500]}" for m in texts[-10:]
255
  )
256
- app = ((conv.get("meta") or {}).get("data") or {}).get("app")
 
 
257
  first = all(m["from"] != "operator" for m in msgs)
258
- human = any(m["from"] == "operator" and m["fingerprint"] not in c["sent"] for m in msgs)
259
-
260
- if human or c["handoff"]:
261
- slack(conv, "Draft for you", customer, [("Draft reply", llm(DRAFT, f"<conversation>\n{transcript}\n</conversation>"))])
 
 
 
 
 
 
 
 
262
  return "draft for the team"
263
 
264
  triage = classify(transcript)
@@ -271,7 +293,7 @@ def handle(conv: dict) -> str:
271
  reason = f"customer sent a {last['type']}"
272
  elif category not in AUTO:
273
  reason = f"category {category}"
274
- elif c["answers"] >= MAX_ANSWERS:
275
  reason = "answer limit reached"
276
  elif app not in KB_FILES:
277
  reason = f"unknown app {app}"
@@ -287,8 +309,7 @@ def handle(conv: dict) -> str:
287
  if reason is None:
288
  if LIVE:
289
  send(sid, last["fingerprint"], reply)
290
- c["answers"] += 1
291
- save()
292
  slack(conv, "Venus replied", customer, [("Reply", reply), ("Triage", f"{category}: {triage.get('summary', '')}")])
293
  return f"answered ({category})"
294
 
@@ -296,8 +317,7 @@ def handle(conv: dict) -> str:
296
  hold = (intro.format(app=app or "Solora") if first else "") + body
297
  if LIVE:
298
  send(sid, last["fingerprint"], hold)
299
- c["handoff"] = True
300
- save()
301
  try:
302
  draft = llm(DRAFT, f"<conversation>\n{transcript}\n</conversation>")
303
  except ModelDown:
@@ -325,7 +345,6 @@ today = date.today().isoformat()
325
  if state.get("day") != today:
326
  state.update(day=today, calls=0)
327
  seen: dict[str, int] = state.setdefault("seen", {})
328
- convs: dict[str, dict] = state.setdefault("convs", {})
329
 
330
  now_ms = int(time.time() * 1000)
331
  todo = sorted(
@@ -341,7 +360,6 @@ todo = sorted(
341
  )
342
  for sid in [s for s, at in seen.items() if now_ms - at > 7 * MAX_AGE_MS]:
343
  seen.pop(sid)
344
- convs.pop(sid, None)
345
 
346
  report = []
347
  for conv in todo[:MAX_PER_RUN]:
 
28
  DAILY_CAP = 300
29
  MAX_ANSWERS = 2
30
  CLAIM_WAIT = 3
31
+ HANDBACK = "venus"
32
  IGNORED_NICKS = {"Crisp Team"}
33
  KB_FILES = {"Tierly": "tierly.md", "Mixly": "mixly.md", "Swatchbox": "swatchbox.md"}
34
  AUTO = {"greeting", "product_question", "troubleshooting"}
 
137
  timeout=60,
138
  )
139
  res.raise_for_status()
140
+ text = res.json()["choices"][0]["message"]["content"]
141
+ return text.translate(str.maketrans({" ": " ", " ": " ", "‑": "-"})).strip()
142
  except (httpx.HTTPError, KeyError, IndexError) as exc:
143
  raise ModelDown(type(exc).__name__) from exc
144
 
 
194
  timeout=30,
195
  )
196
  res.raise_for_status()
 
 
197
 
198
 
199
  def claim(sid: str, fingerprint: int) -> bool:
 
208
  return crisp("GET", f"conversation/{sid}/meta").get("data", {}).get("venus_claim") == mine
209
 
210
 
211
+ def patch_meta(sid: str, changes: dict, segments: list[str] | None = None) -> None:
212
+ if DRY_RUN:
213
+ return
214
+ data = {**((crisp("GET", f"conversation/{sid}/meta").get("data")) or {}), **changes}
215
+ body = {"data": {k: v for k, v in data.items() if v is not None}}
216
+ if segments is not None:
217
+ body["segments"] = segments
218
+ crisp("PATCH", f"conversation/{sid}/meta", json=body)
219
+
220
+
221
  def release(sid: str) -> None:
222
+ patch_meta(sid, {"venus_claim": None})
223
+
224
+
225
+ def is_human(m: dict) -> bool:
226
+ nickname = str((m.get("user") or {}).get("nickname", ""))
227
+ return m["from"] == "operator" and m["type"] == "text" and not nickname.startswith("Venus")
228
 
229
 
230
  def slack(conv: dict, title: str, customer: str, sections: list[tuple[str, str]]) -> None:
 
254
 
255
  def handle(conv: dict) -> str:
256
  sid = conv["session_id"]
 
257
  msgs = thread(sid)
258
  if not msgs or msgs[-1]["from"] != "user":
259
  return "nothing new"
 
265
  transcript = "\n".join(
266
  f"{'customer' if m['from'] == 'user' else 'support'}: {m['content'][:1500]}" for m in texts[-10:]
267
  )
268
+ meta = conv.get("meta") or {} if DRY_RUN else crisp("GET", f"conversation/{sid}/meta")
269
+ data, segments = dict(meta.get("data") or {}), list(meta.get("segments") or [])
270
+ app = data.get("app")
271
  first = all(m["from"] != "operator" for m in msgs)
272
+ humans = [m["fingerprint"] for m in msgs if is_human(m)]
273
+ if HANDBACK in segments:
274
+ data.update(venus_resume=str(max(humans, default=0)), venus_answers="0", venus_handoff=None)
275
+ patch_meta(sid, data, [s for s in segments if s != HANDBACK])
276
+ human = any(fp > int(data.get("venus_resume", 0)) for fp in humans)
277
+ answers = int(data.get("venus_answers", 0))
278
+
279
+ if human or data.get("venus_handoff") == "1":
280
+ sections = [("Draft reply", llm(DRAFT, f"<conversation>\n{transcript}\n</conversation>"))]
281
+ if human:
282
+ sections.append(("Venus is paused here", f"The team replied. Add the segment '{HANDBACK}' to this chat in Crisp to let Venus continue."))
283
+ slack(conv, "Draft for you", customer, sections)
284
  return "draft for the team"
285
 
286
  triage = classify(transcript)
 
293
  reason = f"customer sent a {last['type']}"
294
  elif category not in AUTO:
295
  reason = f"category {category}"
296
+ elif answers >= MAX_ANSWERS:
297
  reason = "answer limit reached"
298
  elif app not in KB_FILES:
299
  reason = f"unknown app {app}"
 
309
  if reason is None:
310
  if LIVE:
311
  send(sid, last["fingerprint"], reply)
312
+ patch_meta(sid, {"venus_answers": str(answers + 1)})
 
313
  slack(conv, "Venus replied", customer, [("Reply", reply), ("Triage", f"{category}: {triage.get('summary', '')}")])
314
  return f"answered ({category})"
315
 
 
317
  hold = (intro.format(app=app or "Solora") if first else "") + body
318
  if LIVE:
319
  send(sid, last["fingerprint"], hold)
320
+ patch_meta(sid, {"venus_handoff": "1"})
 
321
  try:
322
  draft = llm(DRAFT, f"<conversation>\n{transcript}\n</conversation>")
323
  except ModelDown:
 
345
  if state.get("day") != today:
346
  state.update(day=today, calls=0)
347
  seen: dict[str, int] = state.setdefault("seen", {})
 
348
 
349
  now_ms = int(time.time() * 1000)
350
  todo = sorted(
 
360
  )
361
  for sid in [s for s, at in seen.items() if now_ms - at > 7 * MAX_AGE_MS]:
362
  seen.pop(sid)
 
363
 
364
  report = []
365
  for conv in todo[:MAX_PER_RUN]: