Spaces:
Runtime error
Runtime error
Update agent/memory_sync.py
Browse files- agent/memory_sync.py +56 -61
agent/memory_sync.py
CHANGED
|
@@ -100,7 +100,6 @@ async def run_memory_washer(user_id: str):
|
|
| 100 |
cur.execute("""
|
| 101 |
SELECT conversation_id, title
|
| 102 |
FROM conversations
|
| 103 |
-
-- 【逻辑修复】:同时兼容 FALSE 和未初始化的 NULL
|
| 104 |
WHERE user_id = %s AND (is_vectorized = FALSE OR is_vectorized IS NULL) AND status = 'active'
|
| 105 |
""", (user_id,))
|
| 106 |
unwashed_convs = cur.fetchall()
|
|
@@ -113,11 +112,9 @@ async def run_memory_washer(user_id: str):
|
|
| 113 |
gemini_api_key = os.environ.get("GEMINI_API_KEY", "")
|
| 114 |
|
| 115 |
if not llama_api_key or not gemini_api_key or not llama_base_url:
|
| 116 |
-
logging.error("🛑 环境变量缺失:LLAMA 或 GEMINI 配置为空")
|
| 117 |
return
|
| 118 |
|
| 119 |
async with httpx.AsyncClient() as client:
|
| 120 |
-
# 确保 Qdrant 目标存在
|
| 121 |
try:
|
| 122 |
await client.put("http://localhost:6333/collections/user_memories", json={
|
| 123 |
"vectors": {"size": 768, "distance": "Cosine"}
|
|
@@ -128,62 +125,60 @@ async def run_memory_washer(user_id: str):
|
|
| 128 |
for conv_id, title in unwashed_convs:
|
| 129 |
cur.execute("SELECT role, content FROM messages WHERE conversation_id = %s ORDER BY created_at ASC", (conv_id,))
|
| 130 |
msgs = cur.fetchall()
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
|
|
|
|
|
|
| 138 |
要求:
|
| 139 |
1. 去除所有寒暄、大模型的说教和毫无意义的套话。
|
| 140 |
-
2. 以第一人称
|
| 141 |
-
3. 如果
|
| 142 |
|
| 143 |
对话记录:
|
| 144 |
{chat_text[:8000]}"""
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
if not fact_text or "无有效事实" in fact_text or len(fact_text) < 10:
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
continue
|
| 167 |
-
|
| 168 |
-
# 4. Gemini 向量化 (100% 对齐���上传的 retrieval.py 真实契约)
|
| 169 |
-
gemini_url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-001:embedContent?key={gemini_api_key}"
|
| 170 |
-
gemini_payload = {
|
| 171 |
-
"model": "models/gemini-embedding-001",
|
| 172 |
-
"content": {"parts": [{"text": fact_text}]},
|
| 173 |
-
"taskType": "RETRIEVAL_DOCUMENT",
|
| 174 |
-
"outputDimensionality": 768
|
| 175 |
-
}
|
| 176 |
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
-
#
|
| 187 |
point_id = str(uuid.uuid4())
|
| 188 |
qdrant_payload = {
|
| 189 |
"points": [{
|
|
@@ -193,23 +188,23 @@ async def run_memory_washer(user_id: str):
|
|
| 193 |
"user_id": user_id,
|
| 194 |
"source_conversation_id": conv_id,
|
| 195 |
"memory_type": "conversation_fact",
|
| 196 |
-
"content": fact_text,
|
|
|
|
| 197 |
"timestamp": int(time.time())
|
| 198 |
}
|
| 199 |
}]
|
| 200 |
}
|
| 201 |
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
|
| 210 |
-
except Exception
|
| 211 |
conn.rollback()
|
| 212 |
-
logging.error(f"🛑 洗菜工致命异常: {str(e)}")
|
| 213 |
finally:
|
| 214 |
cur.close()
|
| 215 |
conn.close()
|
|
|
|
| 100 |
cur.execute("""
|
| 101 |
SELECT conversation_id, title
|
| 102 |
FROM conversations
|
|
|
|
| 103 |
WHERE user_id = %s AND (is_vectorized = FALSE OR is_vectorized IS NULL) AND status = 'active'
|
| 104 |
""", (user_id,))
|
| 105 |
unwashed_convs = cur.fetchall()
|
|
|
|
| 112 |
gemini_api_key = os.environ.get("GEMINI_API_KEY", "")
|
| 113 |
|
| 114 |
if not llama_api_key or not gemini_api_key or not llama_base_url:
|
|
|
|
| 115 |
return
|
| 116 |
|
| 117 |
async with httpx.AsyncClient() as client:
|
|
|
|
| 118 |
try:
|
| 119 |
await client.put("http://localhost:6333/collections/user_memories", json={
|
| 120 |
"vectors": {"size": 768, "distance": "Cosine"}
|
|
|
|
| 125 |
for conv_id, title in unwashed_convs:
|
| 126 |
cur.execute("SELECT role, content FROM messages WHERE conversation_id = %s ORDER BY created_at ASC", (conv_id,))
|
| 127 |
msgs = cur.fetchall()
|
| 128 |
+
|
| 129 |
+
# 即使消息过少,也要生成一个带时间戳的空记忆节点
|
| 130 |
+
chat_text = "\n".join([f"{m[0]}: {m[1]}" for m in msgs]) if len(msgs) >= 2 else ""
|
| 131 |
+
|
| 132 |
+
is_empty_fact = False
|
| 133 |
+
fact_text = ""
|
| 134 |
+
|
| 135 |
+
if chat_text:
|
| 136 |
+
prompt = f"""你是一个专业的商业事实提取器。请分析以下对话记录,提取出用户业务相关的核心客观事实。
|
| 137 |
要求:
|
| 138 |
1. 去除所有寒暄、大模型的说教和毫无意义的套话。
|
| 139 |
+
2. 以第一人称视角,输出一段高度浓缩的纯文本摘要(不超过300字)。
|
| 140 |
+
3. 如果没有包含实质性的商业事实,请务必且只能回复:无有效事实
|
| 141 |
|
| 142 |
对话记录:
|
| 143 |
{chat_text[:8000]}"""
|
| 144 |
+
try:
|
| 145 |
+
llama_resp = await client.post(
|
| 146 |
+
f"{llama_base_url}/chat/completions",
|
| 147 |
+
headers={"Authorization": f"Bearer {llama_api_key}"},
|
| 148 |
+
json={
|
| 149 |
+
"model": "meta-llama/llama-3.1-8b-instruct",
|
| 150 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 151 |
+
"temperature": 0.1
|
| 152 |
+
},
|
| 153 |
+
timeout=30.0
|
| 154 |
+
)
|
| 155 |
+
llama_data = llama_resp.json()
|
| 156 |
+
fact_text = llama_data.get("choices", [{}])[0].get("message", {}).get("content", "").strip()
|
| 157 |
+
except Exception:
|
| 158 |
+
pass
|
| 159 |
+
|
| 160 |
+
# 【架构级修复】:将“有无事实”与“写入动作”解耦
|
|
|
|
| 161 |
if not fact_text or "无有效事实" in fact_text or len(fact_text) < 10:
|
| 162 |
+
is_empty_fact = True
|
| 163 |
+
fact_text = "无商业事实的闲聊与过渡记录" # 用于占位生成向量,维持空间结构
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
+
# 【底层 Bug 修复】:严格使用您契约里的 models/text-embedding-001
|
| 166 |
+
try:
|
| 167 |
+
gemini_url = f"https://generativelanguage.googleapis.com/v1beta/models/text-embedding-001:embedContent?key={gemini_api_key}"
|
| 168 |
+
gemini_payload = {
|
| 169 |
+
"model": "models/text-embedding-001",
|
| 170 |
+
"content": {"parts": [{"text": fact_text}]},
|
| 171 |
+
"taskType": "RETRIEVAL_DOCUMENT"
|
| 172 |
+
}
|
| 173 |
+
gemini_resp = await client.post(gemini_url, json=gemini_payload, timeout=15.0)
|
| 174 |
+
gemini_data = gemini_resp.json()
|
| 175 |
+
embedding = gemini_data.get("embedding", {}).get("values", [])
|
| 176 |
+
if not embedding:
|
| 177 |
+
continue # 只有 API 彻底断联才跳过,绝不因为业务逻辑跳过
|
| 178 |
+
except Exception:
|
| 179 |
+
continue
|
| 180 |
|
| 181 |
+
# 无论是否有事实,一律打上时间戳压入 Qdrant,记录系统状态
|
| 182 |
point_id = str(uuid.uuid4())
|
| 183 |
qdrant_payload = {
|
| 184 |
"points": [{
|
|
|
|
| 188 |
"user_id": user_id,
|
| 189 |
"source_conversation_id": conv_id,
|
| 190 |
"memory_type": "conversation_fact",
|
| 191 |
+
"content": "" if is_empty_fact else fact_text, # 真正的空值在此体现
|
| 192 |
+
"is_empty": is_empty_fact,
|
| 193 |
"timestamp": int(time.time())
|
| 194 |
}
|
| 195 |
}]
|
| 196 |
}
|
| 197 |
|
| 198 |
+
try:
|
| 199 |
+
qdrant_resp = await client.put("http://localhost:6333/collections/user_memories/points?wait=true", json=qdrant_payload, timeout=10.0)
|
| 200 |
+
if qdrant_resp.status_code == 200:
|
| 201 |
+
cur.execute("UPDATE conversations SET is_vectorized = TRUE WHERE conversation_id = %s", (conv_id,))
|
| 202 |
+
conn.commit()
|
| 203 |
+
except Exception:
|
| 204 |
+
continue
|
| 205 |
|
| 206 |
+
except Exception:
|
| 207 |
conn.rollback()
|
|
|
|
| 208 |
finally:
|
| 209 |
cur.close()
|
| 210 |
conn.close()
|