shensuming commited on
Commit
a4c1951
·
verified ·
1 Parent(s): ecbbe94

Update agent/memory_sync.py

Browse files
Files changed (1) hide show
  1. 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
- if len(msgs) < 2:
132
- cur.execute("UPDATE conversations SET is_vectorized = TRUE WHERE conversation_id = %s", (conv_id,))
133
- conn.commit()
134
- continue
135
-
136
- chat_text = "\n".join([f"{m[0]}: {m[1]}" for m in msgs])
137
- prompt = f"""你是一个专业的商业事实提取器。请分析以下对话记录,提取出用户业务相关的核心客观事实(如:公司规模、所在行业、面临的具体问题、已做出的决策、核心指标)。
 
 
138
  要求:
139
  1. 去除所有寒暄、大模型的说教和毫无意义的套话。
140
- 2. 以第一人称(“我”或“我们公司”)的视角,输出一段高度浓缩的纯文本摘要(不超过300字)。
141
- 3. 如果对话中没有包含实质性的商业事实(例如只是闲聊或测试),请务必且只能回复四个字:无有效事实
142
 
143
  对话记录:
144
  {chat_text[:8000]}"""
145
-
146
- # 3. Llama 推理 (Fail-Fast 机制)
147
- llama_resp = await client.post(
148
- f"{llama_base_url}/chat/completions",
149
- headers={"Authorization": f"Bearer {llama_api_key}"},
150
- json={
151
- "model": "meta-llama/llama-3.1-8b-instruct",
152
- "messages": [{"role": "user", "content": prompt}],
153
- "temperature": 0.1
154
- },
155
- timeout=30.0
156
- )
157
- if llama_resp.status_code != 200:
158
- raise RuntimeError(f"Llama API 拒绝响应: {llama_resp.text}")
159
-
160
- llama_data = llama_resp.json()
161
- fact_text = llama_data.get("choices", [{}])[0].get("message", {}).get("content", "").strip()
162
-
163
  if not fact_text or "无有效事实" in fact_text or len(fact_text) < 10:
164
- cur.execute("UPDATE conversations SET is_vectorized = TRUE WHERE conversation_id = %s", (conv_id,))
165
- conn.commit()
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
- gemini_resp = await client.post(gemini_url, json=gemini_payload, timeout=15.0)
178
- if gemini_resp.status_code != 200:
179
- raise RuntimeError(f"Gemini API 拒绝响应: {gemini_resp.text}")
180
-
181
- gemini_data = gemini_resp.json()
182
- embedding = gemini_data.get("embedding", {}).get("values", [])
183
- if not embedding:
184
- raise RuntimeError("Gemini 返回200但未解析到向量数组")
 
 
 
 
 
 
 
185
 
186
- # 5. Qdrant 落库
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
- qdrant_resp = await client.put("http://localhost:6333/collections/user_memories/points?wait=true", json=qdrant_payload, timeout=10.0)
203
- if qdrant_resp.status_code == 200:
204
- cur.execute("UPDATE conversations SET is_vectorized = TRUE WHERE conversation_id = %s", (conv_id,))
205
- conn.commit()
206
- logging.warning(f"✅ Qdrant记忆结晶成功:{conv_id}")
207
- else:
208
- raise RuntimeError(f"Qdrant 拒绝写入: {qdrant_resp.text}")
209
 
210
- except Exception as e:
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()