This commit is contained in:
许海洋 committed 2026-05-22 11:49:53 +08:00
commit 667b365a84
94 files changed
+6430 -2390

No files matched your search

@@ -59,11 +59,18 @@ def load_agent_config(agent_id: str | None) -> AgentConfig | None:
agent_id: The agent storage/runtime id.
Returns:
AgentConfig instance.
AgentConfig instance, or ``None`` when the on-disk artifacts are missing.
Raises:
FileNotFoundError: If the agent directory or config.yaml does not exist.
ValueError: If config.yaml cannot be parsed.
ValueError: If config.yaml exists but cannot be parsed.
Tolerance:
A missing agent directory or missing config.yaml is **not** an error —
the runtime simply falls back to default Lead Agent behavior for that
id. This keeps the chat session usable when the DB still has an agent
row but its files have been deleted (e.g. data dir moved between
machines, or filesystem wiped). The router layer is expected to
lazily restore the directory next time the agent is fetched via API.
"""
if agent_id is None:
@@ -74,10 +81,20 @@ def load_agent_config(agent_id: str | None) -> AgentConfig | None:
config_file = agent_dir / "config.yaml"
if not agent_dir.exists():
raise FileNotFoundError(f"Agent directory not found: {agent_dir}")
logger.warning(
"Agent directory missing for id '%s' (%s); falling back to default config",
agent_id,
agent_dir,
)
return None
if not config_file.exists() and not (agent_dir / SOUL_FILENAME).exists():
raise FileNotFoundError(f"Agent config not found: {config_file}")
logger.warning(
"Agent has no config.yaml or %s at %s; falling back to default config",
SOUL_FILENAME,
agent_dir,
)
return None
data: dict[str, Any] = {}
if config_file.exists():
@@ -12,21 +12,21 @@
injection: {...} # 系统提示词注入
security: {...} # 内容安全扫描
三层配置覆盖
两层配置覆盖
============
``get_effective_memory_config(user_id)`` 按优先级合并 (高 -> 低):
1. per-user 覆盖 ``{base_dir}/users/{user_id}/memory_config.json``
2. 全局覆盖 ``{base_dir}/memory_user_overrides.json``
3. config.yaml ``memory:`` 段 (即 ``get_memory_config()``)
4. Pydantic 默认值
1. per-user 覆盖 数据库 ``user_memory_configs`` 表 (经进程内 cache 读取)
(有 per-user 记录时自动强制 enabled=True)
2. config.yaml ``memory:`` 段 (即 ``get_memory_config()``)
3. Pydantic 默认值
第 1、2 层只允许覆盖 :data:`USER_WRITABLE_FIELDS` 白名单内的字段。
第 1 层只允许覆盖 :data:`USER_WRITABLE_FIELDS` 白名单内的字段。
cache 由 Gateway lifespan 启动时预热,写入时同步更新,保持同步读取路径。
"""
from __future__ import annotations
import copy
import json
import logging
from typing import Any
@@ -73,7 +73,7 @@ class HindsightMemoryConfig(BaseModel):
description="agent 私有工作 bank 命名模板",
)
memory_mode: str = Field(
default="context",
default="hybrid",
description="工具暴露策略:context(仅自动) / tools(仅工具) / hybrid(两者)",
)
bank_mission: str = Field(default="", description="reflect 推理的身份/框架描述")
@@ -129,29 +129,26 @@ class MemoryConfig(BaseModel):
# ===========================================================================
# per-user 运行时覆盖
# per-user 运行时覆盖 — 白名单
# ===========================================================================
# 用户可在运行时覆盖的字段白名单 (点号路径)。
# 不在此表中的字段必须改 config.yaml 并重启 (例如 provider / api_key / 字符配额)。
# 用户唯一可覆盖的字段:召回深度。
# injection.* / builtin.* / enabled 始终由 config.yaml 控制,用户不可关闭。
USER_WRITABLE_FIELDS: frozenset[str] = frozenset(
{
"injection.enabled",
"injection.max_tokens",
"injection.include_builtin",
"injection.include_hindsight",
"hindsight.memory_mode",
"hindsight.recall_budget",
"hindsight.bank_mission",
}
)
_VALID_RECALL_BUDGETS: frozenset[str] = frozenset({"low", "mid", "high"})
def _filter_to_whitelist(overrides: dict[str, Any]) -> dict[str, Any]:
"""把覆盖 dict 过滤为只含白名单字段的嵌套 dict。
输入既支持嵌套形式 ``{"injection": {"enabled": false}}``,也支持
点号扁平形式 ``{"injection.enabled": false}``。非白名单字段被丢弃并 log。
输入支持嵌套形式 ``{"hindsight": {"recall_budget": "high"}}`` 或
点号扁平形式 ``{"hindsight.recall_budget": "high"}``。
非白名单字段被丢弃并 log。
"""
result: dict[str, Any] = {}
@@ -182,21 +179,6 @@ def _deep_merge(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any
return merged
def _load_json_file(path: Any) -> dict[str, Any]:
"""读取一个 JSON 覆盖文件;不存在或解析失败时返回空 dict。"""
try:
from pathlib import Path
p = Path(path)
if not p.exists():
return {}
data = json.loads(p.read_text(encoding="utf-8"))
return data if isinstance(data, dict) else {}
except (OSError, json.JSONDecodeError) as exc:
logger.warning("读取记忆配置覆盖文件失败 %s: %s", path, exc)
return {}
# ===========================================================================
# 全局单例 + 加载入口
# ===========================================================================
@@ -221,82 +203,88 @@ def load_memory_config_from_dict(config_dict: dict) -> None:
_memory_config = MemoryConfig(**config_dict)
# ===========================================================================
# per-user recall_budget 进程内 cache
#
# Gateway lifespan 启动时调用 load_recall_budget_cache() 从 DB 批量加载。
# API 写入时同步更新 cache,使 get_effective_memory_config() 保持同步读取。
# ===========================================================================
_recall_budget_cache: dict[str, str] = {}
def load_recall_budget_cache(data: dict[str, str]) -> None:
"""用 DB 批量加载结果替换整个 cache (启动时调用一次)。"""
global _recall_budget_cache
_recall_budget_cache = dict(data)
logger.info("recall_budget cache loaded: %d user(s)", len(_recall_budget_cache))
def set_recall_budget_cache(user_id: str, value: str) -> None:
"""写入单个用户的 recall_budget cache。"""
_recall_budget_cache[user_id] = value
def delete_recall_budget_cache(user_id: str) -> None:
"""从 cache 中移除某用户的 recall_budget。"""
_recall_budget_cache.pop(user_id, None)
def get_recall_budget_from_cache(user_id: str) -> str | None:
"""返回 cache 中某用户的 recall_budget,未设置时返回 None。"""
return _recall_budget_cache.get(user_id)
def get_effective_memory_config(user_id: str) -> MemoryConfig:
"""按三层覆盖优先级,返回某用户的生效记忆配置。
"""返回某用户的生效记忆配置 (同步,从进程内 cache 读取 per-user 覆盖)。
优先级 (高 -> 低):per-user 覆盖 > 全局覆盖 > config.yaml > 默认值。
第 1、2 层只应用 :data:`USER_WRITABLE_FIELDS` 白名单内的字段。
覆盖文件读取失败不会抛异常 —— 退化为只用 config.yaml 级别配置。
优先级 (高 -> 低):per-user DB 覆盖 (经 cache) > config.yaml > 默认值。
有 per-user 记录时自动强制 enabled=True。
"""
base = _memory_config.model_dump()
recall_budget = _recall_budget_cache.get(user_id)
if recall_budget is not None:
base.setdefault("hindsight", {})["recall_budget"] = recall_budget
base["enabled"] = True
try:
from deerflow.config.paths import get_paths
paths = get_paths()
global_overrides = _filter_to_whitelist(
_load_json_file(paths.memory_global_overrides_file)
)
user_overrides = _filter_to_whitelist(
_load_json_file(paths.user_memory_config_file(user_id))
)
except Exception as exc: # noqa: BLE001 - 配置覆盖失败必须降级,不能阻断对话
logger.warning("加载 per-user 记忆配置覆盖失败,退回 config.yaml: %s", exc)
return _memory_config
merged = _deep_merge(_deep_merge(base, global_overrides), user_overrides)
try:
return MemoryConfig(**merged)
return MemoryConfig(**base)
except Exception as exc: # noqa: BLE001 - 覆盖产生非法配置时降级
logger.warning("合并后的记忆配置非法,退回 config.yaml: %s", exc)
return _memory_config
def save_user_memory_override(user_id: str, patch: dict[str, Any]) -> dict[str, Any]:
"""把白名单字段写入某用户的 per-user 覆盖文件,返回写入后的完整覆盖 dict。
# ===========================================================================
# Gateway 调用的异步 DB 对接函数
# ===========================================================================
async def save_user_memory_override_db(user_id: str, patch: dict[str, Any], store: Any) -> dict[str, Any]:
"""把白名单字段写入 DB store 并更新 cache,返回生效配置 dict。
``patch`` 支持嵌套或点号扁平形式;非白名单字段被忽略。
``store`` 为 ``UserMemoryConfigStore`` 实例 (避免循环 import,用 Any)。
"""
from deerflow.config.paths import get_paths
path = get_paths().user_memory_config_file(user_id)
current = _load_json_file(path)
filtered = _filter_to_whitelist(patch)
merged = _deep_merge(current, filtered)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(merged, ensure_ascii=False, indent=2), encoding="utf-8")
return merged
recall_budget = (filtered.get("hindsight") or {}).get("recall_budget")
if recall_budget is not None:
if recall_budget not in _VALID_RECALL_BUDGETS:
raise ValueError(f"recall_budget 必须为 {sorted(_VALID_RECALL_BUDGETS)} 之一,收到:{recall_budget!r}")
await store.set_recall_budget(user_id, recall_budget)
set_recall_budget_cache(user_id, recall_budget)
return get_effective_memory_config(user_id).model_dump()
def delete_user_memory_override(user_id: str, field: str | None = None) -> dict[str, Any]:
"""撤销某用户的 per-user 覆盖。
async def delete_user_memory_override_db(user_id: str, field: str | None, store: Any) -> dict[str, Any]:
"""撤销某用户的 per-user 覆盖并更新 cache,返回生效配置 dict。
``field`` 为点号路径 (如 ``injection.enabled``) 时只删该字段;
为 ``None`` 时清空整个 per-user 覆盖文件。返回剩余的覆盖 dict。
``field=None`` 清空全部;``field="hindsight.recall_budget"`` 只清该字段。
"""
from deerflow.config.paths import get_paths
path = get_paths().user_memory_config_file(user_id)
if field is None:
if path.exists():
path.unlink()
return {}
current = _load_json_file(path)
if "." in field:
section, sub_field = field.split(".", 1)
if isinstance(current.get(section), dict):
current[section].pop(sub_field, None)
if not current[section]:
current.pop(section, None)
if field is None or field == "hindsight.recall_budget":
await store.delete(user_id)
delete_recall_budget_cache(user_id)
else:
current.pop(field, None)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(current, ensure_ascii=False, indent=2), encoding="utf-8")
return current
logger.warning("忽略删除非白名单的记忆配置覆盖字段: %s", field)
return get_effective_memory_config(user_id).model_dump()
__all__ = [
@@ -310,6 +298,10 @@ __all__ = [
"set_memory_config",
"load_memory_config_from_dict",
"get_effective_memory_config",
"save_user_memory_override",
"delete_user_memory_override",
"load_recall_budget_cache",
"set_recall_budget_cache",
"delete_recall_budget_cache",
"get_recall_budget_from_cache",
"save_user_memory_override_db",
"delete_user_memory_override_db",
]