Qi

Cogito ergo sum

本系列第一篇:在写 LangGraph / CrewAI 之前,先把 Python 3.10+ 的语言特性打牢——它们是 Agent 工程化的地基。

如果你已经读过 LLM Agent 架构全景LangGraph 生产指南,下一步往往不是换框架,而是把 Python 本身 用到框架设计者的预期水平。Agent 代码本质是「高并发 I/O + 松散 JSON + 长生命周期状态」——Python 3.10+ 的类型系统、异步模型和 Pydantic 恰好覆盖这三块。

下文默认运行环境 Python ≥ 3.10(推荐 3.11+,可使用 TaskGroupExceptionGroup)。示例力求可直接粘贴运行;涉及外部服务处用 asyncio.sleep 模拟。


1. 为什么 Python 是 Agent 开发的事实标准?

维度 说明
生态密度 LangChain、LangGraph、CrewAI、LlamaIndex、AutoGen 均以 Python 为第一公民
迭代速度 Prompt / Tool / Graph 改动频繁,动态语言 + REPL 降低实验成本
模型侧同源 多数推理服务 SDK、微调脚本、评测管线默认 Python
互操作 通过 HTTP/gRPC 暴露服务后,Node/Go 可消费,但 编排层 仍多在 Python
1
2
3
4
5
用户请求 → Agent 编排 (Python) → LLM API

Tool: 搜索 / DB / 代码执行

结构化输出校验 (Pydantic)

LangChain 提供 LCEL 管道与海量集成,适合快速搭 RAG 和 ReAct;LangGraph 在其之上提供图状态机、Checkpoint、人工审批,是 2026 生产 Agent 的首选运行时;CrewAI 用「角色 + 目标」描述多 Agent 协作,降低团队分工建模成本。三者的官方示例、中间件、LangSmith Trace 插件几乎都以 Python 发布,社区 Issue 与 Stack Overflow 解答也集中在此语言。

2026 年的主流路径是:Python 做 Agent 大脑与编排,TypeScript/Go 做边缘 API 与前端。这不是说 Python 性能最强,而是 生态位 已经锁定:换语言意味着重写 Tool 适配层与评测脚本。本系列后续会讲 Node 侧实践;本篇专注 Python 地基。


2. 类型注解:Agent State 的「契约」

LangGraph 的 StateGraph、CrewAI 的 Task 输出、PydanticAI 的依赖注入,都假设你能用类型描述 图状态工具 I/O。没有类型时,十个节点各自往 state 里塞不同形状的 dict,一周后就没人敢改字段名。

Python 3.10+ 的三个高频构造:

构造 Agent 场景
TypedDict LangGraph 共享状态、可增量 merge 的字段
Annotated[..., reducer] 消息列表追加、计数器累加等 reducer
Generic[T] 可复用的 ToolResult[T]MemoryStore[T]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from dataclasses import dataclass
from typing import Annotated, Generic, TypedDict, TypeVar

T = TypeVar("T")

def append_messages(existing: list, new: list) -> list:
return existing + new

class AgentState(TypedDict):
messages: Annotated[list[dict], append_messages]
step_count: int
pending_tool: str | None # 3.10+ 联合类型写法

@dataclass
class ToolResult(Generic[T]):
ok: bool
data: T
error: str | None = None

TypedDict 适合 可部分更新 的图状态:节点只返回变更字段,框架负责 merge。Annotated[..., reducer] 告诉 LangGraph「这个字段不要覆盖,要交给 reducer 合并」——消息历史就是最典型的例子。Generic[T] 则用于封装工具返回值,让搜索工具返回 ToolResult[list[str]]、数据库工具返回 ToolResult[Row],调用方一眼能看懂。

配合 mypy 或 Pyright,能在 改 State 字段时 提前发现节点返回值与图定义不一致——比运行到一半才 KeyError 便宜得多。建议在 CI 中对 agent/ 目录开启 --strict 或等价配置,把类型债务拦在合并请求之前。


3. async/await:并发 Tool 与流式 LLM

Agent 一轮循环往往要:调 LLM(秒级)→ 并行查多个 API → 写库 → 再调 LLM。同步写法在 FastAPI / uvicorn 下会占满线程池,并发上来后延迟陡增;asyncio 让你在 单线程 里挂起等待,把 CPU 让给其它协程。

LangChain 的 ainvokeastream_events 与 OpenAI SDK 的 AsyncOpenAI 都是为这种模型设计的。务必整条链路统一 async:中间夹杂一次同步 requests.get,就会阻塞整个事件循环。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import asyncio
from collections.abc import AsyncIterator

async def call_search(query: str) -> str:
await asyncio.sleep(0.1) # 模拟 HTTP
return f"results for {query}"

async def stream_llm(prompt: str) -> AsyncIterator[str]:
for chunk in ["Hello", ", ", "world"]:
yield chunk
await asyncio.sleep(0.05)

async def agent_turn(user: str) -> str:
# 并行执行多个 Tool
weather, news = await asyncio.gather(
call_search(f"weather {user}"),
call_search(f"news {user}"),
)
parts: list[str] = []
async for token in stream_llm(f"{weather}\n{news}"):
parts.append(token)
return "".join(parts)

# asyncio.run(agent_turn("Shanghai"))

注意:asyncio.gather 适合 无依赖 的 Tool;有依赖时用顺序 awaitasyncio.TaskGroup(3.11+),任一子任务失败时可按组取消。流式响应用 async for 消费,便于边生成边推送给前端 SSE,同时把首 token 时间(TTFT)压进产品指标。

若必须调用同步 SDK(例如部分老版向量库),使用 await asyncio.to_thread(blocking_fn, *args) 把阻塞丢进线程池,避免「假 async」。


4. dataclass vs Pydantic:为什么 Agent I/O 选 Pydantic

LLM 返回的是 近似 JSON 的文本:Markdown 代码块包裹、尾逗号、注释、字段名大小写混乱都是日常。@dataclass 适合 你完全控制构造过程 的内部结构体;一旦数据来自模型或外部 HTTP,缺少运行时校验就等于把 bug 推迟到业务深处。

