Files
AgentLab/backend/app/engine/nodes/knowledge.py
T
ThearchyHelios df935599f2 知识库:换 embedding 模型不再 500,检索能回指了
三件事,都是"这三个模块一条测试都没有"的后果。

**换 embedder 会让检索整体 500。** 库里是 512 维的本地向量、查询是 1536 维的
远端向量时,cosine 直接 `shapes (1536,) and (512,) not aligned`。from_blob 有
dim 参数,但 kb.py 和 memory/store.py 调用时都没传;而且存量向量属于哪个模型
代码里没有任何地方记着,所以也无从降级。

Chunk / MemoryItem 各加 embed_model + embed_dim(走现成的 _COLUMN_MIGRATIONS,
存量回填空值,正好表示"不知道是谁建的")。检索遇到对不上的向量整体退回纯
关键词并说破,不是把它们当 0 分静默沉底——那样用户看到的是结果莫名其妙变差,
而不是"这里有一批索引该重建了"。配套 kb.reindex + POST /api/kb/reindex。

长期记忆那份一起修了。判重那条更危险:维度碰巧相同但模型不同时 cosine 算出来
是随机数,会把不相关的旧记忆认成"重复",然后把新内容丢掉。

**默认 embedder 没有语义能力,而开关藏在一个环境变量里。** LocalEmbedder 是
特征哈希 + TF,和 BM25 吃同一批词;alpha 默认 0.5 等于给了它一半权重,同义
改写一条都召不回。开启真模型的唯一开关是 AGENTLAB_USE_OPENAI_EMBEDDINGS——
没界面、没人会发现。改成设置项(照 COPILOT_SETTING_KEY 的路子),知识库页顶部
能选能看能重建。

配置失败必须响:第一版写成静默退回本地,但选了 OpenAI 却拿到哈希向量的人,
在搜不出同义表达时完全无从怀疑到这里。现在抛 EmbedderUnavailable,API 400
原样交回"检查 OPENAI_API_KEY 是否配了",且不会把配置改掉。

**检索结果不进工件库。** db_query、工具节点、agent 工具调用都落 put_json 快照,
run_retrieve 什么都不落——于是结论只要来自知识库,"这个数是哪来的"就断在这儿,
而数字回指正是这个项目的签名能力。现在落 kind="retrieval_snapshot",并发一条
retrieve.end 带 artifact id。解码层补了正式映射(原来会掉进"未知事件"兜底,
画成一坨原始 JSON)。

新增 test_kb.py 11 条,补上这三个模块此前的零覆盖,包括 embeddings.py 里
注释记着、但一直没有测试守的那个归一化边界(单条候选被 min_score 误杀)。

端到端在真实服务上验过:撞上存量向量返回 200 + 降级说明(以前 500)、
重建后 stale 归零、配不起来的远端模型 400 且配置不变。
2026-09-19 09:27:07 +08:00

