# /home/ubuntu/cerebratex/agent/memory_sync.py import psycopg2 import os import httpx import time import asyncio import uuid import logging def get_conversations_list(user_id: str, limit: int = 500) -> list: conn = psycopg2.connect("dbname=cerebratex user=ubuntu") cur = conn.cursor() try: # 【物理隔绝】:左侧抽屉只拉取纯粹的个人私聊历史,严禁工作区记录污染! cur.execute(""" SELECT conversation_id, title, view, intent, TO_CHAR(updated_at, 'MM-DD HH24:MI') as time, is_pinned FROM conversations WHERE user_id = %s AND workspace_id IS NULL AND status = 'active' ORDER BY updated_at DESC LIMIT %s """, (user_id, limit)) rows = cur.fetchall() return [{ "id": r[0], "title": r[1] or "新推演", "view": r[2] or "", "intent": r[3] or "", "time": r[4], "isPinned": bool(r[5]) } for r in rows] except Exception as e: print(f"Fetch history error: {e}") return [] finally: cur.close() conn.close() def get_conversation_messages(conversation_id: str) -> list: """拉取指定会话下的所有聊天记录""" conn = psycopg2.connect("dbname=cerebratex user=ubuntu") cur = conn.cursor() try: cur.execute(""" SELECT role, content FROM messages WHERE conversation_id = %s ORDER BY created_at ASC """, (conversation_id,)) result = [] for r in cur.fetchall(): role = r[0] content = r[1] or "" # 【读时过滤】:底层保留了发票,但绝不向前端界面和主引擎推理上下文暴露 if role == "assistant" and '{"usage":' in content and '"prompt_tokens":' in content: content = content.rsplit('{"usage":', 1)[0].strip() result.append({"role": role, "content": content}) return result except Exception as e: print(f"Fetch messages error: {e}") return [] finally: cur.close() conn.close() import uuid def init_conversation(user_id: str, view: str, intent: str, title: str, workspace_id: str = None, guest_id: str = None) -> str: """物理建档:生成合法的 UUID 并存入 conversations 表""" conn = psycopg2.connect("dbname=cerebratex user=ubuntu") cur = conn.cursor() new_id = str(uuid.uuid4()) try: # 【物理隔离入库】:如果有 workspace_id,打入专属抽屉 if workspace_id and len(str(workspace_id)) > 10: cur.execute(""" INSERT INTO conversations (conversation_id, user_id, view, intent, title, workspace_id, guest_id) VALUES (%s, %s, %s, %s, %s, %s, %s) """, (new_id, user_id, view, intent, (title or "New Session")[:50], workspace_id, guest_id)) else: cur.execute(""" INSERT INTO conversations (conversation_id, user_id, view, intent, title, guest_id) VALUES (%s, %s, %s, %s, %s, %s) """, (new_id, user_id, view, intent, (title or "New Session")[:50], guest_id)) conn.commit() return new_id except Exception as e: conn.rollback() print(f"Init conv error: {e}") return new_id finally: cur.close() conn.close() def save_chat_message(conversation_id: str, role: str, content: str): """物理落库:将单条消息存入 messages,并刷新会话时间""" if not conversation_id or len(str(conversation_id)) < 30: return conn = psycopg2.connect("dbname=cerebratex user=ubuntu") cur = conn.cursor() try: cur.execute(""" INSERT INTO messages (conversation_id, role, content) VALUES (%s, %s, %s) """, (conversation_id, role, content)) cur.execute(""" UPDATE conversations SET updated_at = NOW() WHERE conversation_id = %s """, (conversation_id,)) conn.commit() except Exception as e: conn.rollback() print(f"Save msg error: {e}") finally: cur.close() conn.close() async def run_memory_washer(user_id: str): conn = psycopg2.connect("dbname=cerebratex user=ubuntu") cur = conn.cursor() try: cur.execute(""" SELECT conversation_id, title FROM conversations WHERE user_id = %s AND (is_vectorized = FALSE OR is_vectorized IS NULL) AND status = 'active' """, (user_id,)) unwashed_convs = cur.fetchall() if not unwashed_convs: return llama_api_key = os.environ.get("LLAMA_API_KEY", "") llama_base_url = os.environ.get("LLAMA_BASE_URL", "").rstrip('/') gemini_api_key = os.environ.get("GEMINI_API_KEY", "") if not llama_api_key or not gemini_api_key or not llama_base_url: return async with httpx.AsyncClient() as client: try: await client.put("http://localhost:6333/collections/user_memories", json={ "vectors": {"size": 768, "distance": "Cosine"} }, timeout=5.0) except Exception: pass for conv_id, title in unwashed_convs: cur.execute("SELECT role, content FROM messages WHERE conversation_id = %s ORDER BY created_at ASC", (conv_id,)) msgs = cur.fetchall() chat_text = "\n".join([f"{m[0]}: {m[1]}" for m in msgs]) if len(msgs) >= 2 else "" is_empty_fact = False fact_text = "" if chat_text: prompt = f"""你是一个专业的商业事实提取器。请分析以下对话记录,提取出用户业务相关的核心客观事实。 要求: 1. 去除所有寒暄、大模型的说教和套话。 2. 以第一人称视角输出高度浓缩的纯文本摘要(不超过300字)。 3. 如果没有包含实质性的商业事实,只能回复:无有效事实 对话记录: {chat_text[:8000]}""" llama_resp = await client.post( f"{llama_base_url}/chat/completions", headers={"Authorization": f"Bearer {llama_api_key}"}, json={ "model": "meta-llama/llama-3.1-8b-instruct", "messages": [{"role": "user", "content": prompt}], "temperature": 0.1 }, timeout=30.0 ) if llama_resp.status_code != 200: raise RuntimeError(f"Llama API 拒绝: {llama_resp.text}") llama_data = llama_resp.json() fact_text = llama_data.get("choices", [{}])[0].get("message", {}).get("content", "").strip() if not fact_text or "无有效事实" in fact_text or len(fact_text) < 10: is_empty_fact = True fact_text = "无商业事实的闲聊与过渡记录" # 【物理对齐】:完全使用您提供的 Gemini 配置 gemini_url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-001:embedContent?key={gemini_api_key}" gemini_payload = { "model": "models/gemini-embedding-001", "content": {"parts": [{"text": fact_text}]}, "taskType": "RETRIEVAL_DOCUMENT", "outputDimensionality": 768 } gemini_resp = await client.post(gemini_url, json=gemini_payload, timeout=15.0) if gemini_resp.status_code != 200: raise RuntimeError(f"Gemini API 拒绝: {gemini_resp.text}") gemini_data = gemini_resp.json() embedding = gemini_data.get("embedding", {}).get("values", []) if not embedding: raise RuntimeError("Gemini 返回200但未能解析到向量") point_id = str(uuid.uuid4()) qdrant_payload = { "points": [{ "id": point_id, "vector": embedding, "payload": { "user_id": user_id, "source_conversation_id": conv_id, "memory_type": "conversation_fact", "content": "" if is_empty_fact else fact_text, "is_empty": is_empty_fact, "timestamp": int(time.time()) } }] } qdrant_resp = await client.put("http://localhost:6333/collections/user_memories/points?wait=true", json=qdrant_payload, timeout=10.0) if qdrant_resp.status_code == 200: cur.execute("UPDATE conversations SET is_vectorized = TRUE WHERE conversation_id = %s", (conv_id,)) # 【核心记账动作】:将消耗的算力和产生的资产容量,记入晨报专用的 user_usage 表 token_cost = llama_data.get("usage", {}).get("total_tokens", 0) + 20 kb_size = round(len(fact_text) / 1024, 2) cur.execute(""" INSERT INTO user_usage (user_id, date, tokens_used, memory_storage_kb) VALUES (%s, CURRENT_DATE, %s, %s) ON CONFLICT (user_id, date) DO UPDATE SET tokens_used = user_usage.tokens_used + EXCLUDED.tokens_used, memory_storage_kb = user_usage.memory_storage_kb + EXCLUDED.memory_storage_kb """, (user_id, token_cost, kb_size)) conn.commit() logging.warning(f"✅ Qdrant记忆结晶并记账成功:{conv_id}") else: raise RuntimeError(f"Qdrant 写入拒绝: {qdrant_resp.text}") # ========================================== # 【商业化防线】:Qdrant 记忆容量 FIFO 斩杀机制 # ========================================== try: # 1. 去总账本查询用户的“法定记忆上限” (默认 20000 字) cur.execute("SELECT max_context FROM user_subscriptions WHERE user_id = %s", (user_id,)) row = cur.fetchone() max_context = row[0] if row and row[0] else 20000 # 2. 从 Qdrant 盘点该用户名下的所有潜意识资产 scroll_payload = { "filter": {"must": [{"key": "user_id", "match": {"value": user_id}}]}, "limit": 10000, "with_payload": True } scroll_resp = await client.post("http://localhost:6333/collections/user_memories/points/scroll", json=scroll_payload, timeout=15.0) if scroll_resp.status_code == 200: points = scroll_resp.json().get("result", {}).get("points", []) # 按时间戳升序排列(最老的记忆排在最前面被处决) points.sort(key=lambda x: x.get("payload", {}).get("timestamp", 0)) # 严密计算字数总负荷 total_length = sum(len(p.get("payload", {}).get("content", "")) for p in points) # 3. 触发超载斩杀! if total_length > max_context: points_to_delete = [] for p in points: content_len = len(p.get("payload", {}).get("content", "")) points_to_delete.append(p["id"]) total_length -= content_len # 一旦斩杀到容量红线以下,立刻停止处决 if total_length <= max_context: break if points_to_delete: del_payload = {"points": points_to_delete} await client.post("http://localhost:6333/collections/user_memories/points/delete", json=del_payload, timeout=10.0) logging.warning(f"🔪 [商业防线触发] 用户 {user_id} 记忆超载。已物理斩杀 {len(points_to_delete)} 条陈旧向量,逼迫套餐升级!") except Exception as fifo_err: logging.error(f"⚠️ FIFO 斩杀机制运行异常 (不影响主流程): {fifo_err}") except Exception as e: conn.rollback() logging.error(f"🛑 洗菜工致命异常: {str(e)}") finally: cur.close() conn.close() async def search_qdrant_history(query: str, user_id: str, session_id: str = None, top_k: int = 3) -> list: """【真兜底】:带租户硬隔离的 Qdrant 历史记忆检索""" gemini_api_key = os.environ.get("GEMINI_API_KEY", "") if not gemini_api_key: return [] async with httpx.AsyncClient() as client: try: # 1. 使用与洗菜工相同的模型进行查询向量化 (任务类型切换为 QUERY) gemini_url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-001:embedContent?key={gemini_api_key}" gemini_payload = { "model": "models/gemini-embedding-001", "content": {"parts": [{"text": query}]}, "taskType": "RETRIEVAL_QUERY", "outputDimensionality": 768 } gemini_resp = await client.post(gemini_url, json=gemini_payload, timeout=10.0) if gemini_resp.status_code != 200: return [] embedding = gemini_resp.json().get("embedding", {}).get("values", []) if not embedding: return [] # 2. 带着 user_id 严密过滤去 Qdrant 检索 must_filters = [ {"key": "user_id", "match": {"value": user_id}}, {"key": "is_empty", "match": {"value": False}} ] # 【物理隔离墙】:如果传入了 session_id,则必须死死锁定在当前会话的记忆池内! if session_id: must_filters.append({"key": "source_conversation_id", "match": {"value": session_id}}) qdrant_payload = { "vector": embedding, "limit": top_k, "with_payload": True, "filter": { "must": must_filters } } qdrant_resp = await client.post( "http://localhost:6333/collections/user_memories/points/search", json=qdrant_payload, timeout=10.0 ) if qdrant_resp.status_code != 200: return [] results = qdrant_resp.json().get("result", []) # 精确提取有效事实 chunks = [res["payload"].get("content") for res in results if res.get("payload") and res["payload"].get("content")] return chunks except Exception as e: logging.error(f"Qdrant 检索异常: {e}") return [] def search_pg_history(mode: str, val: str, conv_id: str) -> list: """三维调度专属:根据意图模式执行不同层级的数据库打捞""" import psycopg2 import os try: conn = psycopg2.connect( dbname=os.environ.get("PG_DBNAME", "cerebratex"), user=os.environ.get("PG_USER", "ubuntu"), password=os.environ.get("PG_PASSWORD", ""), host=os.environ.get("PG_HOST", "127.0.0.1"), port=os.environ.get("PG_PORT", "5432") ) cur = conn.cursor() if mode == "position": cur.execute(""" SELECT role, content FROM messages WHERE conversation_id = %s ORDER BY created_at ASC LIMIT 3 """, (conv_id,)) rows = cur.fetchall() elif mode == "session_anchor": cur.execute(""" SELECT view, intent, title FROM conversations WHERE conversation_id = %s """, (conv_id,)) row = cur.fetchone() if row: rows = [("system", f"当前会话的开局战略锚点:用户视角设定为[{row[0]}],核心目标与动机设定为[{row[1]}],初始话题为[{row[2]}]。")] else: rows = [] else: # keyword 默认模式 val_str = val if val else "" cur.execute(""" SELECT role, content FROM messages WHERE conversation_id = %s AND content ILIKE %s ORDER BY created_at ASC LIMIT 5 """, (conv_id, f"%{val_str}%")) rows = cur.fetchall() cur.close() conn.close() if not rows: return [] return [f"[{r[0]}] {r[1]}" for r in rows] except Exception as e: print(f"❌ [智能PG探针] 检索失败: {e}") return []