@dataclass pydantic.BaseModel
运行时校验 无(除非手写 __post_init__ 内置,可配置 extra="forbid"
JSON Schema 需额外生成 原生,便于 OpenAI response_format
嵌套 / 联合类型 手动 Fieldmodel_validator 一条龙
性能 更轻 v2 用 Rust 核心,生产可接受
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from pydantic import BaseModel, Field, field_validator

class ToolCall(BaseModel):
name: str
arguments: dict[str, object]

class AgentOutput(BaseModel):
thought: str
tool_calls: list[ToolCall] = Field(default_factory=list)
final_answer: str | None = None

@field_validator("tool_calls")
@classmethod
def cap_tools(cls, v: list[ToolCall]) -> list[ToolCall]:
if len(v) > 5:
raise ValueError("too many tool calls in one turn")
return v

# 模拟 LLM 脏输出
raw = {"thought": "查天气", "tool_calls": [{"name": "search", "arguments": {"q": "北京"}}]}
out = AgentOutput.model_validate(raw)

对比一段 仅 dataclass 的写法——能跑,但无法拒绝多余字段,也不会在 arguments 不是 dict 时立刻报错:

1
2
3
4
5
6
7
8
9
from dataclasses import dataclass

@dataclass
class ToolCallDc:
name: str
arguments: dict

# 脏数据静默通过
bad = ToolCallDc(name="search", arguments="not-a-dict") # 运行时不报错

实践建议: 图内部状态可用 TypedDict(偏 LangGraph 惯例);对外 API、Tool 参数、LLM 结构化输出 一律 Pydantic。校验失败时捕获 ValidationError,把 errors() 格式化成自然语言 Observation 喂回模型,往往比硬编码「输出格式错误」更能触发自我纠正。


5. 上下文管理器:连接与客户端的生命周期

Agent 进程常是 长驻服务:一个 uvicorn worker 会处理成千上万次对话。数据库连接池、httpx.AsyncClient、Chroma 临时索引、沙箱子进程都必须在 请求结束或图执行结束 时释放,否则文件描述符与连接泄漏会在凌晨把生产搞挂。

with 语句保证 正常返回与异常抛出 都会执行清理;@contextmanager / @asynccontextmanager 让你把「获取资源 → yield → 释放」封装成可复用的工厂函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from contextlib import asynccontextmanager
from collections.abc import AsyncGenerator

class FakeConn:
async def close(self) -> None:
pass

async def open_connection() -> FakeConn:
return FakeConn()

@asynccontextmanager
async def get_db() -> AsyncGenerator[FakeConn, None]:
conn = await open_connection()
try:
yield conn
finally:
await conn.close()

async def do_agent_work(db: FakeConn) -> str:
return "done"

async def run_with_resources() -> None:
async with get_db() as db:
result = await do_agent_work(db)
assert result == "done"

# asyncio.run(run_with_resources())

同步场景用 with open(...) as f 读 prompt 模板;异步资源用 async with。FastAPI 的 lifespan 在应用启动时创建全局 AsyncClient、在关闭时 aclose();LangGraph 的 Postgres checkpointer 同样应在 lifespan 里初始化一次、全程复用,而不是每个节点 new 一个连接。


6. 常见陷阱(Agent Python 代码)

上线 Agent 后,约一半稳定性问题出在 语言层误用,而非 Prompt。下面这张表来自常见 on-call 复盘:

陷阱 现象 对策
在 async 里调阻塞 SDK 事件循环卡死,QPS 归零 asyncio.to_thread() 或换 async 客户端
忽略 ValidationError 脏 JSON 直接 .get() 导致静默错误 Pydantic 校验 + 错误信息回灌 LLM
State 无类型 节点间字段名拼写错误 TypedDict + CI 跑 mypy
全局可变状态 多请求串话 State per thread_id / session_id
无限 gather 一次发起上百 Tool 打爆下游 信号量 Semaphore 限制并发
混用 sync/async LangChain 偶发挂起 统一 ainvoke / astream 链路
1
2
3
4
5
6
7
8
9
10
11
import asyncio

sem = asyncio.Semaphore(3)

async def fetch(url: str) -> str:
await asyncio.sleep(0.05)
return url

async def bounded_tool(url: str) -> str:
async with sem:
return await fetch(url)

另有两处易忽略:在热路径里 print 调试 会污染结构化日志,应使用 logging 或 OpenTelemetry;把巨大对象塞进 State(完整网页 HTML、未截断 PDF)会导致 Checkpoint 体积爆炸,应在节点内落盘或向量库,State 只留引用 ID。


7. 小结与系列导航

掌握 TypedDict/Annotated 描述状态async 并发 Tool 与流式输出Pydantic 守住 LLM 边界async context manager 管住资源,你就具备了阅读 LangGraph/CrewAI 源码和写生产 Agent 的语言基础。框架 API 每个季度都在变,但这四块在 2026 依然是最值得投入的学习时间。

建议动手练习:用本文的 AgentState + AgentOutput 写一个最小 ReAct 循环(不引框架),再对照 LangGraph 官方教程迁移——你会明显感到「原来框架替我做了哪些脏活」。

系列下一篇: Agent 开发基础:TypeScript / Node.js 侧实践 —— 当你的 Agent 需要暴露 REST、对接前端 SSE,或团队主力栈在 Node 时该如何与 Python 编排层分工。


相关阅读:LangGraph 深度指南:从图状态机到生产级 Agent · LLM Agent 架构全景

English Title: LangGraph Deep Dive — From Graph State Machines to Production-Grade Agents

如果你已经用 LangChain 写过 ReAct Agent,却在生产环境遇到 状态丢失、崩溃无法恢复、无法人工审批、循环失控 等问题,LangGraph 就是为此而生的。本文从架构原理到可运行代码,带你系统掌握 LangGraph。

If you’ve built ReAct agents with LangChain but hit state loss, crash recovery gaps, missing human approval, and runaway loops in production, LangGraph was built for exactly these problems. This article covers architecture and runnable code to help you master LangGraph systematically.


1. LangGraph 是什么?| What Is LangGraph?

中文: LangGraph 是 LangChain 团队开发的 有向图状态机运行时,将 Agent 工作流建模为:

  • State(状态) — 贯穿全流程的共享数据结构
  • Node(节点) — 处理步骤(LLM 调用、工具执行、自定义函数)
  • Edge(边) — 节点间的流转逻辑(含条件分支)

English: LangGraph is a directed graph state-machine runtime from the LangChain team. It models agent workflows with:

  • State — Shared data structure flowing through the pipeline
  • Node — Processing steps (LLM calls, tool execution, custom functions)
  • Edge — Transition logic between nodes (including conditional branches)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
         ┌──────────┐
│ START │
└────┬─────┘

┌──────────┐
│ Planner │ ← 分析任务、制定计划
└────┬─────┘

┌──────────┐ No
┌────│ Need Tool?├──────┐
│Yes └────┬─────┘ │
▼ │ ▼
┌────────┐ │ ┌──────────┐
│ Tool │ │ │ Response │
└───┬────┘ │ └──────────┘
▼ │
┌────────┐ │
│Evaluator├──┘ (retry / done / human review)
└────────┘

与 LangChain 的 create_agent 相比,LangGraph 是 底层运行时 而非高层封装——你获得完全的控制权,代价是更多样板代码。

Compared to LangChain’s create_agent, LangGraph is a low-level runtime, not a high-level wrapper — you get full control at the cost of more boilerplate.


2. 核心概念详解 | Core Concepts

2.1 State — 状态模式

中文: State 通常用 TypedDict 定义,每个节点读取并返回状态更新。LangGraph 自动合并(merge)各节点的返回值。

English: State is typically defined with TypedDict. Each node reads and returns state updates; LangGraph automatically merges node outputs.

1
2
3
4
5
6
7
from typing import Annotated, TypedDict
from langgraph.graph.message import add_messages

class AgentState(TypedDict):
messages: Annotated[list, add_messages] # 消息列表,自动追加
step_count: int # 循环计数器
needs_human: bool # 是否需要人工审批

add_messages 是 LangGraph 内置的 reducer:新消息追加到列表,而非覆盖。

add_messages is a built-in reducer: new messages are appended, not overwritten.

2.2 Node — 节点函数

中文: 节点是普通 Python 函数,接收当前 State,返回 State 更新字典。

English: A node is a plain Python function that receives the current State and returns a state update dict.

1
2
3
4
5
6
7
8
9
10
11
def call_llm(state: AgentState) -> dict:
response = llm.invoke(state["messages"])
return {
"messages": [response],
"step_count": state["step_count"] + 1,
}

def call_tool(state: AgentState) -> dict:
last_message = state["messages"][-1]
tool_result = execute_tool(last_message.tool_calls)
return {"messages": [tool_result]}

2.3 Edge — 条件路由

中文: 条件边根据 State 动态决定下一个节点,这是 LangGraph 超越简单 Chain 的关键能力。

English: Conditional edges dynamically choose the next node based on State — LangGraph’s key advantage over simple chains.

1
2
3
4
5
6
7
8
9
def should_continue(state: AgentState) -> str:
if state["step_count"] > 10:
return "end" # 超过最大步数,强制结束
if state["needs_human"]:
return "human_review" # 需要人工审批
last = state["messages"][-1]
if hasattr(last, "tool_calls") and last.tool_calls:
return "tools" # 有工具调用,执行工具
return "end" # 无工具调用,结束

3. 完整示例:带工具调用的 Agent | Full Example

中文: 以下是一个最小可运行的 LangGraph Agent,包含 LLM 推理、工具执行和循环控制。

English: Below is a minimal runnable LangGraph agent with LLM reasoning, tool execution, and loop control.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from langgraph.graph import StateGraph, END
from langgraph.prebuilt import ToolNode
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool

@tool
def search_web(query: str) -> str:
"""搜索网络获取信息。"""
return f"搜索结果: {query} 的相关信息..."

@tool
def calculate(expression: str) -> str:
"""计算数学表达式。"""
return str(eval(expression))

tools = [search_web, calculate]
llm = ChatOpenAI(model="gpt-4o").bind_tools(tools)

# 构建图
graph = StateGraph(AgentState)
graph.add_node("agent", call_llm)
graph.add_node("tools", ToolNode(tools))

graph.set_entry_point("agent")
graph.add_conditional_edges("agent", should_continue, {
"tools": "tools",
"end": END,
"human_review": "human_review",
})
graph.add_edge("tools", "agent")

app = graph.compile()
result = app.invoke({"messages": [("user", "北京今天天气如何?")], "step_count": 0})

4. 生产级特性 | Production Features

4.1 Checkpointing — 状态持久化

中文: Checkpointing 将每个状态转换持久化到数据库(SQLite、PostgreSQL 等),实现:

  • 崩溃恢复 — 从最后检查点继续执行
  • Time-travel Debugging — 回溯任意历史状态
  • 多用户会话 — 通过 thread_id 隔离不同用户

English: Checkpointing persists each state transition to a database (SQLite, PostgreSQL, etc.), enabling:

  • Crash recovery — Resume from the last checkpoint
  • Time-travel debugging — Replay any historical state
  • Multi-user sessions — Isolate users via thread_id
1
2
3
4
5
6
7
8
from langgraph.checkpoint.sqlite import SqliteSaver

memory = SqliteSaver.from_conn_string(":memory:")
app = graph.compile(checkpointer=memory)

# 使用 thread_id 隔离会话
config = {"configurable": {"thread_id": "user-123"}}
result = app.invoke(input_state, config)

4.2 Human-in-the-Loop — 人工介入

中文: 在关键节点设置 断点(Breakpoint),图执行到此处暂停,等待人工输入后恢复。

English: Set breakpoints at critical nodes; the graph pauses and resumes after human input.

1
2
3
4
5
6
7
8
9
10
11
from langgraph.types import interrupt

def human_review_node(state: AgentState) -> dict:
# 暂停执行,等待人工审批
approval = interrupt({
"question": "是否批准此操作?",
"action": state["messages"][-1].content,
})
if approval == "approved":
return {"needs_human": False}
return {"messages": [("system", "操作已被拒绝")]}
1
2
3
4
5
6
7
8
# 编译时设置断点
app = graph.compile(
checkpointer=memory,
interrupt_before=["human_review"],
)

# 恢复执行
app.invoke(None, config) # 传入 None 从断点继续

4.3 流式输出 | Streaming

中文: LangGraph 支持 Token 级流式输出,改善用户体验。

English: LangGraph supports token-level streaming for better UX.

1
2
3
for event in app.stream(input_state, config, stream_mode="messages"):
node_name, message = event
print(f"[{node_name}] {message.content}")

4.4 子图嵌套 | Sub-graph Composition

中文: 一个完整的图可以作为另一个图的节点,实现模块化复用。

English: A complete graph can become a node in a parent graph for modular reuse.

1
2
3
4
5
6
research_graph = build_research_subgraph()
writing_graph = build_writing_subgraph()

main_graph = StateGraph(MainState)
main_graph.add_node("research", research_graph.compile())
main_graph.add_node("writing", writing_graph.compile())

5. LangGraph vs LangChain vs CrewAI | Comparison

维度 Dimension LangChain LangGraph CrewAI
抽象层级 Level 高层 High 底层 Low 中高层 Mid-high
状态管理 State 无原生 No native 显式持久 Explicit 内置记忆 Built-in
循环/分支 Loops 有限 Limited 原生 Native 有限 Limited
Checkpoint
HITL 中间件 Middleware 原生 Native 可选 Optional
上手难度 Learning curve 低 Low 高 High 低 Low
生产就绪 Production 中 Medium 高 High 中 Medium
可观测性 Observability LangSmith LangSmith 第三方 3rd-party

选型建议 Selection advice:

  • 简单 RAG / 单轮工具调用 → LangChain create_agent
  • 复杂工作流 / 生产系统 → LangGraph
  • 快速多 Agent 原型 → CrewAI
  • 高可靠性 API → PydanticAI + LangGraph

6. 与 LangSmith 集成 | LangSmith Integration

中文: LangSmith 为 LangGraph 提供全链路可观测性:

1
2
3
4
import os
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_API_KEY"] = "your-key"
os.environ["LANGCHAIN_PROJECT"] = "my-agent"

在 LangSmith 控制台可查看:

  • 每个节点的输入/输出
  • LLM 调用的 Prompt 和 Response
  • 工具执行的参数和返回值
  • 端到端延迟和 Token 消耗

English: LangSmith provides full-chain observability for LangGraph. In the console you can inspect per-node I/O, LLM prompts/responses, tool args/results, and end-to-end latency and token usage.


7. 生产部署清单 | Production Checklist

中文:

检查项 说明
✅ 终止条件 step_count 上限、超时、Token 预算
✅ Checkpoint 生产环境用 PostgreSQL 而非 SQLite
✅ HITL 资金/删除/外发操作必经审批
✅ 工具权限 最小权限原则,避免 Agent 越权
✅ 结构化输出 关键节点强制 JSON Schema
✅ 错误处理 节点内 try/catch + 图级 fallback 边
✅ 可观测性 LangSmith Trace + 告警
✅ 评估集 Golden Dataset 回归测试

English:

Check Description
✅ Termination step_count cap, timeout, token budget
✅ Checkpoint PostgreSQL in production, not SQLite
✅ HITL Human approval for financial/delete/outbound ops
✅ Tool permissions Least privilege; prevent escalation
✅ Structured output Enforce JSON Schema at critical nodes
✅ Error handling try/catch in nodes + graph-level fallback edges
✅ Observability LangSmith traces + alerts
✅ Evaluation Golden Dataset regression tests

8. 常见陷阱 | Common Pitfalls

中文:

  1. 状态膨胀messages 列表无限增长,需定期摘要压缩
  2. 循环死锁 — 忘记设置 step_count 上限,Agent 反复调用同一工具
  3. Checkpoint 膨胀 — 高频写入导致存储暴涨,需设置保留策略
  4. 过度设计 — 简单顺序流程不需要 LangGraph,用 LangChain Chain 即可
  5. 忽略评估 — 没有 Golden Dataset,Prompt 微调后无法验证回归

English:

  1. State bloat — Unbounded messages; summarize periodically
  2. Loop deadlock — Missing step_count cap; agent retries the same tool forever
  3. Checkpoint bloat — High-frequency writes; set retention policies
  4. Over-engineering — Simple sequential flows don’t need LangGraph
  5. Skipping evaluation — No Golden Dataset means no regression verification

9. 总结 | Conclusion

中文: LangGraph 的核心价值在于 将 Agent 工作流从黑盒循环变成可审计、可恢复、可介入的状态机。学习曲线虽陡,但对于需要生产级可靠性的系统,这是目前最成熟的开源选择。推荐路径:

  1. 用 LangChain create_agent 验证业务价值
  2. 遇到状态/循环/审批需求时迁移到 LangGraph
  3. 配合 LangSmith 建设可观测性与评估体系
  4. 复杂 Agent 逻辑用 PydanticAI 保证类型安全

English: LangGraph’s core value is turning agent workflows from opaque loops into auditable, recoverable, interruptible state machines. The learning curve is steep, but for production reliability it remains the most mature open-source choice. Recommended path:

  1. Validate business value with LangChain create_agent
  2. Migrate to LangGraph when you need state, loops, or approvals
  3. Build observability and evaluation with LangSmith
  4. Use PydanticAI for type-safe complex agent logic

相关阅读 Related reading:LLM Agent 架构全景:LangChain 生态设计与实践

English Title: A Comprehensive Guide to LLM Agent Architecture, Applications, and Trade-offs

大语言模型(LLM)正从「对话式问答」走向「自主行动」。核心范式是 Agent(智能体):模型在循环中完成 感知 → 推理 → 调用工具 → 观察结果 → 再推理,直到任务完成。LangChain 是这一浪潮中最具代表性的开源框架,其生态已扩展为 LangGraph、LangSmith 等完整工具链。

Large Language Models are evolving from conversational Q&A to autonomous action through the Agent paradigm: instead of merely generating text, the model operates in a loop of perceive → reason → invoke tools → observe results → reason again until the task is complete. LangChain is one of the most representative open-source frameworks, with an ecosystem spanning LangGraph, LangSmith, and more.


1. 什么是 LLM Agent?| What Is an LLM Agent?

中文: 典型 Agent 由以下组件构成:

组件 作用
LLM(大脑) 推理、规划、决策
Tools(工具) 搜索、数据库、API、代码执行等
Memory(记忆) 短期上下文 + 长期向量记忆
Planning(规划) 任务分解与子目标排序
Orchestration(编排) 多步流程控制、重试、人工介入

English: A typical Agent consists of:

Component Role
LLM (Brain) Reasoning, planning, decision-making
Tools Search, databases, APIs, code execution, etc.
Memory Short-term context + long-term vector memory
Planning Task decomposition and sub-goal ordering
Orchestration Multi-step flow control, retries, human-in-the-loop

与简单 Prompt Chain 不同,Agent 具备 自主循环(Agentic Loop)环境反馈(Feedback),能在不确定环境中动态调整策略。

Unlike simple prompt chains, an Agent features an Agentic Loop and environmental feedback, enabling dynamic strategy adjustment in uncertain environments.


2. 核心架构模式 | Core Architecture Patterns

2.1 ReAct 模式 | ReAct Pattern

中文: ReAct(Reasoning + Acting) 是最经典的单 Agent 架构:模型交替输出「思考」和「行动」,根据工具返回的 Observation 继续推理。

English: ReAct (Reasoning + Acting) is the classic single-agent architecture: the model alternates between “Thought” and “Action,” continuing to reason based on tool-returned Observations.

1
2
用户输入 → LLM 思考 → 选择工具 → 执行 → 观察结果 → 再思考 → … → 最终答案
User Input → LLM Think → Select Tool → Execute → Observe → Think Again → … → Final Answer
中文 English
优点 实现简单、可解释性强 Simple to implement, highly interpretable
缺点 循环难控、Token 成本高 Hard to control loops, high token cost

2.2 图状态机模式(LangGraph)| Graph State Machine

中文: LangGraph 将工作流建模为 有向图:节点是处理步骤,边定义流转逻辑,共享 State 贯穿全流程。支持 Checkpointing、Human-in-the-Loop、循环与分支。

English: LangGraph models workflows as a Directed Graph: nodes are processing steps, edges define transitions, and a shared State flows through the pipeline. It supports checkpointing, human-in-the-loop, loops, and branches.

2.3 多 Agent 协作 | Multi-Agent Collaboration

模式 Pattern 框架 Framework 特点 Characteristics
角色分工 Role-based CrewAI 定义角色、目标、背景故事,模拟团队协作
对话协商 Conversational AutoGen/AG2 消息传递协商,适合开放式研究
层级编排 Hierarchical LangGraph 主 Agent 调度子 Agent
类型安全 Type-safe PydanticAI 强类型 I/O,适合高可靠性 API

3. LangChain 生态 | LangChain Ecosystem

3.1 LangChain 核心

中文:

  • LCEL:用管道符 | 组合 Chain
  • 1000+ 集成:模型、向量库、文档加载器、工具
  • v1.0(2025 GA)create_agent 原语、中间件层(PII 检测、摘要、HITL)
  • RAG 全家桶:文档切分、Embedding、Retriever、Reranker

English:

  • LCEL: Compose chains with the pipe operator |
  • 1000+ integrations: Models, vector stores, document loaders, tools
  • v1.0 (2025 GA): create_agent primitive, middleware (PII detection, summarization, HITL)
  • Full RAG stack: Document splitting, embedding, retriever, reranker

适用 Best for: 快速原型、标准 RAG、简单 ReAct Agent
局限 Limitations: 无原生状态持久化(需升级 LangGraph)

3.2 LangGraph

中文: LangGraph 是 LangChain 团队的 底层运行时,已成为 2026 年生产级 Agent 的 事实标准。支持确定性执行、LangSmith 全链路 Trace、子图嵌套、模型无关。

English: LangGraph is the low-level runtime from the LangChain team and the de facto standard for production agents in 2026. It offers deterministic execution, LangSmith tracing, sub-graph nesting, and model-agnostic design.

3.3 LangSmith

中文: 配套 可观测性与评估平台:记录 LLM 调用、工具执行、延迟与 Token;支持回归测试与生产监控。

English: Companion observability and evaluation platform: logs LLM calls, tool execution, latency, and tokens; supports regression testing and production monitoring.


4. 其他主流框架 | Other Major Frameworks

CrewAI

中文: 以「团队」隐喻组织多 Agent,上手最快,适合内容流水线与快速 Demo。生产可观测性较弱。

English: Organizes agents via a “team” metaphor; fastest time-to-ship; best for content pipelines and rapid demos. Weaker production observability.

AutoGen / AG2

中文: 微软出品,以多 Agent 对话为核心。适合研究型开放式任务,但 Token 开销高,需严格终止条件。

English: From Microsoft Research; multi-agent conversation at its core. Suited for research-style open tasks, but high token overhead; strict termination caps required.

PydanticAI

中文: 强调类型安全与 Python 原生体验,适合高并发 API 与强合规场景。常与 LangGraph 组合使用。

English: Emphasizes type safety and native Python DX; suited for high-throughput APIs and compliance scenarios. Often combined with LangGraph.

LlamaIndex

中文: 专注数据连接与 RAG,擅长知识库问答、文档分析 Agent。

English: Focused on data connectivity and RAG; strong at knowledge-base Q&A and document analysis agents.


5. 典型应用场景 | Application Scenarios

场景 Scenario 推荐架构 Architecture 说明 Notes
智能客服 Support LangChain + RAG + ReAct 知识库检索 + 工单工具
代码助手 Code Claude Agent SDK / LangGraph 多文件读写、测试执行
研究报告 Research CrewAI / AutoGen 检索、分析、撰写、审核
企业流程 Enterprise LangGraph + HITL 审批流、合规、可审计
数据分析 Data LlamaIndex + PydanticAI 数据库连接、结构化输出
DevOps 巡检 LangGraph 定时触发、分支、重试告警

6. 优缺点综合分析 | Pros and Cons

Agent 范式整体 | Overall

优点 Pros:

  • 自主性:减少人工逐步引导 / Autonomy reduces manual guidance
  • 可扩展性:通过工具接入外部系统 / Extensibility via tools
  • 灵活性:同一架构适配多领域 / Flexibility across domains
  • 可组合性:Chain、Graph、Multi-Agent 可嵌套 / Composable architectures

缺点 Cons:

  • 成本高:多轮调用 + 工具执行 / High cost from multi-turn calls
  • 不可靠:幻觉、工具错误、无限循环 / Hallucinations, tool errors, infinite loops
  • 延迟大:复杂 Agent 可达数十秒 / Latency can reach tens of seconds
  • 安全风险:Prompt 注入、工具越权 / Prompt injection, privilege escalation
  • 可观测性难:推理链黑盒 / Opaque reasoning chains

框架选型速查 | Quick Selection Guide

1
2
3
4
5
6
7
8
9
10
11
12
13
快速验证想法?        → CrewAI
生产级状态机? → LangGraph
强类型 API 服务? → PydanticAI
RAG 知识库 Agent? → LlamaIndex / LangChain
开放式多 Agent 研究? → AutoGen / AG2
深度绑定某家模型? → 对应厂商 SDK

Rapid validation? → CrewAI
Production state machine? → LangGraph
Strongly typed API? → PydanticAI
RAG knowledge agent? → LlamaIndex / LangChain
Open-ended multi-agent? → AutoGen / AG2
Committed to one vendor? → Vendor SDK

7. 生产级最佳实践 | Production Best Practices

  1. 分层设计 — Agent 逻辑与编排分离(PydanticAI + LangGraph)/ Layer agent logic and orchestration
  2. 工具最小权限 — 每个工具仅暴露必要 API / Least-privilege tools
  3. 终止条件 — 最大循环次数、超时、Token 预算 / Max loops, timeout, token budget
  4. 结构化输出 — 关键步骤强制 JSON Schema / Enforce JSON Schema on critical steps
  5. 可观测性先行 — 上线前接入 LangSmith / Observability before launch
  6. HITL 关键节点 — 资金、删除、对外发送必经审批 / Human approval at critical nodes
  7. 评估驱动迭代 — Golden Dataset 回归测试 / Evaluation-driven iteration
  8. 缓存与摘要 — 压缩长对话、缓存重复查询 / Caching and summarization

  • 协议标准化 — MCP、A2A 推动工具与 Agent 互操作 / MCP, A2A for interoperability
  • 框架收敛 — LangChain v1.0 统一 API,LangGraph 成默认运行时 / Framework convergence
  • 评估与治理 — Guardrails、Policy-as-Code 成标配 / Governance as standard
  • 成本优化 — 小模型路由 + 大模型复杂推理 / Model routing for cost
  • 多模态 Agent — 视觉、语音、代码执行融合 / Multimodal agents

9. 总结 | Conclusion

中文: LLM Agent 是 「模型能力 + 工具生态 + 编排运行时 + 可观测性」 的系统工程。务实路径:先用 Chain/ReAct 验证价值,再按需升级到 LangGraph,并从一开始就建设评估与观测体系。

English: LLM Agents are systems engineering combining model capability + tool ecosystem + orchestration runtime + observability. The pragmatic path: start with Chain/ReAct to validate value, upgrade to LangGraph as needed, and build evaluation and observability from day one.


延伸阅读 Further reading:LangGraph 生产级 Agent 开发指南

Agent Hermes 与 OpenClaw(龙虾)安全模型深度解析

Security Models in Agent Hermes & OpenClaw (Lobster): A Deep Dive

最后更新 | Last updated: 2026-06-05


一、共同前提:个人助理信任模型 | Shared Premise: Personal Assistant Trust Model

中文

两个框架都面向 单用户/单信任边界 的个人助理场景,而非 hostile multi-tenant(敌对多租户)隔离:

假设 含义
单操作者 一个 Gateway 对应一个信任的操作者
主机可信 能修改 ~/.openclaw~/.hermes 的人视为可信管理员
非多租户边界 多个互不信任用户共享同一 Gateway 不是推荐部署模式
工具即权限 能触发 Agent 的人 ≈ 能诱导 Agent 使用其工具权限

若需敌对用户隔离,应 拆分信任边界:独立 Gateway + 独立凭证 + 理想情况下独立 OS 用户/主机。

English

Both frameworks target single-user / single-trust-boundary personal assistant deployments, not hostile multi-tenant isolation:

Assumption Meaning
Single operator One Gateway per trusted operator
Host is trusted Anyone who can modify ~/.openclaw or ~/.hermes is a trusted admin
Not multi-tenant Multiple mutually untrusted users on one Gateway is not a recommended setup
Tools = authority Anyone who can trigger the agent can induce tool usage within the agent’s policy

For adversarial-user isolation, split trust boundaries: separate Gateways, credentials, and ideally OS users/hosts.


二、安全设计哲学对比 | Security Design Philosophy Comparison

中文

维度 OpenClaw Hermes Agent
核心理念 Access control before intelligence — 先控身份,再控范围,最后才信任模型 Defense in depth — 七层纵深防御
默认姿态 信任单操作者,security="full" 为个人助理默认 默认 manual 审批危险命令
审计工具 openclaw security audit [--deep] [--fix] hermes doctor + 供应链告警
沙箱策略 Docker sandbox(可选)+ fs-safe 文件操作 6 种终端后端,容器即边界
审批模型 Exec approvals(allowlist + ask) 危险命令模式匹配 + Tirith 扫描
供应链 npm shrinkwrap 锁定发布依赖 tirith + Skills Guard + 懒安装隔离

English

Dimension OpenClaw Hermes Agent
Core idea Access control before intelligence — identity, scope, then model Defense in depth — seven layers
Default posture Trusted single-operator; security="full" for personal use Default manual approval for dangerous commands
Audit tooling openclaw security audit [--deep] [--fix] hermes doctor + supply-chain advisories
Sandboxing Optional Docker sandbox + @openclaw/fs-safe 6 terminal backends; container as boundary
Approval model Exec approvals (allowlist + ask) Dangerous-command patterns + Tirith scanning
Supply chain npm shrinkwrap for published deps Tirith + Skills Guard + lazy install isolation

三、OpenClaw 安全模型 | OpenClaw Security Model

中文

3.1 威胁模型

Agent 可以:执行任意 Shell、读写文件、访问网络、代发消息。

消息者可以:Prompt 注入、社会工程、探测基础设施。

OpenClaw 的应对:先决定谁能说话,再决定 Agent 能在哪行动,最后假设模型可被操纵并限制爆炸半径。

3.2 信任边界矩阵

控制项 实际作用 常见误读
gateway.auth 认证 Gateway API 调用者 「每帧都需签名才安全」
sessionKey 会话路由键 「sessionKey 是用户认证」
Prompt 防护 降低模型滥用风险 「注入 alone 即证明认证绕过」
Node pairing 操作者级远程执行 「应默认视为不可信用户访问」
Exec approvals 操作者意图护栏 「非敌对多租户隔离」

3.3 DM 访问模型

所有支持 DM 的渠道均有 dmPolicy

策略 行为
pairing(默认) 未知发送者收到配对码,需管理员批准
allowlist 仅白名单内 ID 可对话
open 任何人可触发(高风险)
disabled 禁用 DM

群组策略:requireMention: true 防止群内误触发。

3.4 上下文可见性(contextVisibility)

控制注入模型的补充上下文(引用回复、线程历史),与触发授权分离:

行为
all(默认) 保留所有补充上下文
allowlist 仅白名单发送者的上下文
allowlist_quote 白名单过滤,但保留一条显式引用

3.5 工具爆炸半径控制

硬化基线配置(60 秒快速加固):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
gateway: {
mode: "local",
bind: "loopback",
auth: { mode: "token", token: "replace-with-long-random-token" },
},
session: { dmScope: "per-channel-peer" },
tools: {
profile: "messaging",
deny: ["group:automation", "group:runtime", "group:fs",
"sessions_spawn", "sessions_send"],
fs: { workspaceOnly: true },
exec: { security: "deny", ask: "always" },
elevated: { enabled: false },
},
channels: {
whatsapp: {
dmPolicy: "pairing",
groups: { "*": { requireMention: true } },
},
},
}