137 lines
5.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
import json
from typing import Any
from app.core.events import EventType
from app.db.base import SessionLocal
from app.engine.context import NodeContext, NodeError
from app.engine.state import GraphState, template_context
from app.memory import kb, store
async def run_memory(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
"""长期记忆读写节点。
把记忆做成画布上的一个节点,而不是藏在 agent 内部,是为了让"什么时候记、
记什么、记到哪个 scope"变成可见、可调的编排决策。
"""
action = ctx.cfg("action", "recall") # recall | write | clear
scope = ctx.render_str(ctx.cfg("scope", "") or ctx.run.memory_scope, state)
async with SessionLocal() as session:
if action == "recall":
query = ctx.render_str(ctx.cfg("query", "{{ last_message }}"), state)
limit = int(ctx.cfg("limit", 5) or 5)
hits = await store.recall(
session, scope=scope, query=query, limit=limit, kind=ctx.cfg("kind") or None
)
text = "\n".join(f"- {h['content']}" for h in hits)
result: dict[str, Any] = {
"memories": hits,
"count": len(hits),
"text": text,
"scope": scope,
}
elif action == "write":
content = ctx.render_str(ctx.cfg("content", ""), state)
if not content.strip():
raise NodeError(ctx.node.id, "记忆写入节点没有内容")
item = await store.remember(
session,
scope=scope,
content=content,
kind=ctx.cfg("kind", "fact") or "fact",
importance=float(ctx.cfg("importance", 0.5) or 0.5),
meta={"run_id": ctx.run.run_id, "node_id": ctx.node.id},
)
result = {"id": item.id, "saved": True, "scope": scope, "content": item.content}
elif action == "clear":
removed = await store.clear_scope(session, scope)
result = {"cleared": removed, "scope": scope}
else:
raise NodeError(ctx.node.id, f"未知的记忆操作:{action}")
ctx.emit(EventType.LOG, level="info",
message=f"记忆 {action} @ {scope}:{result.get('count', result.get('cleared', 1))} 条")
updates: dict[str, Any] = {"nodes": {ctx.node.id: result}}
var_name = ctx.cfg("assign_to", "")
if var_name:
updates["vars"] = {var_name: result.get("text", result)}
return updates
async def run_retrieve(state: GraphState, ctx: NodeContext) -> dict[str, Any]:
"""知识库检索节点。输出既有结构化命中列表,也有拼好的上下文文本。"""
query = ctx.render_str(ctx.cfg("query", "{{ last_message }}"), state)
if not query.strip():
raise NodeError(ctx.node.id, "检索节点没有查询内容")
collection = ctx.render_str(ctx.cfg("collection", "") or ctx.run.collection, state)
limit = int(ctx.cfg("limit", 5) or 5)
alpha = float(ctx.cfg("alpha", 0.5) or 0.5) # 1=纯向量,0=纯关键词
degraded: list[str] = []
async with SessionLocal() as session:
hits = await kb.search(
session, collection=collection, query=query, limit=limit, alpha=alpha,
on_degrade=degraded.append,
)
for note in degraded:
# 检索悄悄少了一半能力,不说的话用户只会觉得"最近搜得不准"
ctx.emit(EventType.LOG, level="warn", message=note)
min_score = float(ctx.cfg("min_score", 0.0) or 0.0)
hits = [h for h in hits if h["score"] >= min_score]
# 拼成可以直接塞进 prompt 的上下文,带编号方便模型引用出处
context_text = "\n\n".join(
f"[{i + 1}] {h['title']}(片段 {h['ordinal']})\n{h['content']}"
for i, h in enumerate(hits)
)
# 命中落工件库。SQL 取数、工具调用、agent 工具调用都有快照,检索一直没有,
# 于是结论只要来自知识库,"这个数是哪来的"这条链就断在这儿
from app.core.artifact_store import put_json
from app.memory.embeddings import embedder_id
snapshot: str | None = None
try:
snapshot = await put_json(
{
"query": query, "collection": collection,
"alpha": alpha, "min_score": min_score,
"embedder": embedder_id(), "degraded": degraded,
"hits": hits,
},
kind="retrieval_snapshot",
run_id=ctx.run.run_id, node_id=ctx.node.id,
)
except Exception: # noqa: BLE001 - 存不下不影响这次检索本身
snapshot = None
ctx.emit(
EventType.RETRIEVE_END,
collection=collection,
query=query[:200],
count=len(hits),
top_score=hits[0]["score"] if hits else 0,
degraded=bool(degraded),
artifact=snapshot,
)
result = {
"hits": hits,
"count": len(hits),
"text": context_text,
"query": query,
"collection": collection,
"artifact": snapshot,
}
updates: dict[str, Any] = {"nodes": {ctx.node.id: result}}
var_name = ctx.cfg("assign_to", "")
if var_name:
updates["vars"] = {var_name: context_text}
return updates