From 36e9082d33d1780c659334224e34fe19ddc4196d Mon Sep 17 00:00:00 2001 From: jimi <1847930177@qq.com> Date: Tue, 3 Mar 2026 12:53:36 +0800 Subject: [PATCH] fix: add recent dialogue loader to conversation store --- qingjian_cs/app/store.py | 57 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/qingjian_cs/app/store.py b/qingjian_cs/app/store.py index 665123b..6ed20e2 100644 --- a/qingjian_cs/app/store.py +++ b/qingjian_cs/app/store.py @@ -249,3 +249,60 @@ class ConversationStore: conn.commit() finally: conn.close() + + def get_recent_dialogue(self, customer_key: str, limit: int = 24) -> list[dict[str, Any]]: + """ + 拉取最近对话(按 customer_key 隔离,即 店铺+客户)。 + 仅返回 customer_message / assistant_message 两类事件。 + """ + t_e = self.events_table + n = max(1, int(limit)) + conn = self._conn() + try: + with conn.cursor() as c: + if self.backend == "mysql": + c.execute( + f""" + SELECT event, payload_json + FROM {t_e} + WHERE customer_key=%s + AND event IN ('customer_message','assistant_message') + ORDER BY id DESC + LIMIT %s + """, + (customer_key, n), + ) + else: + c.execute( + f""" + SELECT event, payload_json + FROM {t_e} + WHERE customer_key=? + AND event IN ('customer_message','assistant_message') + ORDER BY id DESC + LIMIT ? + """, + (customer_key, n), + ) + rows = c.fetchall() or [] + + out: list[dict[str, Any]] = [] + for row in reversed(rows): + if isinstance(row, dict): + ev = str(row.get("event", "") or "") + raw = row.get("payload_json") + else: + ev = str(row[0] or "") + raw = row[1] + try: + payload = raw if isinstance(raw, dict) else json.loads(raw or "{}") + except Exception: + payload = {} + msg = str(payload.get("msg", "") or "").strip() + if not msg: + continue + role = "user" if ev == "customer_message" else "assistant" + out.append({"role": role, "text": msg}) + return out + finally: + conn.close()