Spaces:
Runtime error
Runtime error
Download agent/data_assembler.py from shensuming/gemini: direct link, hf CLI and curl.
- Browser
- Download file 7.42 kB
-
https://huggingface.co/spaces/shensuming/gemini/resolve/main/agent/data_assembler.py
- Command line
-
hf download hf://spaces/shensuming/gemini/agent/data_assembler.py
-
curl -L -o data_assembler.py https://huggingface.co/spaces/shensuming/gemini/resolve/main/agent/data_assembler.py
7.42 kB
| # /home/ubuntu/cerebratex/agent/data_assembler.py | |
| import asyncio | |
| import psycopg2 | |
| from typing import Dict, Any, Optional | |
| from agent.retrieval import semantic_retrieve | |
| from agent.memory_sync import search_qdrant_history | |
| class DataAssembler: | |
| def __init__(self): | |
| # 可以在这里初始化数据库连接池或缓存客户端 (如 Redis) | |
| pass | |
| async def assemble( | |
| self, | |
| user_id: str, | |
| session_id: str, | |
| query: str, | |
| history: list = None, # 【物理接入】:直接接收外部真实历史,废弃假 TODO | |
| parsed_attachments: Optional[str] = None, | |
| require_vector: bool = False | |
| ) -> Dict[str, Any]: | |
| """ | |
| 第0步核心装配厂:将四股知识流受控组装为一个标准的 Payload | |
| """ | |
| history = history or [] | |
| # 1. 初始化标准 Payload 容器 | |
| payload = { | |
| "metadata": { | |
| "user_id": user_id, | |
| "session_id": session_id, | |
| "has_attachment": bool(parsed_attachments) | |
| }, | |
| "user_query": query, | |
| "attachment_text": "", | |
| "knowledge_chunks": [], | |
| "session_history": history, # 直接装配,成为全系统唯一合法记忆源 | |
| "working_artifact": None | |
| } | |
| # 2. 装配流2:附件 | |
| if parsed_attachments: | |
| payload["attachment_text"] = parsed_attachments | |
| # 3. 动态并发打捞 (剔除多余的假 history 捞取逻辑) | |
| fetch_tasks = [ | |
| self._fetch_level_2_knowledge(query) if require_vector else asyncio.sleep(0), | |
| self._fetch_level_3_artifact(user_id, session_id) | |
| ] | |
| results = await asyncio.gather(*fetch_tasks, return_exceptions=True) | |
| # 4. 组装打捞结果 | |
| if require_vector and not isinstance(results[0], Exception): | |
| payload["knowledge_chunks"] = results[0] | |
| else: | |
| payload["knowledge_chunks"] = [] | |
| payload["working_artifact"] = results[1] if not isinstance(results[1], Exception) else None | |
| return payload | |
| # ==================== 内部打捞逻辑 (对接具体组件) ==================== | |
| async def _fetch_level_1_history(self, user_id: str, session_id: str) -> list: | |
| """ | |
| 打捞 Level 1 (短期记忆):去数据库/Redis捞取当前会话最近 5-10 轮的对话流水。 | |
| """ | |
| # TODO: 对接 memory_sync.py | |
| # return await fetch_session_history(session_id, limit=5) | |
| return [] | |
| async def _fetch_level_2_knowledge(self, query: str) -> list: | |
| """ | |
| 打捞 Level 2 (专业知识):将 Query 向量化,去 FAISS/Qdrant 捞取相关的专业切片。 | |
| """ | |
| # 正式对接 retrieval.py,打捞 3 条最相关切片 | |
| return await semantic_retrieve(query, top_k=3) | |
| async def _fetch_level_3_artifact(self, user_id: str, session_id: str) -> Optional[dict]: | |
| """ | |
| 打捞 Level 3 (工作区制品):如果你在做一个复杂的长周期任务(如写SOP),捞出当前的 JSONB 图纸。 | |
| 当前为阶段一,默认返回 None。 | |
| """ | |
| return None | |
| async def fetch_call_history(self, keyword: str, user_id: str) -> list: | |
| """ | |
| 【绝杀双漏斗:PG先锋 -> 语义兜底】 | |
| 独立于 FAISS 之外的专属通道。 | |
| """ | |
| def _pg_search(): | |
| if not user_id: return [] | |
| conn = psycopg2.connect("dbname=cerebratex user=ubuntu") | |
| try: | |
| with conn.cursor() as cur: | |
| cur.execute("SELECT column_name FROM information_schema.columns WHERE table_name='conversations'") | |
| cols = [r[0] for r in cur.fetchall()] | |
| id_col = 'conversation_id' if 'conversation_id' in cols else ('session_id' if 'session_id' in cols else 'id') | |
| # 核心 SQL:先定位属于该用户的目标消息,再抓取同会话内的上文4条(2轮)和下文4条(2轮) | |
| sql = f""" | |
| WITH target_msg AS ( | |
| SELECT m.conversation_id, m.created_at | |
| FROM messages m | |
| JOIN conversations c ON m.conversation_id = c.{id_col} | |
| WHERE c.user_id = %s AND m.content ILIKE %s | |
| ORDER BY m.created_at DESC | |
| LIMIT 1 | |
| ) | |
| SELECT role, content FROM ( | |
| -- 上文 2 轮 (4条) | |
| (SELECT m.role, m.content, m.created_at | |
| FROM messages m | |
| JOIN target_msg t ON m.conversation_id = t.conversation_id | |
| WHERE m.created_at < t.created_at | |
| ORDER BY m.created_at DESC LIMIT 4) | |
| UNION ALL | |
| -- 命中的那条本身 | |
| (SELECT m.role, m.content, m.created_at | |
| FROM messages m | |
| JOIN target_msg t ON m.conversation_id = t.conversation_id | |
| WHERE m.created_at = t.created_at) | |
| UNION ALL | |
| -- 下文 2 轮 (4条) | |
| (SELECT m.role, m.content, m.created_at | |
| FROM messages m | |
| JOIN target_msg t ON m.conversation_id = t.conversation_id | |
| WHERE m.created_at > t.created_at | |
| ORDER BY m.created_at ASC LIMIT 4) | |
| ) combined_results | |
| ORDER BY created_at ASC; | |
| """ | |
| cur.execute(sql, (user_id, f"%{keyword}%")) | |
| return cur.fetchall() | |
| except Exception as e: | |
| print(f"⚠️ PG 检索异常: {e}") | |
| return [] | |
| finally: | |
| conn.close() | |
| pg_rows = await asyncio.to_thread(_pg_search) | |
| if pg_rows: | |
| # SQL 中已经做好了 ASC 升序排列,直接拼接,去掉了多余的 reverse() | |
| drama_text = f"【系统从核心数据库精准召回了关于 '{keyword}' 的确切历史记录】:\n" | |
| for role, content in pg_rows: | |
| role_name = "用户" if role == 'user' else "您(AI专家)" | |
| drama_text += f"{role_name}: {content}\n" | |
| return [drama_text] | |
| print(f"ℹ️ PG 未命中 '{keyword}',触发 Qdrant 真实语义兜底...") | |
| try: | |
| # 【物理隔离】:装配厂兜底搜索时,同样强制锁定 session_id | |
| fallback_results = await search_qdrant_history(keyword, user_id, session_id=session_id, top_k=3) | |
| if fallback_results: | |
| chunks_text = "\n".join(fallback_results) if isinstance(fallback_results[0], str) else str(fallback_results) | |
| return [f"【系统从 Qdrant 远古记忆中召回了关于 '{keyword}' 的模糊关联碎片】:\n{chunks_text}"] | |
| except Exception as e: | |
| print(f"⚠️ Qdrant 兜底打捞失败: {e}") | |
| return [] |