高风险控制面工具(对不可信内容默认 deny):

  • gateway — 可修改持久配置
  • cron — 可创建持久定时任务
  • sessions_spawn / sessions_send — 跨会话操作

3.6 Exec 审批模型

配置 含义
tools.exec.security deny / allowlist / full
tools.exec.ask always / on-miss / off
tools.exec.host sandbox / gateway / node / auto

默认对个人助理:security="full", ask="off" — 这是有意为之的 UX 默认,非漏洞。

审批绑定精确请求上下文;无法识别单一本地文件操作数的解释器命令会被拒绝。

3.7 安全文件操作(@openclaw/fs-safe)

  • 根目录边界文件访问
  • 原子写入
  • 安全归档解压
  • 密钥文件辅助函数

3.8 网络安全

风险 缓解
Gateway 公网暴露 bind: "loopback" + Tailscale
反向代理认证绕过 配置 gateway.trustedProxies,拒绝未信任代理的 localhost 伪装
Control UI HTTP 需 HTTPS 或 localhost;allowInsecureAuth 仅本地兼容
DNS 重绑定 收紧 trustedProxies,避免直接公网暴露

3.9 插件与 Skills 供应链

  • 插件在 Gateway 进程内运行 — 视为可信代码
  • 推荐 plugins.allow 显式白名单
  • Skills 目录视为可信代码,限制修改权限
  • openclaw security audit --deep 扫描 Skills/插件
  • 发布包使用 npm-shrinkwrap.json 锁定依赖图

3.10 安全审计

1
2
3
openclaw security audit          # 常规审计
openclaw security audit --deep # 含实时 Gateway 探测
openclaw security audit --fix # 自动修复常见问题

审计覆盖:入站访问、工具爆炸半径、网络暴露、浏览器控制、文件权限、插件、策略漂移。

English

3.1 Threat Model

The agent can execute shell, read/write files, access network, send messages. Messengers can prompt-inject and social-engineer. Response: control who can talk, where the agent acts, assume the model is manipulable, limit blast radius.

3.2 Trust Boundary Matrix

gateway.auth authenticates API callers; sessionKey routes sessions (not auth); exec approvals are operator guardrails, not multi-tenant isolation.

3.3 DM Access Model

dmPolicy: pairing (default), allowlist, open (high risk), disabled. Group mention gates prevent accidental triggers.

3.4 Context Visibility

Separates trigger authorization from supplemental context injection (all, allowlist, allowlist_quote).

3.5 Tool Blast Radius

Hardened baseline denies automation/runtime/fs tools, enables workspace-only filesystem, denies exec by default. Deny gateway, cron, sessions_spawn for untrusted surfaces.

3.6 Exec Approvals

security + ask + host configuration. Default full/off is intentional for trusted personal assistants.

3.7 Secure File Operations

@openclaw/fs-safe: root-bounded access, atomic writes, safe archive extraction.

3.8 Network Security

Loopback bind, trusted proxy config, HTTPS for Control UI, no direct public exposure.

3.9 Plugin & Skills Supply Chain

In-process plugins = trusted code. Explicit allowlists, shrinkwrapped npm deps, deep audit scanning.

3.10 Security Audit

openclaw security audit [--deep] [--fix] covers inbound access, tool blast radius, network exposure, permissions, plugins, policy drift.


四、Hermes Agent 安全模型 | Hermes Agent Security Model

中文

4.1 七层纵深防御

flowchart TB
    L1[1. 用户授权<br/>Allowlist + DM Pairing]
    L2[2. 危险命令审批<br/>Pattern + Tirith]
    L3[3. 容器隔离<br/>Docker/Modal/Daytona]
    L4[4. MCP 凭证过滤<br/>环境变量隔离]
    L5[5. 上下文文件扫描<br/>Prompt 注入检测]
    L6[6. 跨会话隔离<br/>Cron 路径加固]
    L7[7. 输入净化<br/>工作目录 Allowlist]
    L1 --> L2 --> L3 --> L4 --> L5 --> L6 --> L7

4.2 危险命令审批

审批模式~/.hermes/config.yaml):

模式 行为
manual(默认) 所有危险命令需用户明确批准
smart 辅助 LLM 评估风险;低风险自动批准,高风险自动拒绝,不确定则人工
off 禁用所有审批(等同 --yolo

YOLO 模式/yolohermes --yolo):

  • 绕过审批提示,但不绕过硬线黑名单
  • 会话中显示红色 ⚠ YOLO 状态栏提醒

硬线黑名单(Always-On Floor) — 无论 YOLO/off/approve 均拒绝:

模式 原因
rm -rf / 及变体 擦除文件系统根
Bash fork bomb 耗尽进程直到重启
mkfs.* on root device 格式化 live 系统
dd if=/dev/zero of=/dev/sd* 清零物理磁盘
管道不可信 URL 到 sh 远程代码执行

触发审批的模式(部分):

  • rm -r / rm --recursive
  • chmod 777 / chmod -R 不安全权限
  • DROP TABLE / DELETE FROM 无 WHERE / TRUNCATE
  • systemctl stop/restart/disable
  • bash -c / curl | sh / bash <(curl ...)
  • 覆写 /etc/~/.ssh/~/.hermes/.env
  • pkill/killall hermes/gateway(防自终止)

容器绕过:Docker/Singularity/Modal/Daytona 后端跳过危险命令检查——容器本身是安全边界。

4.3 Tirith 预执行扫描

