Commit f2a8db86 by 黄南光

wiki加入长期记忆,鉴权控制等

1 parent d9ae969b
......@@ -223,19 +223,30 @@ REFLECT_ON_NEW_SESSION = _env_bool("REFLECT_ON_NEW_SESSION", "true")
# 收尾沉淀的最小轮数门槛,防止连点「新建会话」反复触发 LLM 调用。
REFLECT_ON_NEW_MIN_TURNS = int(os.environ.get("REFLECT_ON_NEW_MIN_TURNS", "5"))
# 删除会话时收尾沉淀的最小轮数门槛。删除是用户带二次确认的主动动作,不会像连点新建
# 那样刷 LLM,因此门槛更低(默认 1)——只要会话有过对话,删除前就把其价值吸收进长期记忆,
# 避免「叫你小虾」这类一两轮的显式约定因未达新建门槛而漏掉。
REFLECT_ON_DELETE_MIN_TURNS = int(os.environ.get("REFLECT_ON_DELETE_MIN_TURNS", "1"))
# 沉淀使用的模型,留空则复用 QUERY_MODEL_NAME
REFLECT_MODEL_NAME = os.environ.get("REFLECT_MODEL_NAME") or QUERY_MODEL_NAME
# 长期记忆后端:db=存 wiki_user_profiles.agent_md(本轮);mem0=外部记忆组件(预留)
MEMORY_STORE_BACKEND = os.environ.get("MEMORY_STORE_BACKEND", "db").strip().lower()
# 是否给问答 Agent 挂载「记忆工具」remember_user_memory:用户说「你记住…」时模型
# 即时调用它,把信息按性质分流写入用户画像或长期记忆。仅登录会话模式生效,外部 api 不挂。
REMEMBER_TOOL_ENABLED = _env_bool("REMEMBER_TOOL_ENABLED", "true")
# ---------------------------- 用户画像 ----------------------------
# agent.md 长期记忆的长度上限,超出时按「hits 少 + last 久」优先淘汰条目
# agent.md 长期记忆的长度上限(字符)。达到上限时**不再在代码端机械删条目**,
# 而是调 LLM 把长期记忆「融合汇总成高密度记忆」压回上限内(见 remember._llm_compact);
# 仅当 LLM 压缩失败/仍超限时才回退到机械裁剪 `_enforce_cap` 兜底保证有界。
AGENT_MD_MAX_CHARS = int(os.environ.get("AGENT_MD_MAX_CHARS", "4000"))
# user.md 岗位画像的长度上限
PROFILE_MD_MAX_CHARS = int(os.environ.get("PROFILE_MD_MAX_CHARS", "2000"))
# user.md 用户画像的长度上限(字符)。同上,超限走 LLM 融合汇总而非机械截断。
PROFILE_MD_MAX_CHARS = int(os.environ.get("PROFILE_MD_MAX_CHARS", "4000"))
# 用户首次登录时是否自动生成岗位画像(异步执行,不阻塞登录)
PROFILE_GEN_ON_LOGIN = _env_bool("PROFILE_GEN_ON_LOGIN", "true")
......
......@@ -410,7 +410,12 @@ export default function EnterpriseWiki() {
const [currentUser, setCurrentUser] = useState<CurrentUser | null>(null);
const [sessions, setSessions] = useState<SessionItem[]>([]);
const [currentSessionId, setCurrentSessionId] = useState<string | null>(null);
// 切换会话时拉取消息(只影响消息区),与会话列表加载区分开
const [sessionsLoading, setSessionsLoading] = useState(false);
// 仅首次拉取会话列表时为真,避免切换会话时侧栏误报「加载中」
const [listLoading, setListLoading] = useState(false);
// 新建会话进行中,用于禁用按钮 + 转圈,防止连点一次性建出多个会话
const [creatingSession, setCreatingSession] = useState(false);
// 会话列表默认展开
const [showSessionList, setShowSessionList] = useState(true);
// 接口失败等场景的全局提示
......@@ -454,6 +459,9 @@ export default function EnterpriseWiki() {
const openSession = useCallback(async (id: string) => {
setCurrentSessionId(id);
// 先清空旧消息再拉新会话,切换时消息区显示加载态而非停留在上一会话内容;
// 注意这里只动 sessionsLoading(消息区),不碰会话列表的加载态。
setChatHistory([]);
setSessionsLoading(true);
try {
const data = await fetchSessionMessages(id);
......@@ -466,6 +474,9 @@ export default function EnterpriseWiki() {
}, []);
const handleNewSession = useCallback(async () => {
// 防连点:新建进行中直接忽略后续点击,避免一次性建出多个会话
if (creatingSession) return;
setCreatingSession(true);
try {
// 带上当前会话 id:后端据此对上一个会话触发收尾沉淀(未达轮数门槛会跳过)
const data = await createSession(currentSessionId);
......@@ -475,8 +486,10 @@ export default function EnterpriseWiki() {
await refreshSessions();
} catch {
/* 新建失败时保持现状,用户可重试 */
} finally {
setCreatingSession(false);
}
}, [currentSessionId, refreshSessions]);
}, [creatingSession, currentSessionId, refreshSessions]);
const handleDeleteSession = useCallback(async () => {
if (!pendingDeleteSession) return;
......@@ -501,25 +514,39 @@ export default function EnterpriseWiki() {
}
}, [pendingDeleteSession, currentSessionId, refreshSessions, openSession]);
// 首次打开 Copilot 面板时拉取登录态与会话列表
// 每次打开 Copilot 面板:拉取登录态与会话列表,并默认落到「最近一个有内容的会话」,
// 避免因最新会话是空的「新会话」而打开即空白。若当前已停在一个有内容的会话上则不打扰。
useEffect(() => {
if (!isChatOpen || currentUser) return;
if (!isChatOpen) return;
let cancelled = false;
(async () => {
const me = await fetchMe().catch(() => null);
if (cancelled || !me) return;
setCurrentUser(me);
let me = currentUser;
if (!me) {
me = await fetchMe().catch(() => null);
if (cancelled || !me) return;
setCurrentUser(me);
}
setListLoading(true);
const items = await refreshSessions();
setListLoading(false);
if (cancelled) return;
if (items.length > 0) {
await openSession(items[0].id);
} else {
const data = await createSession(null).catch(() => null);
if (data && !cancelled) {
setCurrentSessionId(data.id);
await refreshSessions();
const current = items.find((s) => s.id === currentSessionId);
// 当前未选中、已失效、或停在空会话上 → 跳到最近一个有内容的会话
if (!current || current.totalTurns === 0) {
const target = items.find((s) => s.totalTurns > 0) ?? items[0];
if (target) {
if (target.id !== currentSessionId) await openSession(target.id);
} else {
// 一个会话都没有:新建一个空会话兜底
const data = await createSession(null).catch(() => null);
if (data && !cancelled) {
setCurrentSessionId(data.id);
setChatHistory([]);
await refreshSessions();
}
}
}
})();
......@@ -527,7 +554,9 @@ export default function EnterpriseWiki() {
return () => {
cancelled = true;
};
}, [isChatOpen, currentUser, refreshSessions, openSession]);
// 仅在面板开关切换时触发;其余依赖为闭包读取的当时值,无需追踪
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isChatOpen]);
// 每轮问答结束后刷新列表,让标题与「N 轮」计数保持最新
useEffect(() => {
......@@ -2372,7 +2401,8 @@ export default function EnterpriseWiki() {
<SessionSidebar
sessions={sessions}
currentId={currentSessionId}
loading={sessionsLoading}
loading={listLoading}
creating={creatingSession}
onSelect={openSession}
onCreate={handleNewSession}
onDelete={setPendingDeleteSession}
......@@ -2381,7 +2411,13 @@ export default function EnterpriseWiki() {
<div className="flex-1 flex flex-col min-w-0">
<div className="flex-1 overflow-y-auto p-6 scrollbar-thin bg-slate-50/50 flex flex-col">
{chatHistory.map((msg, idx) => (
{sessionsLoading && (
<div className="flex-1 flex items-center justify-center text-slate-400 text-xs gap-2">
<Loader2 className="w-4 h-4 animate-spin text-blue-600" />
加载会话…
</div>
)}
{!sessionsLoading && chatHistory.map((msg, idx) => (
<MessageBubble
key={idx}
role={msg.role}
......
"use client";
import { useState } from "react";
import { MessageSquare, SquarePen, Trash2 } from "lucide-react";
import { Loader2, MessageSquare, SquarePen, Trash2 } from "lucide-react";
import { cn } from "@/lib/utils";
import type { SessionItem } from "@/lib/auth";
......@@ -10,6 +10,7 @@ interface SessionSidebarProps {
sessions: SessionItem[];
currentId: string | null;
loading?: boolean;
creating?: boolean;
onSelect: (id: string) => void;
onCreate: () => void;
onDelete: (session: SessionItem) => void;
......@@ -38,6 +39,7 @@ export default function SessionSidebar({
sessions,
currentId,
loading = false,
creating = false,
onSelect,
onCreate,
onDelete,
......@@ -49,10 +51,20 @@ export default function SessionSidebar({
<div className="p-3 border-b border-slate-200">
<button
onClick={onCreate}
className="w-full flex items-center justify-center gap-1.5 bg-blue-600 hover:bg-blue-700 text-white text-xs font-semibold py-2 rounded-lg transition"
disabled={creating}
className="w-full flex items-center justify-center gap-1.5 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 disabled:cursor-wait text-white text-xs font-semibold py-2 rounded-lg transition"
>
<SquarePen className="w-3.5 h-3.5" />
新建会话
{creating ? (
<>
<Loader2 className="w-3.5 h-3.5 animate-spin" />
新建中…
</>
) : (
<>
<SquarePen className="w-3.5 h-3.5" />
新建会话
</>
)}
</button>
</div>
......
......@@ -148,6 +148,9 @@ export async function renameSession(sessionId: string, title: string) {
export interface ProfilePayload {
profileMd: string;
agentMd: string;
// 未剥离元信息的原文,供编辑器加载
profileMdRaw: string;
agentMdRaw: string;
profileGenerated: boolean;
profileVersion: number;
memoryStats: { chars: number; entries: number; maxChars: number };
......@@ -161,6 +164,41 @@ export async function regenerateProfile() {
return apiJson("/profile/regenerate", { method: "POST" });
}
/** 用户本人编辑自己的用户画像 / 长期记忆。 */
export async function updateMyProfile(payload: { profileMd?: string; agentMd?: string }) {
return apiJson("/profile", { method: "PATCH", body: JSON.stringify(payload) });
}
export async function clearMemory() {
return apiJson("/profile/memory", { method: "DELETE" });
}
// ============================== 管理员:用户画像编辑 ==============================
export interface AdminUserProfile {
userId: string;
displayName: string;
profileMd: string;
agentMd: string;
profileGenerated: boolean;
profileVersion: number;
memoryStats: { chars: number; entries: number; maxChars: number };
}
export async function fetchUserProfile(userId: string) {
return apiJson<AdminUserProfile>(`/admin/users/${userId}/profile`);
}
export async function updateUserProfile(
userId: string,
payload: { profileMd?: string; agentMd?: string }
) {
return apiJson(`/admin/users/${userId}/profile`, {
method: "PATCH",
body: JSON.stringify(payload),
});
}
export async function regenerateUserProfile(userId: string) {
return apiJson(`/admin/users/${userId}/profile/regenerate`, { method: "POST" });
}
......@@ -2,6 +2,7 @@
全部接口要求 role=admin。
"""
import asyncio
import logging
from datetime import datetime
......@@ -13,6 +14,8 @@ from src.database.models import WikiPosition, WikiUser, WikiUserProfile
from src.database.session import AsyncSessionLocal
from src.services.identity.local import build_password_fields
from src.services.identity.tokens import require_admin
from src.services.memory.profile_gen import generate_profile
from src.services.memory.store import get_memory_store
logger = logging.getLogger(__name__)
......@@ -172,6 +175,7 @@ async def update_user(
_: WikiUser = Depends(require_admin),
):
"""更新用户的岗位、门店、角色或启用状态。"""
position_changed = False
async with AsyncSessionLocal() as session:
user = await session.get(WikiUser, user_id)
if user is None:
......@@ -183,6 +187,7 @@ async def update_user(
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="岗位不存在")
# 岗位变更后画像需要重新生成
if position_id != user.position_id:
position_changed = True
profile = (
await session.execute(
select(WikiUserProfile).where(WikiUserProfile.user_id == user_id)
......@@ -211,9 +216,115 @@ async def update_user(
await session.commit()
# 岗位变更:立即异步重生成用户画像,无需等用户下次登录
if position_changed:
asyncio.create_task(_regenerate_quietly(user_id))
return {"success": True}
async def _regenerate_quietly(user_id: str) -> None:
"""后台重生成画像,任何异常都不影响主请求。"""
try:
await generate_profile(user_id, force=True)
except Exception as exc:
logger.warning("[Admin] 改岗后重生成画像失败(不影响): user_id=%s err=%s", user_id, exc)
# ==================================== 用户画像(管理员可编辑) ====================================
@router.get("/admin/users/{user_id}/profile")
async def get_user_profile(
user_id: str,
_: WikiUser = Depends(require_admin),
):
"""读取指定用户的岗位画像与长期记忆,供管理员查看/编辑。
与用户自查的 `/profile` 不同:这里的 `agentMd` 返回**未剥离元信息**的原文
(含 `<!-- hits:N last:... -->`),因为管理员是直接编辑档案本身。
"""
async with AsyncSessionLocal() as session:
user = await session.get(WikiUser, user_id)
if user is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
record = (
await session.execute(
select(WikiUserProfile).where(WikiUserProfile.user_id == user_id)
)
).scalars().first()
profile_md = (record.profile_md if record else "") or ""
agent_md = (record.agent_md if record else "") or ""
generated = bool(record.profile_generated) if record else False
version = (record.profile_version if record else 1) or 1
display_name = user.display_name
stats = await get_memory_store().stats(user_id)
return {
"success": True,
"userId": user_id,
"displayName": display_name,
"profileMd": profile_md,
"agentMd": agent_md,
"profileGenerated": generated,
"profileVersion": version,
"memoryStats": stats,
}
@router.patch("/admin/users/{user_id}/profile")
async def update_user_profile(
user_id: str,
data: dict = Body(...),
_: WikiUser = Depends(require_admin),
):
"""管理员编辑指定用户的岗位画像与/或长期记忆。
- 写 `profileMd` 时置 `profile_generated=True`,避免该用户下次登录时被首登画像覆盖。
- 写 `agentMd` 直接落 `agent_md` 字段,**不动** `reflected_upto_at` 沉淀游标
(管理员手改不代表沉淀进度变化)。
"""
async with AsyncSessionLocal() as session:
user = await session.get(WikiUser, user_id)
if user is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
record = (
await session.execute(
select(WikiUserProfile).where(WikiUserProfile.user_id == user_id)
)
).scalars().first()
if record is None:
record = WikiUserProfile(user_id=user_id, profile_generated=False)
session.add(record)
if "profileMd" in data:
record.profile_md = (data.get("profileMd") or "").strip() or None
record.profile_generated = True
if "agentMd" in data:
record.agent_md = (data.get("agentMd") or "").strip() or None
record.updated_at = datetime.now()
await session.commit()
logger.info("[Admin] 编辑用户画像: user_id=%s", user_id)
return {"success": True}
@router.post("/admin/users/{user_id}/profile/regenerate")
async def regenerate_user_profile(
user_id: str,
_: WikiUser = Depends(require_admin),
):
"""管理员为指定用户重新生成岗位画像(例如改岗后)。"""
result = await generate_profile(user_id, force=True)
logger.info("[Admin] 重新生成用户画像: user_id=%s -> %s", user_id, result.get("action"))
return {"success": result.get("action") == "generated", "detail": result}
# ==================================== 岗位模板 ====================================
......
......@@ -7,8 +7,9 @@
它与「删除会话」是完全不同的动作,不可混为一谈。
"""
import logging
from datetime import datetime
from fastapi import APIRouter, Depends
from fastapi import APIRouter, Body, Depends
from sqlalchemy import select
from src.database.models import WikiUser, WikiUserProfile
......@@ -24,7 +25,11 @@ router = APIRouter()
@router.get("/profile")
async def get_profile(user: WikiUser = Depends(get_current_user)):
"""读取当前用户的岗位画像与长期记忆(均为只读展示)。"""
"""读取当前用户的用户画像与长期记忆。
同时返回剥离元信息的展示版(`profileMd`/`agentMd`,供渲染)和未剥离的原文
(`profileMdRaw`/`agentMdRaw`,供编辑器加载,含 `<!-- hits/last -->` 注释)。
"""
async with AsyncSessionLocal() as session:
record = (
await session.execute(
......@@ -37,20 +42,56 @@ async def get_profile(user: WikiUser = Depends(get_current_user)):
version = (record.profile_version if record else 1) or 1
store = get_memory_store()
agent_md = await store.get_long_term(user.id)
agent_md_raw = await store.get_raw(user.id)
stats = await store.stats(user.id)
return {
"success": True,
# 岗位画像展示时也剥掉元信息注释,保持渲染干净
# 展示版剥掉元信息注释,保持渲染干净
"profileMd": strip_meta_comments(profile_md),
"agentMd": agent_md,
"agentMd": strip_meta_comments(agent_md_raw),
# 原文版供编辑器加载(保留元信息,保存时原样写回)
"profileMdRaw": profile_md,
"agentMdRaw": agent_md_raw,
"profileGenerated": generated,
"profileVersion": version,
"memoryStats": stats,
}
@router.patch("/profile")
async def update_my_profile(
data: dict = Body(...),
user: WikiUser = Depends(get_current_user),
):
"""用户本人编辑自己的用户画像 / 长期记忆(markdown 原文整体覆盖)。
只处理 body 中出现的字段:写 `profileMd` 时置 `profile_generated=True`,避免下次
登录被首登画像覆盖;写 `agentMd` 直接落库,不动 `reflected_upto_at` 沉淀游标。
"""
async with AsyncSessionLocal() as session:
record = (
await session.execute(
select(WikiUserProfile).where(WikiUserProfile.user_id == user.id)
)
).scalars().first()
if record is None:
record = WikiUserProfile(user_id=user.id, profile_generated=False)
session.add(record)
if "profileMd" in data:
record.profile_md = (data.get("profileMd") or "").strip() or None
record.profile_generated = True
if "agentMd" in data:
record.agent_md = (data.get("agentMd") or "").strip() or None
record.updated_at = datetime.now()
await session.commit()
logger.info("[Profile] 用户编辑画像/记忆: %s", user.username)
return {"success": True}
@router.post("/profile/regenerate")
async def regenerate_profile(user: WikiUser = Depends(get_current_user)):
"""重新生成岗位画像(例如岗位调整后)。"""
......
......@@ -15,14 +15,23 @@ from agentscope.agent import ReActAgent
from agentscope.message import Msg
from agentscope.tool import Toolkit
from config import QUERY_MODEL_NAME, WIKI_DIR
from config import QUERY_MODEL_NAME, REMEMBER_TOOL_ENABLED, WIKI_DIR
from src.database.models import WikiQueryLog
from src.database.session import AsyncSessionLocal
from src.services.identity.tokens import get_current_user_optional
from src.services.memory.assembler import build_context
from src.services.memory.remember import (
apply_remembered,
drain_pending,
forget_user_memory,
open_pending_scope,
remember_user_memory,
reset_pending_scope,
)
from src.services.memory.sessions import (
append_turn,
build_tool_calls_trace,
create_session,
get_owned_session,
)
......@@ -222,7 +231,7 @@ def load_index_map() -> str:
return "(知识库地图读取失败)"
def build_query_agent(memory_injection: str = "") -> ReActAgent:
def build_query_agent(memory_injection: str = "", enable_memory_tool: bool = False) -> ReActAgent:
"""
构建并配置用于检索 Wiki 的 AgentScope ReAct 智能体。
为智能体装载本地文件读取和搜索工具,注入「知识库地图」与业务 System Prompt。
......@@ -246,6 +255,10 @@ def build_query_agent(memory_injection: str = "") -> ReActAgent:
toolkit.register_tool_function(read_local_file) # 读取页面内容(主用)
toolkit.register_tool_function(glob_wiki_files) # 文件名匹配(定位路径)
toolkit.register_tool_function(grep_wiki_files) # 全文正则搜索(兜底)
# 记忆工具仅在登录会话模式注册;外部无状态调用不挂,避免向匿名调用暴露记忆能力
if enable_memory_tool:
toolkit.register_tool_function(remember_user_memory) # 新增记忆
toolkit.register_tool_function(forget_user_memory) # 删除/修改记忆
# 加载针对 llm-query 定制的提示词片段 + 知识库地图
skill_prompt = load_skill_prompt("llm-query")
......@@ -283,6 +296,15 @@ def build_query_agent(memory_injection: str = "") -> ReActAgent:
{skill_prompt}
"""
# 记忆工具用法提示:对全体登录用户恒定,属稳定前缀,不破坏共享缓存。
if enable_memory_tool:
sys_prompt += """
【长期记忆管理】你可以维护关于当前用户的画像与长期记忆(其内容已在下方注入,你能看到):
- 用户明确要求**记住**某条长期信息时(如"你记住…""以后…""我叫/我是/我负责…"),调用 `remember_user_memory`,按 category 选对类别(称呼/约定/偏好/关注/待办/身份/岗位/范围/品牌/门店/事实)。
- 用户要求**删除/忘记**某条记忆时(如"忘掉…""删掉…那条""别再记…"),调用 `forget_user_memory`,content 传要删除条目的关键内容。
- 用户要求**修改**某条记忆时(如"把X改成Y"),先 `forget_user_memory` 忘掉旧的,再 `remember_user_memory` 记住新的。
普通知识库问答无需调用;不要为一次性的临时信息调用。
"""
# 全局稳定前缀到此为止。个性化内容一律追加在最后,避免打碎共享缓存前缀。
if memory_injection:
sys_prompt += memory_injection
......@@ -336,13 +358,17 @@ class WikiQueryRunner:
error_msg: str | None = None
total_tokens = 0
# 记忆工具仅登录会话模式启用;开一个请求级暂存作用域供工具写入
enable_memory_tool = bool(self.user_id) and REMEMBER_TOOL_ENABLED
pending_token = open_pending_scope() if enable_memory_tool else None
# 进入 Token 统计上下文,方便在结束时获取请求消耗
async with token_counter_context() as get_tokens:
try:
# 装配个性化上下文(画像 + 长期记忆 + 会话记忆)。
# 外部无状态调用时 user_id 为 None,返回空上下文、不访问记忆表。
memory_injection = await self._build_memory_injection()
agent = build_query_agent(memory_injection)
agent = build_query_agent(memory_injection, enable_memory_tool=enable_memory_tool)
self._configure_agent(agent)
user_msg = Msg("user", self.user_query, role="user")
......@@ -409,11 +435,16 @@ class WikiQueryRunner:
# 会话模式:落库本轮问答并按需触发摘要(外部无状态调用不写记忆表)
if status == "Success" and self.user_id and self.session_id and answer:
persist_coro = self._persist_turn(answer)
# 同步取出本轮记忆工具暂存的条目,随落库一起处理(避免 contextvar 时序问题)
remembered = drain_pending() if enable_memory_tool else []
persist_coro = self._persist_turn(answer, remembered)
if self.event_queue:
asyncio.create_task(persist_coro)
else:
await persist_coro
# 归还请求级记忆暂存作用域
if pending_token is not None:
reset_pending_scope(pending_token)
logger.info(
"[Query] 查询结束: status=%s, tokens=%s, duration_ms=%s",
status,
......@@ -443,8 +474,8 @@ class WikiQueryRunner:
logger.warning("[Query] 记忆装配失败,本次降级为无个性化上下文: %s", exc)
return ""
async def _persist_turn(self, answer: str) -> None:
"""把本轮问答写入消息表,并按需触发增量摘要。
async def _persist_turn(self, answer: str, remembered: list | None = None) -> None:
"""把本轮问答写入消息表,落库记忆工具的即时记忆,并按需触发增量摘要。
`reasoning` 会先经 `sanitize_reasoning` 净化:**工具返回正文绝不落库**,
只保留工具名、成功与否与返回字节数。落库结果仅供前端重放,不回灌进 prompt。
......@@ -461,6 +492,14 @@ class WikiQueryRunner:
logger.exception("[Query] 会话消息落库失败: session_id=%s err=%s", self.session_id, exc)
return
# 记忆工具的即时记忆:按类别分流写入用户画像 / 长期记忆(失败不阻断)
if remembered:
try:
result = await apply_remembered(self.user_id, remembered)
logger.info("[Query] 即时记忆已落库: %s", result)
except Exception as exc:
logger.warning("[Query] 即时记忆落库失败: %s", exc)
try:
result = await maybe_summarize(self.session_id)
if result.get("action") == "summarized":
......
"""会话路由:列表 / 新建 / 读消息 / 重命名 / 删除。
会话的三个动作语义严格区分(取代原先含义模糊的「清空会话」):
- **新建会话**:旧会话完整保留在列表中,并对其条件触发收尾沉淀
- **删除会话**:软删除,且**不触发沉淀**——用户删除往往正因为聊歪了,
把用户明确想丢弃的内容沉淀进长期记忆是与其意图相反的
- **新建会话**:旧会话完整保留在列表中,并对其条件触发收尾沉淀(门槛 REFLECT_ON_NEW_MIN_TURNS)
- **删除会话**:软删除,删除前用较低门槛(REFLECT_ON_DELETE_MIN_TURNS,默认1)做收尾沉淀,
确保「叫你小虾」这类一两轮的显式约定不因删除而漏掉长期记忆
- **清空长期记忆**:独立入口(见 profile 路由),与会话数据无关
"""
import logging
from fastapi import APIRouter, Body, Depends, HTTPException, Query, status
from config import SESSION_LIST_PAGE_SIZE
from config import REFLECT_ON_DELETE_MIN_TURNS, SESSION_LIST_PAGE_SIZE
from src.database.models import WikiUser
from src.services.identity.tokens import get_current_user
from src.services.memory.reflector import reflect_on_session_end
......@@ -118,9 +118,13 @@ async def delete_session(
if record is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="会话不存在")
# 删除前沉淀:把这段会话学到的稳定事实并入 agent.md
# 删除前沉淀:把这段会话学到的稳定事实并入 agent.md。
# 删除用较低的轮数门槛(REFLECT_ON_DELETE_MIN_TURNS,默认1),确保「叫你小虾」这类
# 一两轮的显式约定也能在删除前被吸收,不因未达新建门槛而漏掉。
try:
await reflect_on_session_end(user.id, session_id)
await reflect_on_session_end(
user.id, session_id, min_turns=REFLECT_ON_DELETE_MIN_TURNS
)
except Exception as exc:
# 沉淀失败不应阻断删除本身
logger.warning("[Session] 删除前沉淀失败(不影响删除): session=%s err=%s", session_id, exc)
......
......@@ -43,7 +43,7 @@ class MemoryContext:
parts: list[str] = []
if self.profile_md:
parts.append("【当前用户的岗位画像】用于理解用户身份与知识范围:\n" + self.profile_md)
parts.append("【当前用户的用户画像】用于理解用户身份与知识范围:\n" + self.profile_md)
if self.agent_md:
parts.append("【关于该用户的长期记忆】历史使用中沉淀的习惯与偏好:\n" + self.agent_md)
......
"""首登岗位画像生成。
"""首登用户画像生成。
用户首次登录时,据其岗位取出职责与常用操作模板,交给 LLM 做**基于模板的
个性化改写**——不是凭空编造。模板是"半成品",LLM 只负责结合该用户的
具体属性(品牌、门店、部门)把它写成一份可读的画像。
忠实改写**——只用数据库里确有的信息,缺数据的小节直接留空/省略,**不凭空编造**。
模板是"半成品",LLM 只负责结合该用户的具体属性(品牌、门店、部门)整理成一份可读画像。
约 13 个岗位在源数据中没有职责模板(董事长、总经理、各类工程师),
这些岗位的 `template_missing=True`,此时 LLM 仅据岗位名生成基础画像,
不阻塞流程,后续管理员可在管理页补齐模板再重新生成。
这些岗位 `template_missing=True`,此时对应小节留空,后续管理员可在管理页补齐模板再重新生成。
「补充画像」小节不由本生成器写,交给记忆工具/反思增量维护,避免重生成时被覆盖。
执行时机:登录成功后**异步**触发,不阻塞登录响应。
生成完成前画像段落为空,问答照常可用。
......@@ -23,21 +24,22 @@ from src.services.memory.llm_call import complete_text
logger = logging.getLogger(__name__)
_PROFILE_PROMPT = """你在为一位企业员工生成岗位画像,供知识库问答助手理解其身份与知识范围。
_PROFILE_PROMPT = """你在为一位企业员工生成**用户画像**,供知识库问答助手理解其身份与知识范围。
**最重要的原则:只使用下方明确提供的数据,数据库没有的信息一律留空或省略该小节,严禁编造。**
严格要求:
1. 输出必须且只能包含以下四个小节:
1. 至多包含以下四个小节,顺序固定;**某小节缺少可用数据时,整节省略,不要硬写、不要臆造**:
## 基本信息
## 岗位职责
## 常用操作
## 知识范围
2. 「岗位职责」必须**基于下方提供的职责模板改写**,结合该员工的具体部门与门店做贴合表述。
**禁止编造模板中不存在的职责**。若模板为空,则仅根据岗位名称写出该岗位最典型的 3-5 条职责,
并保持克制、不要臆造公司特定的制度细节。
3. 「常用操作」写该岗位在知识库中最可能查询的问题类型,3-6 条。
4. 「知识范围」写该员工应关注的品牌与业务范围,供问答时防止跨品牌串味。
5. 全文使用简洁的 markdown 无序列表,总长度不超过 {max_chars} 字符。
6. 只输出画像正文,不要解释、不要客套、不要代码块包裹。
2. 「基本信息」只列**下方员工信息中确实存在**的字段(姓名/岗位/部门/负责门店);标注为「(无)/(未指定)」的字段不要列出。
3. 「岗位职责」**严格依据下方「岗位职责模板」精炼改写**,不得扩写、不得新增模板里没有的职责。**模板为空/占位时整节省略**(不要根据岗位名自行编造职责)。
4. 「常用操作」**严格依据下方「常用操作模板」**;为空则整节省略。
5. 「知识范围」只写下方明确给出的负责品牌/业务;没有则整节省略。
6. 全文简洁 markdown 无序列表,总长度不超过 {max_chars} 字符。
7. 只输出画像正文,不要解释、不要客套、不要代码块包裹。若四个小节都无数据,则只输出「## 基本信息」及已知字段。
【员工信息】
姓名:{display_name}
......@@ -94,8 +96,8 @@ async def generate_profile(user_id: str, force: bool = False) -> dict:
position.dept_l1 if position else None,
position.dept_l2 if position else None,
])) or "(未指定)"
duty_template = (position.duty_template if position else None) or "(无模板,请仅据岗位名称生成)"
ops_template = (position.common_ops_template if position else None) or "(无模板)"
duty_template = (position.duty_template if position else None) or "(无,本节请省略)"
ops_template = (position.common_ops_template if position else None) or "(无,本节请省略)"
profile_md = await _call_llm_profile(
display_name=display_name,
......
"""Wiki 问答答案渲染的 append-only 时间线契约。
核心约束:assistant 的每个 text block 各占一个 part,按 id 覆盖、按到达顺序追加,
**绝不回撤**。历史上这里用时间去抖猜测「本轮是不是最终回答」,猜错就发一帧空内容
清空气泡,表现为「前导文字闪一下又消失」。这些用例锁住不会再退回那个实现。
"""
import asyncio
import unittest
from agentscope.message import Msg
from src.api.routes.query import WikiQueryRunner
def _text_msg(msg_id: str, text: str) -> Msg:
msg = Msg("WikiAssistant", [{"type": "text", "text": text}], "assistant")
msg.id = msg_id
return msg
def _text_and_tool_msg(msg_id: str, text: str, tool_name: str = "read_local_file") -> Msg:
msg = Msg(
"WikiAssistant",
[
{"type": "text", "text": text},
{"type": "tool_use", "id": f"{msg_id}-call", "name": tool_name, "input": {"file_path": "a.md"}},
],
"assistant",
)
msg.id = msg_id
return msg
class _FakeAgent:
"""只提供 _configure_agent 需要的最小接口。"""
def __init__(self) -> None:
self.print = None
def set_console_output_enabled(self, enabled: bool) -> None: # noqa: ARG002
pass
class QueryAnswerTimelineTest(unittest.TestCase):
def setUp(self) -> None:
self.queue: asyncio.Queue = asyncio.Queue()
self.runner = WikiQueryRunner("测试问题", [], session_id="t", event_queue=self.queue)
agent = _FakeAgent()
self.runner._configure_agent(agent)
self.hooked_print = agent.print
def _feed(self, *msgs: Msg) -> None:
async def run() -> None:
for msg in msgs:
await self.hooked_print(msg, True)
asyncio.run(run())
def _drain(self) -> list[dict]:
events = []
while not self.queue.empty():
events.append(self.queue.get_nowait())
return events
def _bot_events(self) -> list[dict]:
return [e for e in self._drain() if e.get("type") == "bot"]
def test_preamble_before_tool_call_is_never_retracted(self):
"""前导文字 + 随后的 tool_use:绝不能出现清空气泡的空内容帧。"""
self._feed(
_text_msg("msg-A", "好的,我先检索话术。"),
_text_and_tool_msg("msg-A", "好的,我先检索话术。"),
)
bots = self._bot_events()
self.assertTrue(bots, "前导文字应当作为答案 part 推送")
self.assertEqual(
[e for e in bots if e["content"] == ""],
[],
"出现了空内容的 bot 事件 = 回撤清空气泡,正是要根除的泄漏闪烁",
)
self.assertEqual({e["id"] for e in bots}, {"msg-A-answer"})
def test_multiple_rounds_become_ordered_parts(self):
"""跨轮 text 各占一个 part,id 不同、按序到达,前端 join 后即完整时间线。"""
self._feed(
_text_msg("msg-A", "我先查一下知识库。"),
_text_msg("msg-B", "以下是应对话术。"),
)
bots = self._bot_events()
self.assertEqual([e["id"] for e in bots], ["msg-A-answer", "msg-B-answer"])
# 复现前端 messageMap[id] = content; Object.values(map).join("")
message_map: dict[str, str] = {}
for event in bots:
message_map[event["id"]] = event["content"]
self.assertEqual("".join(message_map.values()), "我先查一下知识库。以下是应对话术。")
def test_same_round_streams_incrementally(self):
"""同一轮内按 id 覆盖,内容单调增长(逐字流式)。"""
self._feed(
_text_msg("msg-A", "以下"),
_text_msg("msg-A", "以下是应对"),
_text_msg("msg-A", "以下是应对话术。"),
)
bots = self._bot_events()
self.assertEqual({e["id"] for e in bots}, {"msg-A-answer"})
contents = [e["content"] for e in bots]
self.assertEqual(contents, ["以下", "以下是应对", "以下是应对话术。"])
def test_emit_answer_overwrites_last_part_only(self):
"""权威收尾覆盖最后一个 part,更早的前导 part 原样保留。"""
self._feed(
_text_msg("msg-A", "我先查一下知识库。"),
_text_msg("msg-B", "草稿答案"),
)
self._drain()
asyncio.run(self.runner._emit_answer("清洗后的最终答案"))
bots = self._bot_events()
self.assertEqual(len(bots), 1)
self.assertEqual(bots[0]["id"], "msg-B-answer", "应覆盖最后一个 part,而非固定 id")
self.assertEqual(bots[0]["content"], "清洗后的最终答案")
def test_emit_answer_falls_back_when_no_text_part(self):
"""异常/兜底路径下没有任何 text part 时,回落到固定 id 新起一个 part。"""
asyncio.run(self.runner._emit_answer("兜底回答"))
bots = self._bot_events()
self.assertEqual(len(bots), 1)
self.assertEqual(bots[0]["id"], "final-answer")
def test_tool_events_still_go_to_reasoning_box(self):
"""工具调用/返回仍走思考框,前端折叠框功能不受影响。"""
self._feed(_text_and_tool_msg("msg-A", "查一下。"))
events = self._drain()
calls = [e for e in events if e.get("type") == "call"]
self.assertEqual(len(calls), 1)
self.assertEqual(calls[0]["name"], "read_local_file")
self.assertTrue(calls[0]["id"].startswith("call-"))
def test_debounce_heuristics_are_gone(self):
"""锁死:去抖/回撤/粘性标记这套启发式不得复活。"""
import src.api.routes.query as query_module
self.assertFalse(hasattr(query_module, "ANSWER_COMMIT_DEBOUNCE"))
for attr in ("_msg_has_tool", "_answer_sent_len", "_text_first_ts"):
self.assertFalse(hasattr(self.runner, attr), f"{attr} 应已删除")
if __name__ == "__main__":
unittest.main()
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!