集成 tirith 进行内容级命令扫描,检测:

  • 同形字 URL 欺骗
  • 管道到解释器(curl | bash
  • 终端注入攻击
1
2
3
4
security:
tirith_enabled: true
tirith_timeout: 5
tirith_fail_open: true # tirith 不可用时是否放行(高安全环境设为 false)

可疑/阻断命令触发审批流程,默认选择 deny。

4.4 用户授权(Gateway)

授权检查顺序:

  1. 平台 allow-all 标志
  2. DM 配对已批准列表
  3. 平台 allowlist
  4. 全局 allowlist
  5. 全局 allow-all
  6. 默认拒绝

DM 配对安全特性(OWASP + NIST SP 800-63-4):

特性 详情
码格式 8 字符,32 字符无歧义字母表
随机性 secrets.choice() 密码学安全
TTL 1 小时过期
速率限制 每用户每 10 分钟 1 次
锁定 5 次失败 → 锁定 1 小时
文件权限 chmod 0600

4.5 容器隔离(Docker 示例)

每个容器强制安全参数:

1
2
3
4
5
"--cap-drop", "ALL"
"--security-opt", "no-new-privileges"
"--pids-limit", "256"
"--tmpfs", "/tmp:rw,nosuid,size=512m"
"--tmpfs", "/var/tmp:rw,noexec,nosuid,size=256m"

可配置 CPU/内存/磁盘限制。持久模式 bind-mount /workspace/root;临时模式使用 tmpfs。

4.6 终端后端安全对比

后端 隔离 危险命令检查 适用场景
local 无(宿主机) 开发、可信用户
ssh 远程机器 Gateway 与执行分离
docker 容器 ❌(容器即边界) 生产 Gateway
singularity 容器 HPC
modal / daytona 云沙箱 Serverless 隔离

4.7 环境变量与凭证过滤

execute_code / terminal 默认剥离敏感环境变量(含 KEY/TOKEN/SECRET/PASSWORD 等)。

Skill 声明式透传:Skill frontmatter 中 required_environment_variables 仅在 Skill 加载后透传对应变量。

MCP 子进程:仅传递 PATH/HOME/USER/LANG 等安全变量 + MCP 配置中显式声明的 env

凭证脱敏:MCP 错误消息中 GitHub PAT、Bearer token 等替换为 [REDACTED]

4.8 SSRF 与网站访问策略

SSRF 防护(始终开启,面向公网):

阻断 RFC 1918 私网、回环地址、链路本地(含 169.254.169.254 云元数据)、CGNAT、云元数据主机名。重定向链每跳重新验证。

1
2
3
4
5
security:
allow_private_urls: false # 仅内网场景设为 true
website_blocklist:
enabled: true
domains: ["*.internal.company.com"]

4.9 上下文文件注入防护

注入系统提示词前扫描 AGENTS.md、SOUL.md、.cursorrules 等:

  • 忽略/覆盖先前指令的注入
  • 隐藏 HTML 注释中的可疑关键词
  • 读取密钥文件的尝试
  • 不可见 Unicode 字符

被阻断时显示:[BLOCKED: AGENTS.md contained potential prompt injection]

4.10 记忆安全扫描

MEMORY.md / USER.md 写入前检测 Prompt 注入、凭证外泄、SSH 后门、不可见 Unicode。

4.11 Skills 供应链安全

  • Skills Hub 安装经过安全扫描(数据外泄、注入、破坏性命令)
  • --force 可覆盖 caution/warn 级发现,不可覆盖 dangerous 判定
  • 信任等级:builtin > official > trusted > community
  • 懒安装(lazy_deps.py)隔离可选依赖,防止一个毒化包拖垮全部功能

4.12 供应链告警

hermes doctor 检查 Python venv 中已知妥协版本(如供应链蠕虫),可用 hermes doctor --ack <id> 确认处置。

English

4.1 Seven Defense Layers

User auth → dangerous command approval → container isolation → MCP credential filtering → context file scanning → cross-session isolation → input sanitization.

4.2 Dangerous Command Approval

Modes: manual (default), smart (auxiliary LLM risk assessment), off (YOLO). Hardline blocklist always blocks catastrophic commands regardless of YOLO. Container backends skip approval checks — the container is the boundary.

4.3 Tirith Pre-Exec Scanning

Content-level scanning for homograph spoofing, pipe-to-interpreter, terminal injection. Integrates with approval flow; default deny on suspicious verdicts.

4.4 User Authorization

Layered allowlists + DM pairing (cryptographic codes, TTL, rate limits, lockout). Default deny.

4.5 Container Isolation

Docker: cap-drop ALL, no-new-privileges, pids-limit, size-limited tmpfs. Configurable CPU/memory/disk.

4.6 Terminal Backend Security

local/ssh: approval checks on. docker/singularity/modal/daytona: container is boundary, checks skipped.

4.7 Credential Filtering

Strip sensitive env vars by default. Skill-declared passthrough only when skill is loaded. MCP gets filtered env + explicit config only. Error message redaction.

4.8 SSRF & Website Policy

Block private/loopback/link-local/metadata addresses. Redirect re-validation. Optional allow_private_urls for LAN-only setups. Domain blocklist support.

4.9 Context File Injection Protection

Scan workspace files for injection patterns, hidden comments, secret exfiltration, invisible Unicode.

4.10 Memory Security Scanning

Scan memory entries before system-prompt injection.

4.11 Skills Supply Chain

Hub install security scan, trust levels, --force cannot override dangerous verdicts, lazy dep isolation.

4.12 Supply-Chain Advisories

hermes doctor flags known compromised package versions.


五、安全模型对比矩阵 | Security Model Comparison Matrix

中文

安全能力 OpenClaw Hermes
身份优先 ✅ dmPolicy + allowlist ✅ 多层 allowlist + pairing
命令审批 Exec approvals (allowlist + ask) Pattern matching + Tirith + smart mode
不可覆盖黑名单 无明确硬线层 ✅ UNRECOVERABLE_BLOCKLIST
容器沙箱 Docker sandbox(可选) 6 后端,容器即边界
文件安全 @openclaw/fs-safe 根边界 工作目录 allowlist + 上下文扫描
SSRF 防护 浏览器 SSRF 策略可配 内置多类地址阻断
Prompt 注入防护 contextVisibility 过滤 上下文文件 + 记忆写入扫描
MCP 凭证隔离 配置级 env 严格白名单 + 脱敏
安全审计 CLI openclaw security audit hermes doctor
供应链锁定 npm shrinkwrap tirith + lazy_deps + Skills Guard
默认安全姿态 信任操作者(full exec) 人工审批(manual)
硬化基线 audit –fix 一键加固 生产清单(Docker + allowlist)

English

Security capability OpenClaw Hermes
Identity-first ✅ dmPolicy + allowlist ✅ layered allowlist + pairing
Command approval Exec approvals Pattern + Tirith + smart mode
Non-overridable blocklist No explicit hardline layer ✅ UNRECOVERABLE_BLOCKLIST
Container sandbox Optional Docker 6 backends; container as boundary
File safety @openclaw/fs-safe root bounds cwd allowlist + context scanning
SSRF protection Configurable browser SSRF policy Built-in multi-class address blocking
Prompt injection contextVisibility filtering Context file + memory write scanning
MCP credential isolation Config-level env Strict whitelist + redaction
Security audit CLI openclaw security audit hermes doctor
Supply chain npm shrinkwrap tirith + lazy_deps + Skills Guard
Default posture Trust operator (full exec) Manual approval
Hardening baseline audit –fix Production checklist (Docker + allowlist)

六、共享收件箱场景 | Shared Inbox Scenarios

中文

若多人可 DM 你的 Bot,核心风险是 委派工具权限

  • 任一允许发送者可诱导 exec、浏览器、网络/文件工具
  • 一个发送者的 Prompt 注入可影响共享状态/设备/输出
  • 若 Agent 持有敏感凭证,任何允许发送者都可能驱动外泄

OpenClaw 建议

  • session.dmScope: "per-channel-peer"
  • dmPolicy: "pairing" 或严格 allowlist
  • 不要对共享 DM 开放广泛工具访问
  • 团队工作流用独立 Agent/Gateway,最小工具集

Hermes 建议

  • 配置平台 allowlist,禁用 GATEWAY_ALLOW_ALL_USERS
  • 生产环境 terminal.backend: docker
  • Cron 任务设 cron_mode: deny(遇危险命令拒绝而非自动批准)

English

If multiple people can DM your bot, the core risk is delegated tool authority. Any allowed sender can induce exec/browser/network tools; prompt injection from one sender affects shared state.

OpenClaw: per-channel-peer DM scope, pairing/allowlist, no broad tools on shared DMs, separate agents for team workflows.

Hermes: platform allowlists, Docker backend in production, cron_mode: deny for headless jobs.


七、生产硬化清单 | Production Hardening Checklists

中文

OpenClaw 生产清单

  1. openclaw security audit --deep --fix
  2. gateway.bind: "loopback" + 强随机 gateway.auth.token
  3. dmPolicy: "pairing" + session.dmScope: "per-channel-peer"
  4. 收紧 tools.profile,deny gateway/cron/sessions_spawn
  5. tools.exec.security: "deny""allowlist" + ask: "always"
  6. tools.fs.workspaceOnly: true
  7. chmod 700 ~/.openclaw,凭证文件 600
  8. plugins.allow 显式白名单
  9. 反向代理配置 trustedProxies
  10. 定期审查 Skills 目录修改权限

Hermes 生产清单

  1. 配置 TELEGRAM_ALLOWED_USERS 等,禁用 GATEWAY_ALLOW_ALL_USERS
  2. terminal.backend: docker(或 modal/daytona)
  3. 设置容器 CPU/内存/磁盘限制
  4. chmod 600 ~/.hermes/.env
  5. 启用 DM pairing,unauthorized_dm_behavior: pair
  6. approvals.mode: manual(或 smart
  7. security.tirith_fail_open: false(高安全环境)
  8. security.allow_private_urls: false
  9. 定期审查 command_allowlist
  10. hermes doctor + hermes update 保持补丁最新
  11. Gateway 以非 root 用户运行
  12. 网络隔离:Gateway 与执行分离(terminal.backend: ssh

English

OpenClaw production: security audit –deep –fix, loopback bind + auth token, pairing DM policy, tighten tool profile, deny/limit exec, workspace-only fs, lock permissions, plugin allowlist, trusted proxies, audit skills directory.

Hermes production: platform allowlists (no allow-all), Docker/modal backend, container limits, secure .env, DM pairing, manual/smart approvals, tirith fail-closed, no private URLs, audit command allowlist, hermes doctor + update, non-root gateway, split gateway/execution via SSH.


八、结语 | Conclusion

中文

OpenClaw 的安全模型是 「身份先行、范围次之、模型最后」 — 用 Gateway 认证、DM 策略、工具 Profile 和 Exec 审批控制爆炸半径,默认信任单操作者,适合快速搭建个人助理并通过 security audit 渐进加固。Hermes 的安全模型是 「七层纵深、默认审慎」 — 危险命令人工审批、硬线黑名单、Tirith 扫描、容器隔离、凭证过滤环环相扣,适合对命令执行安全有更高要求的长期运行场景。两者都不是敌对多租户沙箱;若需此类隔离,唯一可靠方案是 拆分信任边界,而非在单一 Gateway 上叠加更多审批规则。

English

OpenClaw’s security model is identity first, scope second, model last — Gateway auth, DM policies, tool profiles, and exec approvals control blast radius, defaulting to trusted single-operator UX, hardened progressively via security audit. Hermes’s model is seven-layer defense-in-depth with cautious defaults — manual approval, hardline blocklist, Tirith scanning, container isolation, and credential filtering for higher-assurance long-running deployments. Neither is a hostile multi-tenant sandbox; for that, the only reliable approach is splitting trust boundaries, not piling more approval rules onto one Gateway.

Agent Hermes 与 OpenClaw(龙虾)Gateway 架构深度解析

Gateway Architecture in Agent Hermes & OpenClaw (Lobster): A Deep Dive

最后更新 | Last updated: 2026-06-05


一、Gateway 的角色定位 | Gateway Role & Positioning

中文

在两个框架中,Gateway 都是连接外部世界与 Agent 引擎的枢纽,但职责权重不同:

维度 OpenClaw Gateway Hermes Gateway
架构地位 Gateway 即产品 — 唯一控制平面 Gateway 是入口之一,核心在 AIAgent 引擎
实现语言 TypeScript(Node.js) Python
默认端口 18789 无固定公开端口(各平台 Adapter 独立连接)
进程模型 单进程 WebSocket 服务 长驻 GatewayRunner 进程
Agent 运行时 Gateway 内嵌或路由到外部 Runtime 每消息创建 AIAgent 实例
渠道数量 50+(含插件) 20 个内置 Adapter
控制 UI 浏览器 Dashboard CLI TUI + 各平台原生聊天界面

English

In both frameworks, the Gateway is the hub connecting the external world to the agent engine, but with different weight:

Dimension OpenClaw Gateway Hermes Gateway
Architectural role Gateway is the product — sole control plane Gateway is one entry point; core is AIAgent engine
Language TypeScript (Node.js) Python
Default port 18789 No fixed public port (per-platform adapters)
Process model Single WebSocket server Long-running GatewayRunner
Agent runtime Embedded or routed to external runtime AIAgent instance per message
Channels 50+ (with plugins) 20 built-in adapters
Control UI Browser dashboard CLI TUI + native chat on each platform

二、OpenClaw Gateway 架构 | OpenClaw Gateway Architecture

中文

2.1 整体架构

flowchart TB
    subgraph Clients["客户端"]
        PHONE[手机聊天 App]
        WEB[Web Control UI]
        MAC[macOS App]
        IOS[iOS/Android Nodes]
    end
    subgraph GW["OpenClaw Gateway :18789"]
        WS[WebSocket Server]
        ROUTE[会话路由 sessionKey]
        AUTH[认证 gateway.auth]
        TOOLS[工具执行]
        MEM[记忆读写]
    end
    subgraph Agent["Agent Runtime"]
        WP[Workspace 文件注入]
        SK[Skills 加载]
        LLM[LLM 调用]
    end
    PHONE --> WS
    WEB --> WS
    MAC --> WS
    IOS --> WS
    WS --> ROUTE
    ROUTE --> Agent
    Agent --> TOOLS
    Agent --> MEM
    Agent --> WS

OpenClaw 没有独立的「编排微服务层」——Gateway 接收消息、路由会话、调用 LLM、执行工具、写回响应,全部在一个进程中完成。

2.2 消息处理流程

1
2
3
4
5
6
7
1. 聊天 App 发来消息
2. Gateway 接收(WebSocket / 渠道 Webhook)
3. 解析 sessionKey(路由键,非授权令牌)
4. 加载对应 Agent 的 Workspace 文件 + Skills
5. 组装系统提示词,调用 LLM
6. 若有工具调用 → 执行 shell/文件/浏览器/API
7. 响应经 Gateway 发回原渠道

2.3 会话路由(sessionKey)

sessionKey路由选择器,决定使用哪个会话上下文,不是用户认证令牌。

常见隔离策略(session.dmScope):

行为
per-channel-peer 每个发送者独立会话(推荐多用户 DM)
per-account-channel-peer 多账号渠道下按账号+发送者隔离

2.4 多 Agent 路由

OpenClaw 支持在同一 Gateway 上运行多个 Agent,按工作区、发送者或规则路由:

1
2
3
4
Gateway
├── Agent A(工作区 ~/.openclaw/workspace-personal)
├── Agent B(工作区 ~/.openclaw/workspace-work)
└── 路由规则 → 按 channel / sender / mention 分发

2.5 渠道接入

内置渠道:WhatsApp、Telegram、Discord、Slack、Signal、iMessage、Google Chat、Microsoft Teams、WebChat 等。

插件渠道:Matrix、Nostr、Twitch、Zalo、Feishu 等通过 bundled 或 external channel plugins 扩展。

Nodes(移动端):iOS/Android 设备配对后提供 Canvas、相机、语音等工作流。

2.6 配置中心

主配置文件:~/.openclaw/openclaw.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
gateway: {
mode: "local",
bind: "loopback",
auth: { mode: "token", token: "long-random-token" },
},
channels: {
whatsapp: {
dmPolicy: "pairing",
groups: { "*": { requireMention: true } },
},
},
tools: {
profile: "messaging",
exec: { security: "deny", ask: "always" },
},
}

2.7 Web Control UI

本地默认:http://127.0.0.1:18789/

提供聊天、配置、会话管理、节点配对的浏览器控制台。远程访问需 Tailscale 或 SSH 隧道。

English

2.1 Overall Architecture

Single TypeScript process on port 18789: WebSocket server handles all channels, session routing, tool execution, and memory I/O. No separate orchestration microservice — the Gateway is the product.

2.2 Message Flow

Chat app → Gateway (WebSocket/webhook) → sessionKey routing → load workspace + skills → LLM → tools → response back to channel.

2.3 Session Routing (sessionKey)

sessionKey is a routing selector, not an auth token. session.dmScope controls DM isolation (e.g., per-channel-peer for multi-user inboxes).

2.4 Multi-Agent Routing

Multiple agents on one Gateway, routed by workspace, sender, or rules.

2.5 Channel Integration

Built-in channels (WhatsApp, Telegram, Discord, etc.) plus plugin channels (Matrix, Zalo, etc.) and iOS/Android nodes.

2.6 Configuration

Central config at ~/.openclaw/openclaw.json — gateway mode, auth, channel policies, tool profiles.

2.7 Web Control UI

Browser dashboard at http://127.0.0.1:18789/ for chat, config, sessions, and node pairing.


三、Hermes Gateway 架构 | Hermes Gateway Architecture

中文

3.1 整体架构

flowchart TB
    subgraph Platforms["20+ 平台 Adapter"]
        TG[telegram.py]
        DC[discord.py]
        SL[slack.py]
        WA[whatsapp.py]
        CN[dingtalk / feishu / wecom / qqbot]
    end
    subgraph GR["GatewayRunner (gateway/run.py)"]
        HANDLE[_handle_message]
        AUTHZ[用户授权]
        SLASH[斜杠命令分发]
        AGENT[AIAgent 创建]
        GUARD[双层消息守卫]
    end
    subgraph Core["共享核心"]
        AI[AIAgent run_agent.py]
        SS[SessionStore SQLite]
        DEL[delivery.py 出站投递]
    end
    Platforms --> HANDLE
    HANDLE --> AUTHZ
    AUTHZ --> SLASH
    SLASH --> AGENT
    AGENT --> AI
    AI --> SS
    AI --> DEL
    DEL --> Platforms

Hermes Gateway 是 AIAgent 引擎的消息前端,本身不包含独立的 LLM 编排逻辑。

3.2 关键源文件

文件 职责
gateway/run.py GatewayRunner — 主循环、消息分发、斜杠命令
gateway/session.py SessionStore — 会话持久化、session key 构建
gateway/delivery.py 出站消息投递(回复、跨平台、Cron 投递)
gateway/pairing.py DM 配对授权流程
gateway/hooks.py 生命周期 Hook 发现与分发
gateway/platforms/*.py 各平台 Adapter

3.3 消息处理流程

1
2
3
4
5
6
7
8
平台事件 → Adapter.on_message() → MessageEvent
→ GatewayRunner._handle_message()
1. 解析 session key
2. 用户授权检查
3. 斜杠命令?→ 命令处理器
4. Agent 正在运行?→ 双层守卫(排队/中断/审批)
5. 创建 AIAgent → run_conversation()
6. 响应经 Adapter 发回

3.4 Session Key 格式

1
agent:main:{platform}:{chat_type}:{chat_id}

示例:agent:main:telegram:private:123456789

线程型平台(Telegram 论坛话题、Discord/Slack 线程)在 chat_id 中包含线程 ID。禁止手动拼接,应使用 build_session_key()

3.5 双层消息守卫

Agent 正在处理消息时,新消息经过两级拦截:

Level 1 — Base Adaptergateway/platforms/base.py):

  • 检查 _active_sessions
  • 活跃会话 → 消息入 _pending_messages 队列,设置中断事件

Level 2 — GatewayRunnergateway/run.py):

  • 检查 _running_agents
  • /stop/approve/deny 等命令绕过守卫,内联分发
  • 其他消息触发 running_agent.interrupt()

3.6 用户授权

授权检查顺序(_is_user_authorized()):

  1. 平台级 allow-all(如 DISCORD_ALLOW_ALL_USERS=true
  2. DM 配对已批准列表
  3. 平台 allowlist(如 TELEGRAM_ALLOWED_USERS=12345,67890
  4. 全局 allowlist(GATEWAY_ALLOWED_USERS
  5. 全局 allow-all(GATEWAY_ALLOW_ALL_USERS=true
  6. 默认:拒绝

未配置任何 allowlist 时,启动日志会警告所有未授权用户将被拒绝。

3.7 DM 配对流程

1
2
3
未知用户发 DM → Bot 回复 8 位配对码
管理员 CLI:hermes pairing approve telegram ABC12DEF
用户永久授权(存储于 ~/.hermes/pairing/)

安全特性:密码学随机、1 小时 TTL、10 分钟速率限制、5 次失败锁定 1 小时。

3.8 斜杠命令统一分发

CLI 与 Gateway 共享命令注册表(hermes_cli/commands.py):

操作 命令
新对话 /new/reset
换模型 /model [provider:model]
浏览技能 /skills/skill-name
中断 /stop(Gateway)/ Ctrl+C(CLI)
危险命令审批 /approve / /deny
压缩上下文 /compress

Agent 运行中,部分命令(如 /model)会被拒绝,需先 /stop

3.9 出站投递(Delivery)

gateway/delivery.py 支持四种投递模式:

模式 说明
直接回复 响应发回 originating chat
Home Channel Cron/后台结果路由到配置的「主频道」
显式目标 send_message 工具指定 telegram:-1001234567890
跨平台投递 从 Telegram 收到消息,结果发到 Discord

设计决策:Cron 投递不镜像进 Gateway 会话历史,避免消息交替违规。

3.10 平台 Adapter 列表

Adapter 协议/依赖
telegram.py Telegram Bot API(长轮询或 Webhook)
discord.py discord.py
slack.py Slack Socket Mode
whatsapp.py WhatsApp Business Cloud API
signal.py signal-cli REST
matrix.py mautrix(可选 E2EE)
dingtalk.py / feishu.py 钉钉/飞书 WebSocket 或 Webhook
wecom.py / weixin.py 企业微信 / 个人微信 iLink
qqbot/ 腾讯 QQ 官方 API v2
email.py IMAP/SMTP
sms.py Twilio
homeassistant.py Home Assistant 对话集成
api_server.py REST API 适配器
webhook.py 通用入站/出站 Webhook

3.11 Token 锁(Profile 隔离)

使用相同 Bot Token 的 Adapter 在 connect() 时调用 acquire_scoped_lock(),防止多 Profile 同时占用同一 Token。

每个 Profile(hermes -p <name>)拥有独立的 HERMES_HOME、配置、会话和 Gateway PID。

3.12 生命周期 Hooks

事件 触发时机
gateway:startup Gateway 进程启动
session:start / session:end / session:reset 会话生命周期
agent:start / agent:step / agent:end Agent 处理周期
command:* 任意斜杠命令执行

Hook 目录:~/.hermes/hooks/(用户自定义)

3.13 后台维护任务

Gateway 并行运行:

  • Cron 调度 — 检查到期任务并触发
  • 会话过期 — 清理超时废弃会话
  • 记忆刷新 — 会话过期前主动 flush 记忆
  • 缓存刷新 — 模型列表与 Provider 状态

3.14 进程管理

1
2
3
hermes gateway start    # 启动
hermes gateway stop # 停止当前 Profile
hermes gateway stop --all # 停止所有 Profile(更新时用)

PID 文件:~/.hermes/gateway.pid(Profile 作用域)

English

3.1 Overall Architecture

GatewayRunner is the messaging frontend for the shared AIAgent engine. 20+ platform adapters normalize inbound events; the runner handles auth, slash commands, agent creation, and delivery.

3.2 Key Source Files

gateway/run.py (runner), session.py (persistence), delivery.py (outbound), pairing.py (DM auth), platforms/*.py (adapters).

3.3 Message Flow

Platform event → adapter → _handle_message() → auth → slash command or AIAgent → response via adapter.

3.4 Session Key

agent:main:{platform}:{chat_type}:{chat_id} — use build_session_key(), never construct manually.

3.5 Two-Level Message Guard

Adapter-level queuing + runner-level interrupt/approval routing while agent is active.

3.6 User Authorization

Layered allowlists + DM pairing; default deny if no allowlist configured.

3.7 DM Pairing

8-char cryptographic codes, TTL, rate limits, lockout. Approved via hermes pairing approve.

3.8 Shared Slash Commands

CLI and Gateway share COMMAND_REGISTRY/model, /skills, /stop, /approve, etc.

3.9 Delivery Modes

Direct reply, home channel, explicit target, cross-platform. Cron deliveries excluded from gateway session history.

3.10 Platform Adapters

20 built-in adapters covering Telegram, Discord, Slack, WhatsApp, Signal, Matrix, DingTalk, Feishu, WeCom, QQ, email, SMS, Home Assistant, REST API, webhooks, and more.

3.11 Profile Isolation

Per-profile HERMES_HOME, config, sessions, gateway PID, and token locks.

3.12 Hooks & Background Tasks

Lifecycle hooks for startup, sessions, agent steps, commands. Background cron ticking, session expiry, memory flush, cache refresh.


四、Gateway 对比矩阵 | Gateway Comparison Matrix

中文

能力 OpenClaw Hermes
核心哲学 Gateway = 产品 Gateway = AIAgent 入口
协议栈 WebSocket 统一 每平台原生协议
控制 UI 浏览器 Dashboard CLI TUI + 各平台聊天
会话存储 jsonl 文件 SQLite state.db
斜杠命令 渠道内 + Control UI CLI/Gateway 统一注册表
多 Profile Profile 机制 hermes -p <name> 完整隔离
Cron 投递 支持 一等公民,可附 Skills
跨平台投递 支持 delivery.py 显式路由
移动端 Nodes iOS/Android 配对 无原生 Node(靠消息平台)
从对方迁移 hermes claw migrate 导入消息设置

English

Capability OpenClaw Hermes
Core philosophy Gateway = product Gateway = AIAgent entry
Protocol Unified WebSocket Per-platform native protocols
Control UI Browser dashboard CLI TUI + platform chats
Session storage jsonl files SQLite state.db
Slash commands In-channel + Control UI Unified CLI/Gateway registry
Multi-profile Profile mechanism hermes -p <name> full isolation
Cron delivery Supported First-class with skill attachment
Cross-platform delivery Supported Explicit delivery.py routing
Mobile nodes iOS/Android pairing Via messaging platforms only
Migration hermes claw migrate imports messaging config

五、部署模式 | Deployment Patterns

中文

模式 A:本地 Loopback(最安全)

1
笔记本 localhost → Gateway → 仅本机 Control UI / 本地渠道
  • OpenClaw:gateway.bind: "loopback"
  • Hermes:Gateway 默认不暴露 HTTP 端口

模式 B:VPS + 消息平台(最常见)

1
2
$5 VPS → Gateway 长驻 → Telegram/WhatsApp Bot Token
用户在手机上对话,Agent 在云端执行
  • Hermes 推荐 terminal.backend: docker 隔离命令执行
  • OpenClaw 推荐 openclaw security audit 加固

模式 C:分离式(高安全)

1
Gateway 机器(仅消息)──SSH──→ 执行机器(Docker 沙箱)
  • Hermes 原生支持:terminal.backend: ssh
  • OpenClaw:通过 sandbox 配置 + 远程 node

模式 D:Serverless(Hermes 独有)

1
2
Gateway 在 VPS → Agent 命令发往 Modal/Daytona
空闲休眠,按需唤醒,接近零闲置成本

English

Pattern A — Local loopback (safest): bind to localhost only.

Pattern B — VPS + messaging (most common): long-running Gateway on cheap VPS, chat from phone.

Pattern C — Split trust (high security): Gateway on one host, execution on another via SSH/Docker sandbox.

Pattern D — Serverless (Hermes-specific): Modal/Daytona backends with sleep-on-idle.


六、生产部署清单 | Production Deployment Checklist

中文

OpenClaw

  • openclaw security audit --deep 并修复发现项
  • gateway.bind: "loopback" 或配置 gateway.auth
  • dmPolicy: "pairing" + session.dmScope: "per-channel-peer"
  • 收紧 tools.profile,禁用不必要的工具组
  • chmod 锁定 ~/.openclaw 权限
  • 插件仅加载信任来源

Hermes Agent

  • 配置平台 allowlist,禁用 GATEWAY_ALLOW_ALL_USERS
  • terminal.backend: docker(生产 Gateway)
  • 启用 DM pairing
  • chmod 600 ~/.hermes/.env
  • 定期审查 command_allowlist
  • hermes doctor 检查供应链告警

English

OpenClaw: run security audit, bind loopback or enable auth, pairing DM policy, tighten tool profile, lock filesystem permissions, trust-only plugins.

Hermes: configure allowlists, use Docker backend, enable DM pairing, secure .env, audit command allowlist, run hermes doctor.


七、结语 | Conclusion

中文

OpenClaw Gateway 是 「多渠道操作系统」 — 用单一 WebSocket 控制平面统一 50+ 渠道,适合需要极致连接广度与浏览器控制台的场景。Hermes Gateway 是 「Agent 引擎的消息前端」 — 20 个 Adapter 接入同一 AIAgent 核心,与 CLI、ACP、Cron 共享会话存储与斜杠命令,适合需要统一学习闭环与跨入口一致体验的场景。二者都能让你「在 Telegram 上发消息、Agent 在云端干活」,选型应优先考虑你对 连接广度 还是 引擎深度 的需求。

English

OpenClaw Gateway is a multi-channel operating system — one WebSocket control plane for 50+ channels, ideal for maximum connectivity and a browser dashboard. Hermes Gateway is the messaging frontend for the agent engine — 20 adapters into one AIAgent core, sharing session storage and slash commands with CLI, ACP, and Cron. Both let you “message from Telegram while the agent works in the cloud”; choose based on whether you need connectivity breadth or engine depth.

Agent Hermes 与 OpenClaw(龙虾)记忆系统深度解析

Memory Systems in Agent Hermes & OpenClaw (Lobster): A Deep Dive

最后更新 | Last updated: 2026-06-05


一、设计哲学对比 | Design Philosophy Comparison

中文

记忆系统是个人 Agent「是否越用越懂你」的核心。两个框架在此采取了截然不同的路径:

维度 OpenClaw(龙虾) Hermes Agent
存储介质 纯 Markdown 文件 Markdown + SQLite + 可选外部 Provider
更新方式 Agent 按规则写入 MEMORY.md Agent 主动管理 + 闭环学习自动沉淀
检索方式 全量注入系统提示词 分层:冻结注入 + FTS5 按需检索 + 语义搜索
技能与记忆关系 Skills 与 Memory 分离 Skills 是「程序性记忆」的产出
容量策略 文件大小无硬限,但全量进 Prompt 持久记忆有字符上限,技能渐进式披露

English

Memory is central to whether a personal agent “knows you better over time.” The two frameworks take fundamentally different approaches:

Dimension OpenClaw (Lobster) Hermes Agent
Storage medium Plain Markdown files Markdown + SQLite + optional external providers
Update model Agent writes to MEMORY.md per rules Agent-managed + closed-loop auto-curation
Retrieval Full injection into system prompt Layered: frozen injection + FTS5 on-demand + semantic search
Skills vs memory Skills and memory are separate Skills are procedural memory output
Capacity strategy No hard file limit, but full content in prompt Char limits on persistent memory; progressive skill disclosure

二、OpenClaw 记忆架构 | OpenClaw Memory Architecture

中文

2.1 核心理念:文件即记忆

OpenClaw 将 Agent 的「身份」与「知识」完全外化为工作区中的 Markdown 文件。默认路径:~/.openclaw/workspace/

1
2
3
4
5
6
7
8
9
10
~/.openclaw/workspace/
├── SOUL.md # 人格(每次会话注入,通常人工维护)
├── AGENTS.md # 操作手册(含记忆规则)
├── USER.md # 用户偏好
├── MEMORY.md # 长期记忆(Agent 可更新)
├── memory/ # 日记式记忆
│ ├── 2026-06-01.md
│ └── 2026-06-05.md
└── skills/ # 技能(与记忆分离)
└── weather/SKILL.md

2.2 系统提示词注入顺序

OpenClaw 在会话启动时按固定顺序组装系统提示词:

  1. SOUL.md — 人格优先,影响模型注意力分配
  2. IDENTITY.md — Agent 身份信息
  3. USER.md — 用户上下文
  4. AGENTS.md — 工具与流程指令
  5. MEMORY.md — 持久知识(变化最频繁,靠后注入)

这种顺序设计确保人格指令优先于易变的记忆内容。

2.3 记忆类型划分

类型 文件 管理者 典型内容
人格记忆 SOUL.md 用户(可 Git 管理) 语气、边界、价值观
用户画像 USER.md 用户 + Agent 姓名、时区、沟通偏好
长期事实 MEMORY.md Agent 项目路径、约定、重要决策
日记记忆 memory/*.md Agent 按日归档的对话摘要
程序性知识 skills/*/SKILL.md 用户/社区 工作流、操作步骤

2.4 记忆更新机制

OpenClaw 的记忆更新依赖 AGENTS.md 中定义的规则。Agent 在会话中根据指令决定是否写入 MEMORY.mdmemory/YYYY-MM-DD.md。没有内置的:

  • 自动技能生成
  • FTS5 历史检索
  • 记忆容量管理与整合

优势是透明、可审计;劣势是随记忆增长,系统提示词 Token 成本线性上升。

2.5 会话持久化

会话记录存储在 ~/.openclaw/agents/<agent>/sessions/*.jsonl,用于会话连续性和可选的记忆索引,但不等于结构化记忆检索层。磁盘访问权限即信任边界。

English

2.1 Core Idea: Files as Memory

OpenClaw externalizes agent identity and knowledge as Markdown in the workspace. Default path: ~/.openclaw/workspace/.

2.2 System Prompt Injection Order

At session start, files assemble in fixed order: SOUL.md → IDENTITY.md → USER.md → AGENTS.md → MEMORY.md. Persona instructions precede volatile memory content.

2.3 Memory Type Taxonomy

Type File Maintainer Typical content
Persona memory SOUL.md User (Git-managed) Tone, boundaries, values
User profile USER.md User + agent Name, timezone, preferences
Long-term facts MEMORY.md Agent Project paths, conventions, decisions
Diary memory memory/*.md Agent Daily conversation summaries
Procedural knowledge skills/*/SKILL.md User/community Workflows, procedures

2.4 Update Mechanism

Updates follow rules in AGENTS.md. No built-in auto-skill generation, FTS5 history search, or capacity management. Transparent and auditable, but prompt token cost grows linearly with memory size.

2.5 Session Persistence

Transcripts live in ~/.openclaw/agents/<agent>/sessions/*.jsonl for continuity and optional indexing — not a structured memory retrieval layer. Filesystem access is the trust boundary.


三、Hermes Agent 记忆架构 | Hermes Agent Memory Architecture

中文

3.1 四层记忆模型

flowchart TB
    subgraph L1["第一层:工作记忆 Working Memory"]
        CTX[当前对话上下文]
    end
    subgraph L2["第二层:会话记忆 Session Memory"]
        DB[(SQLite state.db)]
        FTS[FTS5 全文索引]
        TRIG[Trigram 索引 CJK]
    end
    subgraph L3["第三层:持久记忆 Persistent Memory"]
        MEM[MEMORY.md ~2200 chars]
        USER[USER.md ~1375 chars]
    end
    subgraph L4["第四层:技能记忆 Skill Memory"]
        SKILLS[~/.hermes/skills/]
        PROG[渐进式披露]
    end
    subgraph EXT["外部记忆 Provider(可选)"]
        HON[Honcho 用户建模]
        MEM0[Mem0]
        OTH[OpenViking / Hindsight / ...]
    end
    CTX --> DB
    DB --> FTS
    MEM --> CTX
    USER --> CTX
    SKILLS --> PROG
    EXT -.-> CTX

3.2 第一层:工作记忆

当前会话中的消息、工具调用结果、压缩后的历史摘要。由 ContextCompressor 在上下文超阈值时进行有损压缩,触发会话分裂(parent_session_id 链)。

3.3 第二层:会话记忆(SQLite + FTS5)

存储位置~/.hermes/state.db(WAL 模式)

核心表结构

1
2
3
4
5
6
state.db
├── sessions — 会话元数据、Token 统计、计费
├── messages — 完整消息历史
├── messages_fts — FTS5 全文索引(content + tool_name + tool_calls)
├── messages_fts_trigram — Trigram 分词器(中日韩子串搜索)
└── state_meta — 键值元数据

检索工具session_search

特性 持久记忆 MEMORY.md 会话搜索 session_search
容量 ~1300 tokens 固定 无限(所有历史会话)
速度 即时(已在 Prompt 中) ~20ms FTS5 查询
成本 每会话固定 Token 开销 按需,无 LLM 调用
用途 关键事实常驻 「上周我们讨论过 X 吗?」

FTS5 查询语法

语法 示例 含义
关键词 docker deployment 隐式 AND
引号短语 "exact phrase" 精确匹配
布尔 OR docker OR kubernetes 任一匹配
前缀 deploy* 前缀匹配

写入争用处理:Gateway 多平台并发写入时,采用 1 秒超时 + 最多 15 次随机抖动重试(20–150ms)+ BEGIN IMMEDIATE 事务。

3.4 第三层:持久记忆

两个受字符上限约束的文件,位于 ~/.hermes/memories/

文件 用途 上限
MEMORY.md Agent 个人笔记:环境事实、约定、经验教训 2,200 字符(~800 tokens)
USER.md 用户画像:偏好、沟通风格、期望 1,375 字符(~500 tokens)

冻结快照模式:会话启动时将记忆渲染进系统提示词后不再变更(保护 LLM 前缀缓存)。Agent 在会话中通过 memory 工具增删改,变更立即落盘,但下次会话才进入 Prompt。

memory 工具操作

1
2
3
memory(action="add",    target="memory", content="...")
memory(action="replace", target="user", old_text="dark mode", content="...")
memory(action="remove", target="memory", old_text="obsolete entry")

安全扫描:写入前检测 Prompt 注入、凭证外泄、不可见 Unicode 字符。

3.5 第四层:技能记忆(程序性记忆)

技能是 Hermes 闭环学习的核心产出,存储于 ~/.hermes/skills/

渐进式披露(Progressive Disclosure)

1
2
3
Level 0: skills_list()        → [{name, description}]     (~3k tokens)
Level 1: skill_view(name) → 完整 SKILL.md 内容 (按需)
Level 2: skill_view(name, path) → 特定参考文件 (按需)

效果:技能库从 40 个增长到 200 个,上下文成本几乎不变。

自动创建触发条件skill_manage 工具):

  • 完成 5+ 次工具调用的复杂任务
  • 经历错误并找到正确路径
  • 用户纠正了 Agent 做法
  • 发现非平凡工作流

自改进:优先使用 patchold_string / new_string)而非全量 edit,节省 Token。

3.6 外部记忆 Provider

Hermes 内置 8 种可选外部 Provider,与内置记忆并行运行(不替代):

Provider 能力
Honcho 辩证式用户建模
Mem0 自动事实提取
OpenViking 知识图谱
Hindsight 长期回忆增强
Holographic 语义向量检索
RetainDB / ByteRover / Supermemory 各专精场景

配置:hermes memory setup / hermes memory status

3.7 闭环学习与记忆的协同

sequenceDiagram
    participant U as 用户
    participant A as AIAgent
    participant M as Memory Manager
    participant S as Skill Store
    participant DB as SQLite FTS5
    U->>A: 复杂任务请求
    A->>A: 执行工具(5+ 次)
    A->>M: 策划记忆(add/replace)
    A->>S: skill_manage(create)
    A->>DB: 持久化会话消息
    Note over A,S: 下次同类任务
    A->>S: skill_view(按需加载)
    A->>DB: session_search(历史召回)
    A->>U: 更高效响应

English

3.1 Four-Layer Memory Model

Working memory (current context) → Session memory (SQLite + FTS5) → Persistent memory (MEMORY.md / USER.md with char limits) → Skill memory (progressive disclosure in ~/.hermes/skills/). Optional external providers (Honcho, Mem0, etc.) run in parallel.

3.2 Layer 1: Working Memory

Current session messages and tool results. ContextCompressor summarizes when context exceeds thresholds, triggering session splits via parent_session_id chains.

3.3 Layer 2: Session Memory

Stored in ~/.hermes/state.db (WAL mode). FTS5 + trigram indexes for full-text and CJK substring search. session_search tool for on-demand recall. Write contention handled with short timeouts and jittered retries.

3.4 Layer 3: Persistent Memory

MEMORY.md (2200 chars) and USER.md (1375 chars) in ~/.hermes/memories/. Frozen snapshot at session start for prefix-cache stability. memory tool for add/replace/remove with security scanning.

3.5 Layer 4: Skill Memory

Procedural memory in ~/.hermes/skills/ with progressive disclosure (index → full content on demand). Auto-created after complex tasks; self-improved via skill_manage patch.

3.6 External Memory Providers

8 optional providers (Honcho, Mem0, OpenViking, Hindsight, etc.) complement built-in memory.

3.7 Learning Loop Synergy

Task completion → memory curation → skill creation → FTS5 indexing → faster recall on similar future tasks.


四、关键差异总结 | Key Differences Summary

中文

场景 OpenClaw 做法 Hermes 做法
记住用户偏好 写入 USER.md,全量注入 写入 USER.md(有上限),冻结注入
回忆上周对话 依赖 MEMORY.md 摘要或重新阅读 jsonl session_search FTS5 按需检索
沉淀重复工作流 手动编写 SKILL.md 任务完成后自动生成 + patch 优化
控制 Token 成本 精简 Markdown 文件 字符上限 + 渐进式技能披露 + 压缩
跨会话用户理解 静态文件累积 Honcho 辩证建模 + 周期性微调
记忆可审计性 极高(纯文本 Git) 高(Markdown + SQLite 可导出)

English

Scenario OpenClaw Hermes
Remember user preferences Write USER.md, full injection Write USER.md (capped), frozen injection
Recall last week’s chat MEMORY.md summary or jsonl replay session_search FTS5 on demand
Capture repeated workflows Manual SKILL.md Auto-create + patch after tasks
Control token cost Trim Markdown files Char limits + progressive skills + compression
Cross-session user modeling Static file accumulation Honcho dialectic + periodic nudge
Auditability Very high (plain text Git) High (Markdown + exportable SQLite)

五、最佳实践 | Best Practices

中文

OpenClaw

  1. 职责分离:人格写 SOUL.md,流程写 AGENTS.md,事实写 MEMORY.md
  2. 版本管理:SOUL.md 和 AGENTS.md 纳入 Git;MEMORY.md 可让 Agent 自管
  3. 控制体积:MEMORY.md 定期人工审查,避免 Prompt 膨胀
  4. 日记归档:用 memory/YYYY-MM-DD.md 分离当日 ephemeral 内容

Hermes Agent

  1. 善用分层:关键事实放 MEMORY.md;历史细节靠 session_search
  2. 监控容量:MEMORY.md 超 80% 时主动整合条目
  3. 信任技能索引:不必手动维护大量 Skill,让闭环学习自动沉淀
  4. 选配 Provider:需要深度用户建模时启用 Honcho;简单场景用内置即可
  5. 从龙虾迁移hermes claw migrate 导入 MEMORY.md / USER.md 条目

English

OpenClaw

  1. Separate concerns: SOUL.md (persona), AGENTS.md (procedures), MEMORY.md (facts)
  2. Version-control SOUL.md and AGENTS.md in Git
  3. Periodically audit MEMORY.md to control prompt size
  4. Use memory/YYYY-MM-DD.md for daily ephemeral content

Hermes Agent

  1. Use layers: critical facts in MEMORY.md; historical detail via session_search
  2. Consolidate when MEMORY.md exceeds ~80% capacity
  3. Trust the skill index — let the learning loop accumulate procedural memory
  4. Enable external providers (e.g., Honcho) only when deeper user modeling is needed
  5. Migrate from OpenClaw with hermes claw migrate

六、结语 | Conclusion

中文

OpenClaw 的记忆系统是 「透明文件柜」——简单、可读、完全由人掌控,适合重视可审计性与手动定制的用户。Hermes 的记忆系统是 「分层图书馆 + 自学习档案员」——通过 SQLite 检索、字符预算、技能渐进披露和闭环学习,在 Token 成本可控的前提下实现「越用越懂你」。选择哪套记忆架构,本质上是在 可控透明度自动进化效率 之间做权衡。

English

OpenClaw’s memory is a transparent filing cabinet — simple, readable, fully human-controlled, ideal for users who value auditability and manual curation. Hermes’s memory is a layered library with a self-learning archivist — SQLite search, char budgets, progressive skill disclosure, and closed-loop learning deliver “knows you better over time” with controlled token cost. The choice is fundamentally a tradeoff between transparent control and automatic evolutionary efficiency.

Agent Hermes 与 OpenClaw(龙虾):架构、应用与对比

Agent Hermes & OpenClaw (Lobster): Architecture, Applications, and Comparison

最后更新 | Last updated: 2026-06-05


一、背景与定位 | Background & Positioning

中文

2026 年初,个人 AI Agent 领域出现两个现象级开源项目:

  • OpenClaw(龙虾):吉祥物是太空龙虾 Molty 🦞,GitHub Star 超 35 万,社区称其为「养虾」——在本地或服务器上长期运行一只个人助理。
  • Hermes Agent(爱马仕):由 Nous Research 发布,定位是 “The agent that grows with you”(与你共同成长的智能体),核心差异是内置 闭环学习系统(Learning Loop)

二者均为 MIT 协议、可自托管、支持多渠道消息,但设计哲学不同:

维度 OpenClaw(龙虾) Hermes Agent
核心问题 连接 — 让 AI 接入工具与聊天渠道 进化 — 让 AI 从经验中学习并自我改进
架构重心 Gateway 控制平面 Agent Engine + 学习闭环
技能来源 用户/社区手动编写 SKILL.md 任务完成后 自动生成 + 自我迭代
记忆模式 Markdown 工作区文件 分层记忆 + SQLite FTS5 检索

English

In early 2026, two standout open-source personal AI agent projects emerged:

  • OpenClaw (Lobster): Mascot Molty the space lobster 🦞, 350K+ GitHub stars; Chinese communities call it “raising a lobster” — running a persistent personal assistant locally or on a server.
  • Hermes Agent: Built by Nous Research, positioned as “The agent that grows with you”, with a built-in closed learning loop.

Both are MIT-licensed, self-hostable, and multi-channel — but their design philosophies diverge:

Dimension OpenClaw (Lobster) Hermes Agent
Core problem Connectivity — tools + chat channels Evolution — learn and improve from experience
Architecture focus Gateway control plane Agent engine + learning loop
Skills User/community-authored SKILL.md Auto-generated + self-improving after tasks
Memory Markdown workspace files Layered memory + SQLite FTS5 search

二、OpenClaw(龙虾)架构设计 | OpenClaw Architecture

中文

OpenClaw 的核心理念是:Gateway 即产品。单一 TypeScript 进程监听默认端口 18789,统一管理所有渠道连接、会话路由与工具执行。

flowchart TB
    subgraph Channels["消息渠道"]
        WA[WhatsApp]
        TG[Telegram]
        DC[Discord]
        SL[Slack]
        IM[iMessage]
        SG[Signal]
        MORE[50+ 渠道...]
    end
    subgraph Gateway["OpenClaw Gateway :18789"]
        ROUTE[会话路由]
        TOOLS[工具执行]
        MEM[记忆读写]
    end
    subgraph Runtime["Agent Runtime"]
        WP[工作区文件注入]
        SK[Skills 加载]
        LLM[LLM 推理]
    end
    Channels --> Gateway
    Gateway --> Runtime
    Runtime --> Gateway
    Gateway --> Channels

2.1 工作区文件体系(Workspace Bootstrap)

Agent 的「人格」与「知识」以纯 Markdown 文件存在,默认位于 ~/.openclaw/workspace/

文件 作用
SOUL.md 人格、语气、价值观、行为边界
AGENTS.md 操作手册:工作流、记忆规则、多 Agent 协作
USER.md 用户偏好与身份信息
TOOLS.md 工具使用指南
MEMORY.md 长期记忆(Agent 可周期性更新)
HEARTBEAT.md 主动巡检任务(如晨间简报)
IDENTITY.md Agent 名称、头像等元数据
skills/*/SKILL.md 可扩展技能包

每次会话启动时,这些文件按固定顺序注入系统提示词:SOUL.md 优先(人格),MEMORY.md 靠后(变化最频繁)。

2.2 三层扩展体系

  1. Workspace 文件 — 人格与上下文
  2. Skills(SKILL.md) — 按需加载的能力包
  3. Channel Plugins — Matrix、Nostr、Twitch 等渠道插件

2.3 多 Agent 路由

Gateway 支持按发送者、工作区或 Agent 实例隔离会话,适合「一个 Gateway、多个专职 Agent」的场景。

English

OpenClaw’s core idea: the Gateway is the product. A single TypeScript process on port 18789 manages all channel connections, session routing, and tool execution.

2.1 Workspace Bootstrap Files

Agent identity and knowledge live as plain Markdown under ~/.openclaw/workspace/:

File Purpose
SOUL.md Persona, tone, values, behavioral boundaries
AGENTS.md Operating manual: workflows, memory rules, multi-agent coordination
USER.md User preferences and identity
TOOLS.md Tool usage guidance
MEMORY.md Long-term memory (periodically updated by the agent)
HEARTBEAT.md Proactive checks (e.g., morning briefings)
IDENTITY.md Agent name, avatar, metadata
skills/*/SKILL.md Extensible skill packages

At session start, files inject into the system prompt in a fixed order: SOUL.md first (persona), MEMORY.md last (most volatile).

2.2 Three-Layer Extension System

  1. Workspace files — persona and context
  2. Skills (SKILL.md) — on-demand capability packs
  3. Channel plugins — Matrix, Nostr, Twitch, etc.

2.3 Multi-Agent Routing

The Gateway isolates sessions per sender, workspace, or agent instance — one Gateway, many specialized agents.


三、Hermes Agent 架构设计 | Hermes Agent Architecture

中文

Hermes 的架构重心是 AIAgent 同步编排引擎run_agent.py),而非微服务。CLI、Gateway、ACP(IDE 集成)、Cron、Batch Runner 共用同一 Agent 核心。

flowchart TB
    subgraph Entry["入口层"]
        CLI[CLI / TUI]
        GW[Gateway 20+ 平台]
        ACP[ACP - VS Code/Zed]
        CRON[Cron 调度器]
    end
    subgraph Core["AIAgent 核心引擎"]
        PB[Prompt Builder]
        PR[Provider 解析 18+ 模型]
        TD[Tool Dispatch 70+ 工具]
        CC[上下文压缩]
    end
    subgraph Memory["记忆与学习"]
        WM[工作记忆]
        SM[会话记忆 SQLite+FTS5]
        PM[持久记忆 MEMORY.md/USER.md]
        SKM[技能记忆 Skills]
        HON[Honcho 用户建模]
    end
    subgraph Exec["执行环境"]
        T1[Local]
        T2[Docker]
        T3[SSH]
        T4[Daytona/Modal Serverless]
    end
    Entry --> Core
    Core --> Memory
    Core --> Exec
    Memory -->|闭环学习| SKM

3.1 Agent 循环(Agent Loop)

标准流程:

1
2
3
4
用户消息 → 构建 Prompt(系统提示 + 记忆 + 上下文)
→ 调用 LLM(支持 chat_completions / codex_responses / anthropic_messages 三种 API 模式)
→ 解析工具调用 → 执行工具 → 结果回注上下文
→ 循环直至 LLM 不再请求工具 → 返回最终响应 → 持久化会话

设计原则包括:提示词稳定性(会话中不突变,保护前缀缓存)、可观测执行(每次工具调用对用户可见)、可中断(用户可随时取消)。

3.2 四层记忆体系

层级 机制 特点
工作记忆 当前对话上下文 即时可用
会话记忆 SQLite + FTS5 全文检索 跨会话搜索历史对话,session_search 工具按需召回
持久记忆 MEMORY.md2200 字符)+ USER.md1375 字符) 会话启动时冻结注入系统提示词
技能记忆 ~/.hermes/skills/ 下的 SKILL.md 渐进式披露:索引仅含名称/描述,全文按需加载

此外支持 8 种外部记忆 Provider(Honcho、Mem0、Hindsight 等),用于知识图谱、语义检索、跨会话用户建模。

3.3 闭环学习(Learning Loop)

Hermes 最核心的差异化能力:

  1. 策划记忆 — 任务完成后,Agent 自主判断什么值得记住
  2. 创建 Skill — 复杂任务(通常 5+ 次工具调用)成功后,自动生成 Markdown 格式 Skill
  3. Skill 自改进 — 执行失败或发现更优路径时,通过 skill_manage 工具 patch 更新
  4. 周期性微调(Periodic Nudge) — 会话间隙触发自我反思与优化
  5. FTS5 召回 — 按需检索历史,经 LLM 摘要后注入相关片段

技能库可从几十个增长到上百个,而上下文 Token 成本几乎不变(仅加载索引 + 按需全文)。

3.4 工具与执行环境

  • 70+ 工具,28 个 toolsets,模块级自注册(registry.register()
  • 6 种终端后端:Local、Docker、SSH、Daytona、Modal、Singularity
  • 5 种浏览器后端 + MCP 双向支持(既可作 MCP 客户端,也可被 Cursor/VS Code 接入)
  • 子 Agent 委派delegate_tool 生成隔离子代理并行处理

3.5 Gateway 与多渠道

单一 Gateway 进程支持 20 个平台适配器:Telegram、Discord、Slack、WhatsApp、Signal、Matrix、钉钉、飞书、企业微信、QQ 等。与 CLI 共享斜杠命令(/model/skills/compress 等)。

English

Hermes centers on the AIAgent synchronous orchestration engine (run_agent.py) — not microservices. CLI, Gateway, ACP (IDE), Cron, and Batch Runner share one agent core.

3.1 Agent Loop

1
2
3
4
User message → Build prompt (system + memory + context)
→ Call LLM (3 API modes: chat_completions / codex_responses / anthropic_messages)
→ Parse tool calls → Execute → Inject results
→ Loop until no more tool calls → Final response → Persist session

Design principles: prompt stability (no mid-session mutations, preserves prefix cache), observable execution, interruptibility.

3.2 Four-Layer Memory

Layer Mechanism Trait
Working memory Current conversation context Immediate
Session memory SQLite + FTS5 full-text search Cross-session recall via session_search
Persistent memory MEMORY.md (2200 chars) + USER.md (1375 chars) Frozen into system prompt at session start
Skill memory SKILL.md under ~/.hermes/skills/ Progressive disclosure: index only, full content on demand

Plus 8 external memory providers (Honcho, Mem0, Hindsight, etc.) for knowledge graphs and semantic search.

3.3 Closed Learning Loop

Hermes’s key differentiator:

  1. Curate memory — after tasks, decide what’s worth remembering
  2. Create skills — auto-generate Markdown skills after complex tasks (typically 5+ tool calls)
  3. Self-improve skills — patch via skill_manage on failure or better paths
  4. Periodic Nudge — self-reflection between sessions
  5. FTS5 recall — search history, LLM-summarize, inject relevant snippets

Skill libraries can grow from dozens to hundreds with near-flat context token cost.

3.4 Tools & Execution Environments

  • 70+ tools, 28 toolsets, self-registering at import time
  • 6 terminal backends: Local, Docker, SSH, Daytona, Modal, Singularity
  • 5 browser backends + bidirectional MCP (client and server for Cursor/VS Code)
  • Sub-agent delegation via delegate_tool

3.5 Gateway & Multi-Channel

One Gateway process, 20 platform adapters: Telegram, Discord, Slack, WhatsApp, Signal, Matrix, DingTalk, Feishu, WeCom, QQ, etc. Shares slash commands with CLI (/model, /skills, /compress).


四、典型应用场景 | Typical Use Cases

中文

OpenClaw(龙虾)擅长

场景 说明
口袋里的个人助理 手机 Telegram/WhatsApp 发消息,Gateway 在本地/服务器响应
多渠道统一入口 一个 Gateway 同时服务 Discord + Slack + iMessage
开发者编码助手 与 Claude Code / Cursor 等 Agent Runtime 集成
主动巡检 HEARTBEAT.md 定义定时检查(邮件、日历、服务器状态)
多 Agent 分工 不同工作区/发送者路由到不同专职 Agent
社区生态 海量 Skills 市场、插件、教程

Hermes Agent 擅长

场景 说明
长期个人进化 用得越久,技能库越丰富,越贴合个人习惯
自动化 Cron 任务 自然语言描述日报、备份、周审计,无人值守投递到任意平台
研究 / RL 轨迹 批量生成 ShareGPT 格式轨迹,用于训练工具调用模型
低成本 Serverless Daytona/Modal 后端:空闲休眠、按需唤醒,接近零闲置成本
从龙虾迁移 hermes claw migrate 一键导入 SOUL.md、记忆、技能、API Key
企业级安全审批 危险命令强制审批、容器隔离、DM 配对白名单

English

OpenClaw Excels At

Scenario Description
Pocket personal assistant Message from Telegram/WhatsApp; Gateway responds locally/on server
Unified multi-channel hub One Gateway for Discord + Slack + iMessage simultaneously
Developer coding assistant Integrates with Claude Code / Cursor agent runtimes
Proactive monitoring HEARTBEAT.md defines scheduled checks (email, calendar, servers)
Multi-agent specialization Route by workspace/sender to dedicated agents
Community ecosystem Large skills marketplace, plugins, tutorials

Hermes Excels At

Scenario Description
Long-term personal evolution Richer skill library and better habit fit over time
Cron automation Natural-language daily reports, backups, audits — unattended delivery
Research / RL trajectories Batch ShareGPT-format trajectories for tool-calling model training
Low-cost serverless Daytona/Modal backends: sleep when idle, wake on demand
Migration from OpenClaw hermes claw migrate imports SOUL.md, memory, skills, API keys
Enterprise-grade safety Dangerous-command approval, container isolation, DM pairing allowlists

五、优缺点对比 | Pros & Cons Comparison

中文

OpenClaw(龙虾)

优点

  • 社区体量极大,文档、教程、第三方 Skills 丰富
  • Gateway 架构简洁直观,「一个进程、一个端口」易于理解
  • 渠道覆盖广(50+),含 iOS/Android Nodes、Web Control UI
  • 工作区文件(SOUL.md 等)人类可读、可 Git 版本管理
  • 本地优先,数据主权在用户手中
  • 上手快:openclaw onboard 引导式安装

缺点

  • 记忆与技能主要靠人工维护,缺少内置自学习闭环
  • 技能不会随使用自动优化,重复任务仍需重新推理
  • 广泛文件/系统访问带来安全风险,需仔细配置 allowlist
  • 云模型 API 费用可能较高($10–150+/月,视用量而定)
  • 静态配置为主,「越用越懂你」需额外 Skills 或手动维护 MEMORY.md

Hermes Agent

优点

  • 唯一内置完整闭环学习的 Agent 框架
  • 技能自动生成与自我迭代,重复任务效率显著提升
  • 四层记忆 + FTS5 按需检索,Token 成本可控
  • 模型无关,支持 18+ Provider(OpenRouter、NIM、Kimi、GLM 等)
  • 6 种执行后端 + Serverless,$5 VPS 到 GPU 集群均可
  • 官方提供 OpenClaw 迁移工具,降低切换成本
  • 研究友好:轨迹导出、批量 Runner、RL 环境支持

缺点

  • 生态较新,社区规模小于 OpenClaw
  • 学习闭环增加系统复杂度,调试需理解记忆/技能机制
  • 持久记忆有字符上限(MEMORY.md ~2200 字符),需主动整合
  • 企业集成与大型社区插件市场仍在建设中
  • Windows 需 WSL2,不支持原生 Windows

English

OpenClaw (Lobster)

Pros

  • Massive community, docs, tutorials, third-party skills
  • Simple Gateway: one process, one port
  • Broad channel coverage (50+), iOS/Android nodes, Web Control UI
  • Human-readable workspace files, Git-versionable
  • Local-first, user data sovereignty
  • Fast onboarding via openclaw onboard

Cons

  • Memory and skills mostly manual; no built-in self-learning loop
  • Skills don’t auto-improve; repeated tasks re-reason each time
  • Broad file/system access raises security risk; careful allowlist config needed
  • Cloud model API costs can be high ($10–150+/month depending on usage)
  • Static config; “knows you better over time” needs extra skills or manual MEMORY.md

Hermes Agent

Pros

  • Only major framework with a built-in closed learning loop
  • Auto-generated, self-improving skills; big gains on repeated tasks
  • Four-layer memory + FTS5 on-demand recall; controlled token cost
  • Model-agnostic, 18+ providers (OpenRouter, NIM, Kimi, GLM, etc.)
  • 6 execution backends + serverless; $5 VPS to GPU cluster
  • Official OpenClaw migration tool
  • Research-ready: trajectory export, batch runner, RL environments

Cons

  • Newer ecosystem, smaller community than OpenClaw
  • Learning loop adds complexity; debugging requires understanding memory/skills
  • Persistent memory has char limits (~2200 for MEMORY.md); active consolidation needed
  • Enterprise integrations and large plugin marketplace still maturing
  • Windows requires WSL2; no native Windows

六、架构哲学对比 | Architectural Philosophy Comparison

flowchart LR
    subgraph OpenClaw["OpenClaw 龙虾 — 广度优先"]
        OC_GW[Gateway 控制平面]
        OC_WS[Workspace Markdown]
        OC_SK[手动 Skills]
        OC_CH[50+ 渠道]
        OC_GW --> OC_WS
        OC_GW --> OC_SK
        OC_GW --> OC_CH
    end
    subgraph Hermes["Hermes — 深度优先"]
        HM_EN[Agent Engine]
        HM_LL[Learning Loop]
        HM_MEM[四层记忆]
        HM_SK[自生成 Skills]
        HM_GW[Gateway 20+ 平台]
        HM_EN --> HM_LL
        HM_LL --> HM_MEM
        HM_LL --> HM_SK
        HM_EN --> HM_GW
    end

中文总结

  • 龙虾 回答的是:「如何让 AI 连上我的世界?」— Gateway + 文件即配置。
  • Hermes 回答的是:「如何让 AI 在使用中变得更聪明?」— Engine + 学习闭环。

二者并非简单替代关系。Hermes 官方提供 hermes claw migrate,说明其定位是承接龙虾用户、并叠加自进化能力。社区也有 HermesClaw 等项目,尝试在同一微信账号上同时运行两者。

选型建议:

你的需求 推荐
多渠道聊天、快速上手、庞大社区 OpenClaw
长期运行、自动沉淀技能、研究轨迹 Hermes Agent
已有龙虾部署、想尝试自学习 hermes claw migrate
编码为主、IDE 深度集成 两者均可;OpenClaw 与 Cursor/Claude Code 生态更成熟

English Summary

  • OpenClaw asks: “How do I connect AI to my world?” — Gateway + files-as-config.
  • Hermes asks: “How does AI get smarter through use?” — Engine + learning loop.

They’re not simple replacements. Hermes ships hermes claw migrate to onboard OpenClaw users with self-evolution on top. Community projects like HermesClaw run both on the same WeChat account.

Selection guide:

Your need Recommendation
Multi-channel chat, fast start, large community OpenClaw
Long-running use, auto skill accumulation, research trajectories Hermes Agent
Existing OpenClaw setup, want self-learning hermes claw migrate
Coding-first, deep IDE integration Both work; OpenClaw + Cursor/Claude Code ecosystem is more mature

七、快速上手命令对照 | Quick Start Command Reference

操作 OpenClaw(龙虾) Hermes Agent
安装 npm install -g openclaw@latest curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash
初始化 openclaw onboard --install-daemon hermes setup
启动服务 openclaw dashboard hermes gateway start
对话 Web Control UI 或聊天 App hermes 或 Telegram 等
人格配置 编辑 ~/.openclaw/workspace/SOUL.md /personality 或 SOUL 迁移
技能管理 skills/ 目录 + SKILL.md /skills + 自动生成 + Skills Hub
从对方迁移 hermes claw migrate
诊断 Gateway 日志 hermes doctor

八、延伸阅读(完整 12 篇系列)| Further Reading (Full 12-Article Series)

# 主题 文档
1 总览 hermes-openclaw-overview.md
2 部署迁移 deploy-migrate-operations.md
3 工作区与 Prompt workspace-context-prompt.md
4 Gateway gateway.md
5 记忆系统 memory-system.md
6 技能与学习闭环 skills-learning-loop.md
7 工具与执行环境 tools-execution-environments.md
8 插件与 MCP plugins-mcp-ecosystem.md
9 多 Agent multi-agent-delegation.md
10 自动化调度 automation-cron-heartbeat.md
11 模型与成本 model-provider-cost.md
12 安全模型 security-model.md

知识点覆盖矩阵:knowledge-map.md


九、结语 | Conclusion

中文

Agent Hermes 与 OpenClaw(龙虾)代表了个人 AI Agent 的两条演进路线:连接广度学习深度。龙虾用 Gateway 把 AI 带进你的消息应用和工作区;Hermes 用闭环学习让 AI 从每一次任务中沉淀经验。在实际部署中,二者可以共存、迁移、甚至互补——关键取决于你是更需要「随时随地的多渠道助理」,还是「越用越懂你的自进化伙伴」。

English

Agent Hermes and OpenClaw (Lobster) represent two evolution paths for personal AI agents: connectivity breadth vs. learning depth. OpenClaw’s Gateway brings AI into your messaging apps and workspace; Hermes’s closed loop turns every task into lasting experience. In practice they can coexist, migrate, and complement each other — the choice depends on whether you need an always-available multi-channel assistant or a self-evolving partner that knows you better over time.

Baseline Environment & Minimum-Set Environment: Concepts, Philosophy, and Practice

一、概述 | Overview

**中文:**在微服务、云原生和持续交付日益普及的今天,环境管理已成为研发效能的关键瓶颈之一。一条业务调用链往往涉及数十甚至上百个服务;若每次开发、联调、测试都为全链路拉起一套完整环境,成本高昂、维护困难,且资源利用率极低。

为此,业界逐步形成了环境分层思路:用一套稳定、完整的基准环境(Baseline Environment)承载全量服务,再用轻量、隔离的最小集环境(Minimum-Set Environment)只部署变更或必要的服务。二者协同,在稳定性、隔离性、成本之间取得平衡。

English: As microservices, cloud-native architectures, and continuous delivery become mainstream, environment management has become a major bottleneck in engineering productivity. A single business call chain may involve dozens or even hundreds of services. If every development, integration, and testing session requires spinning up a full copy of the entire chain, costs soar, maintenance becomes painful, and resource utilization stays very low.
The industry has responded with environment layering: a stable, complete Baseline Environment hosts all services, while lightweight, isolated Minimum-Set Environments deploy only changed or essential services. Together, they balance stability, isolation, and cost.

二、核心概念 | Core Concepts

2.1 基准环境(Baseline Environment)

  • 定义:包含全量稳定服务的参考环境,通常部署生产主干或最新稳定版本代码
  • 定位:环境中的”锚点”与”公共底座”,为其他环境提供未变更服务的依赖支撑
  • 特征:服务齐全、版本统一、变更受控、长期可用
  • 类比:像城市的主干道与公共设施——稳定运行,供各分支道路接入

Definition: A reference environment containing the full set of stable services, typically running production mainline or the latest stable release.
Role: The “anchor” and “shared foundation” that supplies unchanged services to other environments.
Characteristics: Complete service coverage, unified versions, controlled changes, long-term availability.
Analogy: Like a city’s main roads and public infrastructure—stable and shared by all branches.

2.2 最小集环境(Minimum-Set Environment)

  • 定义:仅包含当前任务所需的最少服务子集的隔离环境
  • 定位:面向特定需求、特性分支或缺陷修复的轻量工作空间
  • 特征:服务精简、按需创建、可快速销毁、与基准环境协同
  • 别名:子环境、特性环境、项目环境、沙箱环境
  • 类比:像施工围挡内的局部改造区——只动必要部分,其余沿用主干设施

Definition: An isolated environment containing only the minimum subset of services required for the current task.
Role: A lightweight workspace for a specific feature, branch, or bug fix.
Also known as: Sub-environment, feature environment, project environment, or sandbox.

2.3 二者关系 | Relationship

中文要点:

  • 最小集环境中的服务,是基准环境服务集合的子集
  • 请求通过流量路由(如灰度标、Header、Service Mesh)在两类环境间调度
  • 变更服务在最小集环境中验证,未变更服务由基准环境承接

English: Services in the minimum-set environment are a subset of those in the baseline. Requests are routed between the two via traffic routing (e.g., canary tags, headers, Service Mesh). Changed services are validated in the minimum-set environment; unchanged services are served by the baseline.

1
2
3
4
5
客户端请求 → 入口网关 / Mesh Sidecar
→ 解析路由标识(如 x-env-tag: feature-123)
→ 变更服务 → 最小集环境实例
→ 未变更服务 → 基准环境实例
→ 链路追踪串联跨环境调用

三、设计思想 | Design Philosophy

3.1 分层复用,而非重复建设 | Layered Reuse, Not Duplication

中文:核心思想是“共享稳定、隔离变更”。全量服务维护成本高,但大多数开发任务只改动链路中的少数服务。基准环境承担”公共部分”,最小集环境只承载”差异部分”,避免为每个需求复制整套系统。

English: The core idea is “share what is stable, isolate what changes.” The baseline carries the shared stable portion; the minimum-set environment holds only the delta.

3.2 以稳定为基线,以最小为切口 | Stability as Baseline, Minimality as Entry Point

中文:基准环境强调可预期性与一致性——它是比较、回归、联调的参照系。最小集环境强调敏捷与专注——只暴露与当前任务相关的复杂度,降低认知负担和故障面。

English: The baseline emphasizes predictability and consistency. The minimum-set environment emphasizes agility and focus—reducing cognitive load and blast radius.

3.3 控制变更边界 | Controlled Change Boundaries

中文:基准环境通常禁止直接部署开发中特性,仅允许经过流程验证的主干/稳定版本自动同步。最小集环境则允许任意实验、破坏性测试,不影响他人与公共底座。

English: The baseline prohibits direct deployment of in-development features. The minimum-set environment permits free experimentation and destructive testing without impacting others.

3.4 流量驱动的环境编排 | Traffic-Driven Environment Orchestration

**中文:**环境协同的关键不在”部署了多少套”,而在”请求如何被正确路由“。通过灰度标识、链路追踪(Tracing)、服务网格(Service Mesh)等机制,使一次调用在基准与最小集之间无缝衔接。

English: Effective coordination depends on how requests are routed correctly via canary tags, distributed tracing, and Service Mesh.

四、意义与价值 | Significance and Value

价值维度 基准环境 最小集环境
成本 集群内通常只需一套全量环境 按需创建,资源占用远低于全量复制
效率 减少重复搭建与配置工作 分钟级创建/销毁,加速开发联调
质量 提供稳定参照,利于回归与对比 隔离变更,避免”互相踩环境”
协作 多团队共享同一稳定底座 每人/每需求独立工作区,并行不干扰
风险 与生产版本对齐,降低环境漂移 限制变更范围,缩小故障影响面

五、典型应用场景 | Typical Use Cases

  1. 微服务开发联调:在最小集环境部署 1~2 个变更服务,其余依赖由基准环境提供,通过路由标识完成端到端联调。
    Microservice dev & integration: deploy changed services in minimum-set; baseline supplies the rest.
  2. 特性分支验证:每个特性分支对应一个最小集环境,基准环境保持主干最新稳定态作为对照基线。
    Feature branch validation: one minimum-set per branch; baseline stays on stable mainline.
  3. 缺陷复现与修复:针对特定 Bug 创建最小集环境,在隔离条件下复现、修复、验证。
    Bug reproduction & fix: isolated minimum-set for targeted debugging.
  4. 性能与兼容性基线测试:基准环境作为性能基线和兼容性参照,与最小集环境中的新版本对比指标。
    Performance & compatibility testing against baseline reference.
  5. CI/CD 与预发布:流水线在最小集环境做快速冒烟测试,基准环境提供稳定依赖注入。
    CI/CD smoke tests in minimum-set; baseline supplies stable dependencies.

六、优缺点分析 | Pros and Cons

6.1 基准环境 | Baseline Environment

优点 ✅ 缺点 ❌
服务完整,联调链路可达 维护成本高,需专人或平台保障
版本稳定,结果可复现 与生产同步有延迟时,存在环境漂移
多团队共享,资源利用率高 单点依赖:基准故障影响所有子环境
适合作为性能/兼容性参照 全量部署耗时较长,更新需流程约束

6.2 最小集环境 | Minimum-Set Environment

优点 ✅ 缺点 ❌
资源占用少,创建销毁快 依赖基准环境,基准不可用时无法独立工作
隔离性好,互不干扰 路由与流量标识配置复杂,学习成本较高
支持并行开发,提升吞吐 若子集选取不当,可能遗漏隐性依赖
允许破坏性实验,风险可控 跨环境调用链路调试难度高于单体环境

6.3 组合模式的权衡 | Trade-offs

  • 成本 vs 仿真度:最小集环境仿真度略低于全量复制,但多数联调场景可接受
  • 复杂度 vs 收益:需投入路由、Mesh、环境平台能力,规模化后收益显著
  • 稳定性 vs 敏捷性:基准偏稳定,最小集偏敏捷,二者分工明确
  • 适用规模:微服务数量较多、联调频繁时价值最大;单体或少量服务时可能过度设计

七、落地实践要点 | Implementation Essentials

7.1 基准环境建设

  1. 版本策略:仅部署主干/稳定版本,禁止特性分支直接部署
  2. 自动同步:生产或主干发布完成后,自动触发基准环境更新
  3. 可观测性:完善监控、日志、链路追踪,保障底座可诊断
  4. 高可用:基准环境故障会级联影响子环境,需保障 SLA

7.2 最小集环境建设

  1. 一键创建:提供模板化创建能力,自动完成路由、配置、域名等
  2. 服务子集选择:支持按调用链、依赖分析推荐最小服务集
  3. 生命周期管理:闲置自动回收,控制资源浪费
  4. 流量标识规范:统一灰度标、Header 约定,避免路由混乱

八、与其他环境概念对比 | Comparison

环境类型 服务范围 稳定性 典型用途
生产环境 全量 最高 对外提供服务
预发/Staging 全量 发布前最终验证
基准环境 全量(稳定版) 公共底座、联调依赖
最小集环境 子集(变更服务) 中(按需) 开发、自测、特性验证
本地开发环境 极少 个人编码调试

九、总结 | Summary

**中文:*基准环境是稳定、完整、可复用的环境基线,解决的是”全量服务从哪来、如何保持稳定”的问题;最小集环境是轻量、隔离、按需的环境切片,解决的是”如何低成本、高效率地完成变更验证”的问题。二者结合,体现了现代软件交付中*”共享稳定底座 + 隔离变更验证”**的核心思想。

English: The Baseline Environment is a stable, complete, reusable foundation—it answers where full stable services come from and how they stay reliable. The Minimum-Set Environment is a lightweight, isolated, on-demand slice—it answers how to validate changes cheaply and quickly. Together they embody “shared stable foundation + isolated change validation” in modern software delivery.

本文系统介绍 LLM Wiki 的核心思想、意义、应用场景与优缺点,采用中英文对照形式,便于理解与分享。

This article introduces the core philosophy, significance, application scenarios, and pros & cons of LLM Wiki in a bilingual Chinese–English format.


一、什么是 LLM Wiki? | What Is LLM Wiki?

中文:LLM Wiki 并非某一款固定产品,而是由 AI 研究者 Andrej Karpathy(OpenAI 联合创始人、前特斯拉 AI 总监)提出的一种个人知识库构建范式。其核心思想是:不要每次提问都让 LLM 重新阅读原始文档,而是让 LLM 一次性将资料「编译」成结构化的 Wiki,并持续维护更新。与传统 RAG 不同,LLM Wiki 把知识当作可累积、可演化的持久化产物

English: LLM Wiki is not a single fixed product. It is a personal knowledge-base pattern proposed by Andrej Karpathy. Instead of having the LLM re-read raw documents every time you ask a question, compile them once into a structured wiki and keep it updated forever. Knowledge is a persistent, compounding artifact—not a one-off answer assembled at query time.

二、核心思想 | Core Philosophy

2.1 从「检索」到「编译」 | From Retrieval to Compilation

中文:传统 RAG 每次问答都从零开始检索片段;LLM Wiki 采用 Compile(编译) 思路——将原始资料放入 raw/,由 LLM 生成摘要页、概念页、实体页与交叉链接;新资料加入时增量更新;查询时在 Wiki 中检索、交叉验证、综合作答。

English: Traditional RAG retrieves chunks on every query. LLM Wiki follows a Compile approach: drop materials into raw/, let the LLM generate summaries, concept pages, entity pages, and cross-links; update incrementally when new material arrives; at query time, search, cross-validate, and synthesize across the wiki.

2.2 三层架构 | Three-Layer Architecture

层级 / Layer名称 / Name职责 / Responsibility
Layer 1Raw(原料库)不可篡改的原始文档,地面真相 / Immutable originals—the ground truth
Layer 2Wiki(维基库)LLM 维护的 Markdown:实体页、概念页、索引、日志 / LLM-owned Markdown pages
Layer 3Schema(配置层)CLAUDE.md / AGENTS.md 规定结构与工作流 / Config defining structure and workflows

中文:你负责投喂原料和提出问题;LLM 负责写作、链接、修订、查错。

English: You feed raw material and ask questions; the LLM writes, links, revises, and flags errors.

2.3 三大核心操作 | Three Core Operations

操作 / Operation说明 / Description
Ingest(摄入)新文档入 raw/,LLM 写摘要、更新相关页、建链接、标矛盾 / Add to raw/, summarize, update pages, cross-link, flag contradictions
Query(查询)向 Wiki 提问,LLM 检索页面、综合多源、给出带引用答案 / Search pages, synthesize, return cited answers
Lint(巡检)检查矛盾、过时内容、断链,自动修复或标记 / Audit contradictions, stale content, broken links

三、意义与价值 | Significance and Value

  1. 知识复利 / Knowledge compounding:Wiki 越增长,交叉链接越密,综合回答质量越高。
  2. 降低认知负担 / Lower cognitive load:不必记住每篇文档;问复杂关联问题,LLM 在 Wiki 中串联多源作答。
  3. 可追溯可审计 / Traceable:答案基于 Markdown 页面,可点击查看引用,比黑盒 RAG 更透明。
  4. 人机协作 / Human–AI collaboration:人策展与提问,AI 整理与维护,适合长期深度研究。
  5. 格式灵活 / Flexible output:可导出幻灯片、图表、HTML,并回灌 Wiki 形成正向循环。

Karpathy 的实践:某研究主题 Wiki 已积累 100+ 篇文章、约 40 万字,基本由 LLM 自动维护。

四、应用场景 | Application Scenarios

场景 / Scenario典型用法 / Typical Use
学术研究 / Academic research论文、预印本 → 概念 Wiki → 写综述、找矛盾、生成幻灯片
技术学习 / Technical learning文档、教程、代码 → 架构与 API 概念页 → 快速定位、对比方案
读书笔记 / Reading notes书籍摘录 → 人物/主题/观点页 → 跨书综合理解
项目知识管理 / Project knowledge需求、会议、设计 → 实体与决策 Wiki → onboarding、决策追溯
内容创作 / Content creation素材库 → 主题 Wiki → 文章、播客提纲、幻灯片
个人反思 / Personal journal日志、想法 → 主题与模式页 → 长期自我认知

适用边界:资料量有限(通常数百篇以内)、需要综合与连接的场景。不适合超大规模、实时性极强的企业级知识库。

Sweet spot: bounded corpora where synthesis matters more than one-shot lookup.

五、优缺点分析 | Pros and Cons

5.1 优点 | Advantages

  • 持久化积累:知识结构化沉淀,非一次性问答 / Persistent accumulation
  • 综合能力强:多源交叉验证,适合「连接多篇资料」类问题 / Strong synthesis
  • 增量更新简单:一句「归档进 wiki」即可 / Simple incremental updates
  • 无需复杂 RAG 栈:长上下文 + 索引常可替代向量库 / No heavy RAG stack
  • 可观测:Markdown 可读可改,过程透明 / Observable Markdown

5.2 缺点与局限 | Disadvantages

  • 依赖 LLM 质量:编译错误会写入 Wiki,需 Lint 与人工抽查 / LLM quality dependency
  • 上下文窗口限制:超大库需索引与分块策略 / Context window limits
  • 初期投入:Schema 设计与首轮编译需时间 / Upfront investment
  • 非实时:适合异步积累,不适合秒级动态数据 / Not real-time
  • 成本:大量 Ingest/Compile 消耗 Token / Token cost
  • 幻觉风险:综合时可能编造,需引用与校验 / Hallucination risk

六、与传统 RAG 的对比 | LLM Wiki vs. Traditional RAG

维度 / Dimension传统 RAGLLM Wiki
知识形态原始文档 + 向量索引结构化 Markdown Wiki
查询时检索片段 → 生成答案检索 Wiki 页 → 综合答案
更新方式重新索引/嵌入增量更新相关页面
知识沉淀强,Wiki 持续演化
适用问题「某文档里 X 是什么?」「X 和 Y 如何关联?」

七、快速上手建议 | Quick Start

  1. raw/wiki/ 目录 / Create raw/ and wiki/ directories
  2. CLAUDE.md:结构、约定、Ingest/Query/Lint 流程 / Write schema config
  3. 用 Obsidian 打开 wiki/ 便于可视化 / Visualize with Obsidian
  4. 指令:「阅读 raw/ 全部文件,按 CLAUDE.mdwiki/ 生成维基」
  5. 持续 Ingest → Query → Lint,形成闭环 / Run the loop

开源实现:nashsu/llm_wiki(基于 Karpathy 范式的桌面应用)。

方法论原文:Karpathy's llm-wiki.md

八、总结 | Summary

中文:LLM Wiki 是一种用 LLM 编译并维护个人知识库的方法论。它适合深度研究、长期学习、项目沉淀等需要综合与连接的场景,是对传统 RAG「每次从头检索」思路的有益补充。成功关键在于清晰的 Schema、高质量的原料,以及定期的 Lint 与人工校验。

English: LLM Wiki is a methodology for compiling and maintaining a personal knowledge base with LLMs. It fits deep research, long-term learning, and project documentation where synthesis and connection matter. Success depends on a clear schema, high-quality sources, and regular Lint plus human verification.

0%