# https://github.com/neo4j-labs/agent-memory 项目说明书

生成时间：2026-06-17 05:03:30 UTC

## 目录

- [System Overview & Graph Architecture](#page-1)
- [Backends (NAMS vs Bolt), Configuration & SDK Setup](#page-2)
- [Framework Integrations, MCP Server & Reference Apps](#page-3)
- [Memory Operations, Extraction Pipeline & Roadmap Topics](#page-4)

<a id='page-1'></a>

## System Overview & Graph Architecture

### 相关页面

相关主题：[Backends (NAMS vs Bolt), Configuration & SDK Setup](#page-2), [Memory Operations, Extraction Pipeline & Roadmap Topics](#page-4)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/neo4j-labs/agent-memory/blob/main/README.md)
- [examples/README.md](https://github.com/neo4j-labs/agent-memory/blob/main/examples/README.md)
- [src/neo4j_agent_memory/nams/ontology.py](https://github.com/neo4j-labs/agent-memory/blob/main/src/neo4j_agent_memory/nams/ontology.py)
- [typescript/src/ontology/index.ts](https://github.com/neo4j-labs/agent-memory/blob/main/typescript/src/ontology/index.ts)
- [typescript/src/reasoning/index.ts](https://github.com/neo4j-labs/agent-memory/blob/main/typescript/src/reasoning/index.ts)
- [typescript/src/index.ts](https://github.com/neo4j-labs/agent-memory/blob/main/typescript/src/index.ts)
- [examples/full-stack-chat-agent/README.md](https://github.com/neo4j-labs/agent-memory/blob/main/examples/full-stack-chat-agent/README.md)
- [examples/microsoft_agent_retail_assistant/README.md](https://github.com/neo4j-labs/agent-memory/blob/main/examples/microsoft_agent_retail_assistant/README.md)
- [src/neo4j_agent_memory/integrations/openai_agents/memory.py](https://github.com/neo4j-labs/agent-memory/blob/main/src/neo4j_agent_memory/integrations/openai_agents/memory.py)
</details>

# System Overview & Graph Architecture

## 系统定位与设计目标

`neo4j-agent-memory` 是一个面向 AI 智能体的图原生（graph-native）记忆系统，其核心目标是把"对话历史"、"实体知识"与"推理轨迹"统一落到一张 Neo4j 图中，使智能体既能跨会话召回上下文，也能从自身过往的推理中学习 资料来源：[README.md:1-18]()。系统同时提供 Python 与 TypeScript 双端 SDK，并内建与 PydanticAI、LangChain、Google ADK、Strands、CrewAI、OpenAI Agents 等框架的适配层 资料来源：[README.md:14-20]()。所有写入操作均为 `async`，调用方需以 `async with MemoryClient(settings) as client:` 或显式 `await client.connect()` 管理生命周期 资料来源：[examples/README.md:18-22]()。

## 三层记忆架构

系统将记忆划分为三个互补的层级，统称 **short-term / long-term / reasoning**：

| 层级 | 核心职责 | 典型节点 / 关系 | 入口访问器 |
|------|----------|-----------------|-----------|
| Short-term | 会话级消息历史与语义召回 | `(:Message)-[:IN_SESSION]->(:Session)` | `client.short_term` |
| Long-term | POLE+O 实体、偏好、关系 | `(:Person\|:Organization\|:Location\|:Event\|:Object)` | `client.long_term` |
| Reasoning | 智能体步骤与工具调用审计 | `(:ReasoningTrace)-[:HAS_STEP]->(:ReasoningStep)-[:TOUCHED]->(:Entity)` | `client.reasoning` |

这三层在 OpenAI Agents 适配器中通过 `get_context()` 被统一合并为一条系统提示词可见的上下文字符串 资料来源：[src/neo4j_agent_memory/integrations/openai_agents/memory.py:50-72]()；在零售示例中则显式呈现为"对话历史 + 商品实体 + 过往购物推理轨迹"的复合召回 资料来源：[examples/microsoft_agent_retail_assistant/README.md:120-140]()。社区已就此提出"为 LangGraph 提供自动记忆中间件"的需求（issue #49），用以替代由智能体显式调用 memory 的模式，目前尚未合入 资料来源：[README.md 社区上下文 #49]()。

## 图模型与 POLE+O 本体

所有 long-term 实体都映射到 POLE+O 五类顶层标签（`PERSON` / `ORGANIZATION` / `LOCATION` / `EVENT` / `OBJECT`），并由 `examples/domain-schemas/` 下的工厂类（新闻、学术、商业、娱乐、医疗、法律等）按域扩展 subtype 与关系集合 资料来源：[examples/domain-schemas/README.md:25-70]()。实体写入时会附带嵌入向量与去重元组：`await client.long_term.add_entity(...)` 自 v0.1.1 起返回 `(entity, dedup_result)`，调用方需用 `_, _ = await ...` 显式解包 资料来源：[examples/README.md:24-27]()。

在 v0.4.0 引入的 NAMS（Neo4j Agent Memory Service）后端上，图模式不再是写死的 Cypher，而是由 *ontology*（一个版本化、带 `validation_mode` 的类型化 schema）驱动：每个 `EntityTypeDef` 显式声明 `poleType`，每个 `PropertyDef` 携带 `type / required / unique / enum` 约束，关系类型也由 `RelationshipDef` 类型化 资料来源：[src/neo4j_agent_memory/nams/ontology.py:60-110]()。同一组模型在 TypeScript SDK 中以 `OntologyClient` 暴露，并通过 `/ontologies` REST 端点完成克隆、激活、版本化与结构化 diff 资料来源：[typescript/src/ontology/index.ts:1-90]()。

```mermaid
flowchart LR
    subgraph Client["MemoryClient (Python / TS)"]
        ST[Short-Term]
        LT[Long-Term]
        RS[Reasoning]
    end
    ST -->|messages| S[(Session / Message)]
    LT -->|entities & relations| K[(Entity · POLE+O)]
    RS -->|steps & tool calls| T[(ReasoningTrace)]
    K -. :TOUCHED .-> T
    S -. sem search .-> K
    T -. provenance .-> K
```

## 托管后端 NAMS 与自托管切换

v0.4.0 把 `MemorySettings(backend="nams", ...)` 作为**纯加性**选项引入，调用方只需在配置阶段选择本地 bolt 直连 Neo4j 还是托管 REST 服务，面向 `MemoryClient` 的业务代码无需改动 资料来源：[README.md 社区上下文 v0.4.0]()。NAMS 端点以 `*_ontology` 子路径对外，并显式声明"这些路由不在 staging OpenAPI 中，是通过实测验证的"——这意味着客户端代码（含 TS SDK）必须把这些路径当作受支持的隐式契约 资料来源：[typescript/src/ontology/index.ts:10-20]()。TypeScript 端通过 `RestTransport` 的 `snakeBody` 标志把 ontology 请求体保持为 snake_case JSON 以匹配服务端 资料来源：[typescript/src/ontology/index.ts:130-160]()。

## 审计追溯与推理可解释性

系统的设计亮点之一是 `:TOUCHED` 审计边——每次推理步骤都会显式指向被它"触碰"过的实体，从而既能解释"该结论来自哪段历史"，也能支撑实体级 provenance 视图 资料来源：[README.md:6-12]()；`ReasoningMemory` 进一步把 `explain` 行为作为"白银层"包装方法，在 hosted-native 模式下则提供更扁平的"按 conversation 取 step"接口 资料来源：[typescript/src/reasoning/index.ts:1-50]()。社区同时讨论了**记忆衰减**（issue #42：在检索阶段加入时间感知 re-ranker）与**多租户可见性**（issue #13：把程序性记忆标为组织内公开），这两项尚未合入，但与当前的 POLE+O 图模型天然兼容——衰减可作为长期检索器的后处理步骤，公开/私有则可作为 `Entity` 上的访问控制属性 资料来源：[README.md 社区上下文 #42 #13]()。

## 常见使用模式

- **异步一次性上下文召回**：`await client.get_context(query=..., session_id=..., include_short_term=True, include_long_term=True, include_reasoning=True)` 资料来源：[src/neo4j_agent_memory/integrations/openai_agents/memory.py:55-72]()。
- **批量转写导入**：通过 `client.buffered.submit(...)` 实现 fire-and-forget 写入，适合 Lenny Podcast 类的转写灌入（issue #11 也提出过 CLI 化批处理需求） 资料来源：[README.md:8-10]()。
- **采纳已有图**：生产环境已有 Neo4j 图时，使用 `client.schema.adopt_existing_graph(...)` 在不破坏既有数据的前提下叠加记忆层 资料来源：[README.md:8-10]()。

## See Also

- [MCP Tools Reference](https://neo4j.com/labs/agent-memory/reference/mcp-tools) — 16 工具的 MCP server 详细说明
- [Provider Migration Guide](https://neo4j.com/labs/agent-memory/how-to/migrate-to-providers.html) — OpenAI / Anthropic / Bedrock / Vertex AI / LiteLLM 适配说明
- [Examples Index](https://github.com/neo4j-labs/agent-memory/blob/main/examples/README.md) — 旗舰 demo 与单功能小例的入口
- [Community Issue #49](https://github.com/neo4j-labs/agent-memory/issues/49) — LangGraph 中间件与自动记忆存取
- [Community Issue #42](https://github.com/neo4j-labs/agent-memory/issues/42) — 检索阶段记忆衰减与时间重排

---

<a id='page-2'></a>

## Backends (NAMS vs Bolt), Configuration & SDK Setup

### 相关页面

相关主题：[System Overview & Graph Architecture](#page-1), [Framework Integrations, MCP Server & Reference Apps](#page-3)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/neo4j_agent_memory/config/settings.py](https://github.com/neo4j-labs/agent-memory/blob/main/src/neo4j_agent_memory/config/settings.py)
- [src/neo4j_agent_memory/nams/client.py](https://github.com/neo4j-labs/agent-memory/blob/main/src/neo4j_agent_memory/nams/client.py)
- [src/neo4j_agent_memory/nams/transport.py](https://github.com/neo4j-labs/agent-memory/blob/main/src/neo4j_agent_memory/nams/transport.py)
- [src/neo4j_agent_memory/nams/auth.py](https://github.com/neo4j-labs/agent-memory/blob/main/src/neo4j_agent_memory/nams/auth.py)
- [src/neo4j_agent_memory/nams/__init__.py](https://github.com/neo4j-labs/agent-memory/blob/main/src/neo4j_agent_memory/nams/__init__.py)
- [src/neo4j_agent_memory/nams/ontology.py](https://github.com/neo4j-labs/agent-memory/blob/main/src/neo4j_agent_memory/nams/ontology.py)
- [src/neo4j_agent_memory/nams/_serialization.py](https://github.com/neo4j-labs/agent-memory/blob/main/src/neo4j_agent_memory/nams/_serialization.py)
- [src/neo4j_agent_memory/graph/client.py](https://github.com/neo4j-labs/agent-memory/blob/main/src/neo4j_agent_memory/graph/client.py)
- [src/neo4j_agent_memory/llm/factory.py](https://github.com/neo4j-labs/agent-memory/blob/main/src/neo4j_agent_memory/llm/factory.py)
- [README.md](https://github.com/neo4j-labs/agent-memory/blob/main/README.md)
- [examples/README.md](https://github.com/neo4j-labs/agent-memory/blob/main/examples/README.md)
</details>

# 后端（NAMS vs Bolt）、配置与 SDK 初始化

## 概述

`neo4j-agent-memory` 通过统一的 `MemoryClient` 抽象，向应用层暴露短期会话、长期实体 / 偏好 / 事实、推理轨迹等能力。底层实现可由 `MemorySettings(backend=...)` 在两种后端之间切换：

- **Bolt 后端**：客户端直接通过 Bolt 协议连到本地或自管的 Neo4j 数据库，所有读写下沉到自有集群。
- **NAMS 后端（Neo4j Agent Memory Service）**：客户端把 `MemoryClient` 的所有调用作为 HTTP 请求，转发给 Neo4j Labs 托管的 REST 服务。

两种后端共享同一份应用代码。`backend="nams"` 在 v0.4.0 中作为可选项加入；现有基于 v0.3.x 编写、跑在 Bolt 上的代码无需修改即可继续运行。该变化被官方描述为“完全叠加”（purely additive）。资料来源：[README.md]()

## 架构总览

```mermaid
flowchart LR
    App[Agent / 应用] --> MC[MemoryClient]
    MC -->|backend=bolt| BC[graph/client.py<br/>BoltDriver]
    BC --> Neo4j[(自管 Neo4j)]
    MC -->|backend=nams| NC[nams/client.py<br/>NamsClient]
    NC --> HT[nams/transport.py<br/>HttpTransport]
    HT -->|HTTPS + Bearer| NAMS[(NAMS 托管服务)]
    MS[MemorySettings] -.配置.-> MC
    Auth[nams/auth.py] -.API Key.-> NC
```

## Bolt 后端（自管 Neo4j）

Bolt 后端是项目的默认形态。`MemoryClient` 在该模式下通过 `graph/client.py` 中的驱动直接与 Neo4j 通信：写入直接落到图数据库，查询由客户端拼装 Cypher 再下发。Pydantic 风格的领域对象在客户端与图节点之间互转。该模式适合以下场景：

- 数据需要完全驻留在自有环境，满足合规与数据主权要求；
- 团队已维护 Neo4j 集群，希望复用既有的运维、备份与监控链路；
- 需在客户端层面编写自定义 Cypher、扩展 POLE+O 之外的实体类型或推理节点。

资料来源：[README.md]()、[src/neo4j_agent_memory/graph/client.py]()

## NAMS 后端（托管 REST 服务）

NAMS 后端由 `src/neo4j_agent_memory/nams/` 子包实现。`NamsClient` 通过 `HttpTransport` 把 Pydantic 模型序列化为 JSON 提交给托管服务。关键约束与约定：

- 端点并未完全公开在 OpenAPI 中，部分路由（如 `*/ontologies`）的负载与响应需按经验实现，并通过 `snakeBody` 透传 snake_case 字段。资料来源：[src/neo4j_agent_memory/nams/ontology.py]()
- 身份由 `nams/auth.py` 中的 `MEMORY_API_KEY`（形如 `nams_xxxxxxxxxxxxxxxx`）承载，调用时通过 `Authorization: Bearer ...` 头发送。资料来源：[src/neo4j_agent_memory/nams/auth.py]()、[[examples/README.md](https://github.com/neo4j-labs/agent-memory/blob/main/examples/README.md)]()
- JSON 编解码统一通过 `_serialization.py` 处理：`UUID → str`、`datetime → ISO 8601`、`None` 字段从出站负载中剔除，由服务端默认值兜底。资料来源：[src/neo4j_agent_memory/nams/_serialization.py]()
- 顶层导出集中在 `nams/__init__.py`，包括 `NamsClient`、`NamsOntology`、`OntologyDocument`、`MigrationJob` 等 v0.5 阶段符号。资料来源：[src/neo4j_agent_memory/nams/__init__.py]()

## 配置与 SDK 初始化

`MemorySettings` 是唯一的配置入口。`backend` 字段决定运行时走 Bolt 还是 NAMS；`embedding` 与 `llm` 字段控制抽取向量与补全模型，二者既支持简写 provider 字符串（如 `"anthropic/claude-3-5-sonnet-latest"`、`"BAAI/bge-small-en-v1.5"`），也支持显式 `Provider` 实例；原生适配器覆盖 OpenAI、Anthropic、Bedrock、Vertex AI、sentence-transformers，其余 100+ 提供商由 LiteLLM 兜底。资料来源：[README.md]()、[src/neo4j_agent_memory/llm/factory.py]()

NAMS 模式下，凭证与端点通常通过环境变量注入：

```bash
export MEMORY_API_KEY=nams_xxxxxxxxxxxxxxxx
export MEMORY_ENDPOINT=https://nams.staging.neo4j.io
```

随后在脚本中以异步上下文管理器实例化客户端：

```python
from neo4j_agent_memory import MemoryClient, MemorySettings

settings = MemorySettings(backend="nams", api_key=..., endpoint=...)
async with MemoryClient(settings) as client:
    entity, dedup = await client.long_term.add_entity(...)
```

`add_entity` 等长期记忆调用自 v0.1.1 起返回 `(entity, dedup_result)` 元组，调用方需要解包；其余方法遵循相同的 `await` 异步约定。资料来源：[examples/README.md]()

## 选型建议与社区关注点

Bolt 后端由用户自管 Neo4j，鉴权依赖数据库账号密码，水平扩展受限于自建集群规模；NAMS 后端由服务商负责弹性伸缩，鉴权统一收敛到 `MEMORY_API_KEY`。社区中关于自动记忆读写中间件（issue #49，LangGraph Middleware）、记忆衰减重排序（issue #42）、多租户 / 组织级安全（issue #13）的讨论，是后端无关的应用层话题，但它们在 NAMS 模式下更接近一等公民能力，应结合所选后端评估落地路径。此外，`OPENAI_API_KEY` 等模型凭证在两种后端下都需要在启动前就绪，缺失时建议显式 fail-fast 而不是静默回退。资料来源：[README.md]()、[examples/README.md]()

## See Also

- [Use NAMS 使用指南](https://neo4j.com/labs/agent-memory/how-to/use-nams)
- [Bolt vs NAMS 后端选型说明](https://neo4j.com/labs/agent-memory/explanation/backends)
- [Provider 迁移指南](https://neo4j.com/labs/agent-memory/how-to/migrate-to-providers.html)
- [examples/README.md](https://github.com/neo4j-labs/agent-memory/blob/main/examples/README.md)

---

<a id='page-3'></a>

## Framework Integrations, MCP Server & Reference Apps

### 相关页面

相关主题：[Backends (NAMS vs Bolt), Configuration & SDK Setup](#page-2), [Memory Operations, Extraction Pipeline & Roadmap Topics](#page-4)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/neo4j-labs/agent-memory/blob/main/README.md)
- [examples/README.md](https://github.com/neo4j-labs/agent-memory/blob/main/examples/README.md)
- [examples/financial-services-advisor/README.md](https://github.com/neo4j-labs/agent-memory/blob/main/examples/financial-services-advisor/README.md)
- [examples/microsoft_agent_retail_assistant/README.md](https://github.com/neo4j-labs/agent-memory/blob/main/examples/microsoft_agent_retail_assistant/README.md)
- [examples/domain-schemas/README.md](https://github.com/neo4j-labs/agent-memory/blob/main/examples/domain-schemas/README.md)
- [typescript/src/index.ts](https://github.com/neo4j-labs/agent-memory/blob/main/typescript/src/index.ts)
- [typescript/src/integrations/langchain.ts](https://github.com/neo4j-labs/agent-memory/blob/main/typescript/src/integrations/langchain.ts)
- [typescript/examples/mcp/package.json](https://github.com/neo4j-labs/agent-memory/blob/main/typescript/examples/mcp/package.json)
- [src/neo4j_agent_memory/integrations/microsoft_agent/memory.py](https://github.com/neo4j-labs/agent-memory/blob/main/src/neo4j_agent_memory/integrations/microsoft_agent/memory.py)
- [src/neo4j_agent_memory/integrations/openai_agents/memory.py](https://github.com/neo4j-labs/agent-memory/blob/main/src/neo4j_agent_memory/integrations/openai_agents/memory.py)
</details>

# Framework Integrations, MCP Server & Reference Apps

## 集成总览

`agent-memory` 提供三种"接入路径"，让不同技术栈的代理（agent）应用都能复用其三层记忆（短期会话、长期实体、推理轨迹）能力：（1）面向通用 LLM 代理的 **MCP Server**；（2）面向主流代理框架的 **语言绑定**；（3）面向真实业务场景的 **参考应用**。

仓库的 TypeScript 入口将所有子客户端统一导出，包含 `ShortTermMemory`、`LongTermMemory`、`ReasoningMemory`、`QueryConsole`、`AuthClient` 与 `OntologyClient` 等，开发者既能走高级 `MemoryClient` 门面，也能直接构造某个子模块做精细化调用。资料来源：[typescript/src/index.ts:1-50]()

Python 端 `neo4j_agent_memory.nams` 包在 v0.5 之后扩展了 NAMS 后端支持，并暴露 `NamsOntology` 等类型化模型，确保两侧语言的 API 形态在托管与本地 bolt 模式下保持一致。资料来源：[src/neo4j_agent_memory/nams/\_\_init\_\_.py:1-30]()

## MCP Server

README 明确指出项目随附一个 MCP server，提供 **16 个工具**，覆盖会话历史、实体详情、图谱导出、关系创建、推理轨迹、观察值（observation）以及只读 Cypher 等能力。资料来源：[README.md:1-15]()

TypeScript 端的 MCP 样例独立打包，使用官方 `@modelcontextprotocol/sdk` 1.x，并以 `file:../..` 引用本地构建产物，开发者可在 `typescript/examples/mcp/` 下用 `pnpm start` 启动该服务端。资料来源：[typescript/examples/mcp/package.json:1-13]()

社区 Issue #49 提议为 LangGraph 增加 Middleware，把记忆读写从"由 agent 显式调用"改为"在 LLM 调用前后自动触发"，与 MCP server 的工具化暴露形成互补——MCP 提供被动工具接口，而 Middleware 提供主动拦截层。资料来源：[README.md:1-15]()（结合社区讨论 #49）

## 框架集成

### LangChain（JS）

`Neo4jChatMessageHistory` 将 `MemoryClient` 适配为 LangChain JS 的 `BaseChatMessageHistory` 形态，按 `human/ai/system` 与 `user/assistant/system` 的双向映射把消息写入短期记忆。资料来源：[typescript/src/integrations/langchain.ts:1-60]()

Python 端的 LangChain 集成（`integrations/langchain/memory.py` 与 `retriever.py`）则提供 `Neo4jChatMessageHistory` 与 `Neo4jEntityRetriever`，常用于把长期实体作为 retriever 嵌入 RAG 链路。

### Microsoft Agent Framework

`Neo4jMicrosoftMemory` 把 `BaseContextProvider` 与 `BaseHistoryProvider` 合并为一个统一接口，可同时挂到 `chat_client.as_agent(context_providers=[...])` 上，让 agent 自动获得上下文注入与历史持久化。资料来源：[src/neo4j_agent_memory/integrations/microsoft_agent/memory.py:1-90]()

### OpenAI Agents SDK

OpenAI Agents 适配器在保存消息时支持 `extract_entities` 与 `generate_embedding` 开关，并把工具调用与 `tool_call_id` 写入元数据，使代理在多步调用中能够正确回写消息。资料来源：[src/neo4j_agent_memory/integrations/openai_agents/memory.py:1-90]()

README 顶部列出的官方支持框架还包括 **Pydantic AI、Google ADK、Strands、CrewAI**，社区 Issue #49 中的 LangGraph Middleware 是目前最受关注的待补齐适配。资料来源：[README.md:1-15]()

## 参考应用

`examples/` 目录下沉淀了三类应用：旗舰演示、领域 schema 与多代理金融合规。资料来源：[examples/README.md:1-40]()

| 类别 | 示例 | 关键能力 |
|------|------|----------|
| 旗舰演示 | `lennys-memory/` | 299 期播客知识图谱、Wikipedia 富化、地理可视化、NVL 图谱视图（对应 Issue #7 关注的 `OPENAI_API_KEY` 必填项） |
| 多代理金融合规 | `financial-services-advisor/{aws,google-cloud}/` | KYC/AML/关系/合规四专家 + Supervisor，AWS Strands + Bedrock 与 Google ADK + Gemini 两种实现 |
| 零售助理 | `microsoft_agent_retail_assistant/` | GDS 算法、实体去重、上下文提供者；前端 Next.js 14 + 后端 FastAPI SSE 流式输出 |

领域 schema（`domain-schemas/`）则给出 podcast、新闻、学术、商业、娱乐、医疗、法律等 7 套工厂化 POLE+O 模板，开发者可按业务直接套用并按需裁剪。资料来源：[examples/domain-schemas/README.md:1-30]()

## 社区待办与边界

- **#11 Add CLI**：当前缺少批量导入、基准评测、样本加载的官方命令行工具，CLI 相关需求被合并到未来的客户端工具中讨论。
- **#13 Security / Auth**：现有 `AuthClient`（见 [typescript/src/index.ts]()）仅覆盖 API Key/Token 维度，跨用户"公共/私有"记忆作用域（如程序性记忆共享）尚未抽象。
- **#42 记忆衰减**：retriever 尚未提供时间衰减重排器，目前记忆新鲜度依赖向量相似度排序。

## See Also

- 主页：[README.md](https://github.com/neo4j-labs/agent-memory/blob/main/README.md)
- 配置与后端：[MemoryClient 入门（v0.4.0 NAMS）](#)
- 本体系统：[Ontology / NAMS Ontology](#)
- 示例索引：[examples/README.md](https://github.com/neo4j-labs/agent-memory/blob/main/examples/README.md)

---

<a id='page-4'></a>

## Memory Operations, Extraction Pipeline & Roadmap Topics

### 相关页面

相关主题：[System Overview & Graph Architecture](#page-1), [Framework Integrations, MCP Server & Reference Apps](#page-3)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/neo4j-labs/agent-memory/blob/main/README.md)
- [examples/README.md](https://github.com/neo4j-labs/agent-memory/blob/main/examples/README.md)
- [examples/domain-schemas/README.md](https://github.com/neo4j-labs/agent-memory/blob/main/examples/domain-schemas/README.md)
- [examples/full-stack-chat-agent/README.md](https://github.com/neo4j-labs/agent-memory/blob/main/examples/full-stack-chat-agent/README.md)
- [examples/google_cloud_integration/README.md](https://github.com/neo4j-labs/agent-memory/blob/main/examples/google_cloud_integration/README.md)
- [examples/microsoft_agent_retail_assistant/README.md](https://github.com/neo4j-labs/agent-memory/blob/main/examples/microsoft_agent_retail_assistant/README.md)
- [src/neo4j_agent_memory/integrations/openai_agents/memory.py](https://github.com/neo4j-labs/agent-memory/blob/main/src/neo4j_agent_memory/integrations/openai_agents/memory.py)
- [src/neo4j_agent_memory/integrations/microsoft_agent/memory.py](https://github.com/neo4j-labs/agent-memory/blob/main/src/neo4j_agent_memory/integrations/microsoft_agent/memory.py)
- [src/neo4j_agent_memory/nams/ontology.py](https://github.com/neo4j-labs/agent-memory/blob/main/src/neo4j_agent_memory/nams/ontology.py)
- [typescript/src/long-term/index.ts](https://github.com/neo4j-labs/agent-memory/blob/main/typescript/src/long-term/index.ts)
- [typescript/src/reasoning/index.ts](https://github.com/neo4j-labs/agent-memory/blob/main/typescript/src/reasoning/index.ts)
- [typescript/src/ontology/index.ts](https://github.com/neo4j-labs/agent-memory/blob/main/typescript/src/ontology/index.ts)
- [typescript/src/middleware/vercel-ai.ts](https://github.com/neo4j-labs/agent-memory/blob/main/typescript/src/middleware/vercel-ai.ts)
- [typescript/src/integrations/langchain.ts](https://github.com/neo4j-labs/agent-memory/blob/main/typescript/src/integrations/langchain.ts)
</details>

# 记忆操作、提取流水线与路线图主题

## 概述

`neo4j-labs/agent-memory` 是一套以 Neo4j 为长期存储后端的智能体记忆库。它把记忆拆成 **短期（对话历史）**、**长期（实体 / 偏好 / 事实）** 与 **推理（trace / step）** 三层，并提供 **多阶段实体提取流水线**、**后台富集**、**POLE+O 本体** 与 **MCP 工具 / 框架中间件** 集成。项目同时维护 Python 与 TypeScript 双 SDK，从 v0.4.0 起新增 **NAMS（Neo4j Agent Memory Service）** 后端，开发者可在 `MemorySettings(backend="nams" | "bolt")` 之间无侵入切换 [README.md](README.md)。

资料来源：[README.md:1-30]()

## 记忆操作分层

`MemoryClient` 通过三个命名空间暴露 CRUD / 检索能力，社区示例普遍以 `async with MemoryClient(settings) as client:` 模式管理生命周期 [examples/README.md:1-30]()。

| 命名空间 | 典型方法 | 数据形态 | 主要来源 |
|---|---|---|---|
| `client.short_term` | `add_message`、`get_conversation` | `Message` 节点 | [src/.../microsoft_agent/memory.py:1-60]() |
| `client.long_term` | `add_entity`、`search_entities`、`merge_entities`、`get_graph` | `Entity` / `Preference` / `Fact` | [typescript/src/long-term/index.ts:1-60]() |
| `client.reasoning` | `record_step`、`complete_trace`、`get_similar_traces` | `ReasoningTrace` / `AgentStep` | [typescript/src/reasoning/index.ts:1-60]() |

`short_term` 负责把对话消息落图并附带 `tool_calls`、`tool_call_id` 等元数据 [src/.../openai_agents/memory.py:1-60]()。`long_term` 在 TypeScript SDK 中以"桥接方法 + Volume 5 托管原生方法"两层 API 暴露实体反馈、历史追溯、按 ID 合并与图视图 [typescript/src/long-term/index.ts:1-30]()。`reasoning` 命名空间同样提供托管平铺方法（step 直接隶属于 conversation），并附 `explain` / `provenance` 视图用于审计 [typescript/src/reasoning/index.ts:1-20]()。

## 提取流水线

提取阶段是构建长期记忆的核心，仓库在 README 与 `domain-schemas` 示例中均强调 **多阶段 + 可插拔** 设计：先由 spaCy / GLiNER / LLM 进行命名实体识别，再由 GLiREL 完成关系抽取，最后在后台异步执行 Wikipedia / Diffbot 富集 [README.md:1-30]()。

资料来源：[README.md:1-30]()、 [examples/domain-schemas/README.md:1-60]()

本体层采用 **POLE+O**（Person / Organization / Location / Event / Object）字符串标签而非枚举，便于扩展领域子类（`subtype`），示例涵盖 `poleo`（调查分析）、`podcast`、`news`、`scientific`、`business`、`entertainment`、`medical`、`legal` 等域 [examples/domain-schemas/README.md:1-60]()。在 NAMS 后端中，本体被建模为可版本化文档，包含 `EntityTypeDef`、`RelationshipDef`、`PropertyDef`，并支持创建 / 克隆 / 设为主线 / 删除等生命周期操作 [src/.../nams/ontology.py:1-60]()、 [typescript/src/ontology/index.ts:1-60]()。

```mermaid
flowchart LR
  A[原始文本] --> B[阶段1 NER<br/>spaCy / GLiNER / LLM]
  B --> C[阶段2 关系抽取<br/>GLiREL]
  C --> D[POLE+O 实体/关系<br/>入库 Neo4j]
  D --> E[后台富集<br/>Wikipedia / Diffbot]
  E --> F[长期记忆<br/>Entity / Preference / Fact]
```

## 框架集成与中间件

为减少业务侧对"何时调用记忆"的判断成本，仓库提供两类集成：

- **显式适配器**：`Neo4jChatMessageHistory`（LangChain JS）、`Neo4jMicrosoftMemory`（封装 `BaseContextProvider` + `BaseHistoryProvider`，可直接挂到 Microsoft Agent 上）[typescript/src/integrations/langchain.ts:1-40]()、 [src/.../microsoft_agent/memory.py:1-60]()。
- **透明中间件**：`agentMemoryMiddleware(client, { conversationId, userId, includeContext })` 在每次 `generateText` 调用前注入三段式上下文（reflections + observations + recent messages），调用后回写用户输入与助手输出，必要时懒创建 conversation [typescript/src/middleware/vercel-ai.ts:1-40]()。

社区在 issue #49 中提出 **LangGraph Middleware** 的等价需求，希望在 LLM 调用前后自动完成记忆的存取，这与 Vercel AI SDK 中间件的设计思路一致 [README.md:1-30]()。

## 路线图相关议题

结合社区高频议题与已发布能力，记忆库的下一步演进聚焦四个方向：

1. **时间衰减与重排序**：issue #42 建议在检索阶段引入"时间重排序器"，让近期记忆获得更高权重，同时识别并淘汰异常记忆。README 中提到的 GLiREL 关系抽取与缓冲写入可作为前置信号 [README.md:1-30]()。
2. **多租户与安全 / 授权**：issue #13 区分"个人记忆"与"组织级公共记忆"（如程序性 SOP），需配合 `user_identifier=` 多租户作用域与受控的可见性策略 [README.md:1-30]()。
3. **CLI 与批处理工具**：issue #11 提出转录批量入库、跨 schema / 模型基准测试、样例加载等命令入口，目前主要由 `examples/` 下的脚本承担，尚未统一 CLI [examples/README.md:1-30]()。
4. **托管后端持续完善**：v0.4.0 引入的 NAMS REST 后端在配置层是纯增量变更；TypeScript 侧的 `snakeBody` 路由与 `NotSupportedError` 处理仍处于与开放 API 对齐阶段 [typescript/src/ontology/index.ts:1-20]()、 [src/.../nams/ontology.py:1-30]()。

资料来源：[README.md:1-30]()、 [examples/README.md:1-30]()

## 常见失败模式

- **`OPENAI_API_KEY` 缺失导致静默失败**：issue #7 反馈 Lenny Podcast 示例因未设 key 而异常，应在启动期 fail-fast 并显式提示 [examples/README.md:1-30]()。
- **方法签名漂移**：v0.1.1 后 `add_entity` 返回 `(entity, dedup_result)` 元组，旧代码若按单值解包会触发 `ValueError` [examples/README.md:1-30]()。
- **后端能力差异**：NAMS 与 bolt 后端并非完全等价，例如 `client.ontology` 托管端点不在 OpenAPI 规范内，TypeScript SDK 对其启用 `snakeBody` 旁路并对未实现能力抛出 `NotSupportedError` [typescript/src/ontology/index.ts:1-20]()。

## See Also

- [README.md](README.md)
- [examples/README.md](examples/README.md)
- [examples/domain-schemas/README.md](examples/domain-schemas/README.md)
- [typescript/src/middleware/vercel-ai.ts](typescript/src/middleware/vercel-ai.ts)
- [src/neo4j_agent_memory/nams/ontology.py](src/neo4j_agent_memory/nams/ontology.py)

---

<!-- evidence_pipeline_checked: true -->
<!-- evidence_injected: true -->

---

## Doramagic 踩坑日志

项目：neo4j-labs/agent-memory

摘要：发现 20 个潜在踩坑项，其中 3 个为 high/blocking；最高优先级：安装坑 - 来源证据：Build #42's decay as re-ranking over a bitemporal, invalidate-not-delete store。

## 1. 安装坑 · 来源证据：Build #42's decay as re-ranking over a bitemporal, invalidate-not-delete store

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Build #42's decay as re-ranking over a bitemporal, invalidate-not-delete store
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 证据：community_evidence:github | https://github.com/neo4j-labs/agent-memory/issues/138 | 来源类型 github_issue 暴露的待验证使用条件。

## 2. 安装坑 · 来源证据：Support memory decay in memory search retrievers

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Support memory decay in memory search retrievers
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 证据：community_evidence:github | https://github.com/neo4j-labs/agent-memory/issues/42 | 来源类型 github_issue 暴露的待验证使用条件。

## 3. 维护坑 · 来源证据：Long-term recall is not isolation-enforced per user (Entity/Fact are global; omitting `user_identifier` returns another…

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：Long-term recall is not isolation-enforced per user (Entity/Fact are global; omitting `user_identifier` returns another user's data)
- 对用户的影响：可能影响升级、迁移或版本选择。
- 证据：community_evidence:github | https://github.com/neo4j-labs/agent-memory/issues/137 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 4. 安装坑 · 来源证据：If short-term memory is processed multiple times, Message-to-Entity links are skipped for existing extracted entities

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：If short-term memory is processed multiple times, Message-to-Entity links are skipped for existing extracted entities
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 证据：community_evidence:github | https://github.com/neo4j-labs/agent-memory/issues/131 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 5. 配置坑 · 可能修改宿主 AI 配置

- 严重度：medium
- 证据强度：source_linked
- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。
- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。
- 证据：capability.host_targets | https://github.com/neo4j-labs/agent-memory | host_targets=mcp_host, claude, chatgpt

## 6. 配置坑 · 来源证据：[Python SDK] NamsConfig requires endpoint with /v1 suffix — quick-start docs use base URL without it

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[Python SDK] NamsConfig requires endpoint with /v1 suffix — quick-start docs use base URL without it
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 证据：community_evidence:github | https://github.com/neo4j-labs/agent-memory/issues/129 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 7. 配置坑 · 来源证据：[TypeScript SDK] EntityTypeDef.poleType typed as string — invalid values pass compile-time but fail at runtime with 422

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：[TypeScript SDK] EntityTypeDef.poleType typed as string — invalid values pass compile-time but fail at runtime with 422
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 证据：community_evidence:github | https://github.com/neo4j-labs/agent-memory/issues/141 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 8. 配置坑 · 来源证据：false acks

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：false acks
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 证据：community_evidence:github | https://github.com/neo4j-labs/agent-memory/issues/140 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 9. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 证据：capability.assumptions | https://github.com/neo4j-labs/agent-memory | README/documentation is current enough for a first validation pass.

## 10. 维护坑 · 来源证据：[Python SDK] record_tool_call() and get_session_traces() crash with ValidationError — server returns status='completed'…

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：[Python SDK] record_tool_call() and get_session_traces() crash with ValidationError — server returns status='completed' not in ToolCallStatus enum
- 对用户的影响：可能阻塞安装或首次运行。
- 证据：community_evidence:github | https://github.com/neo4j-labs/agent-memory/issues/128 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 11. 维护坑 · 来源证据：[TypeScript SDK] getConversation and getContext return silent 200 for non-existent IDs instead of throwing NotFoundError

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：[TypeScript SDK] getConversation and getContext return silent 200 for non-existent IDs instead of throwing NotFoundError
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 证据：community_evidence:github | https://github.com/neo4j-labs/agent-memory/issues/124 | 来源类型 github_issue 暴露的待验证使用条件。

## 12. 维护坑 · 来源证据：[TypeScript SDK] getEntity throws TransportError instead of NotFoundError for missing entities

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：[TypeScript SDK] getEntity throws TransportError instead of NotFoundError for missing entities
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 证据：community_evidence:github | https://github.com/neo4j-labs/agent-memory/issues/125 | 来源类型 github_issue 暴露的待验证使用条件。

## 13. 维护坑 · 来源证据：[TypeScript SDK] searchMessages — sessionId typed as optional but required at runtime on hosted service

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：[TypeScript SDK] searchMessages — sessionId typed as optional but required at runtime on hosted service
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 证据：community_evidence:github | https://github.com/neo4j-labs/agent-memory/issues/126 | 来源类型 github_issue 暴露的待验证使用条件。

## 14. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 证据：evidence.maintainer_signals | https://github.com/neo4j-labs/agent-memory | last_activity_observed missing

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 证据：downstream_validation.risk_items | https://github.com/neo4j-labs/agent-memory | no_demo; severity=medium

## 16. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 证据：risks.scoring_risks | https://github.com/neo4j-labs/agent-memory | no_demo; severity=medium

## 17. 安全/权限坑 · 来源证据：[Bug/Integration] `Neo4jMemoryService` (Google ADK) is incompatible with NAMS backend + v0.4 documentation Mismatches

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Bug/Integration] `Neo4jMemoryService` (Google ADK) is incompatible with NAMS backend + v0.4 documentation Mismatches
- 对用户的影响：可能阻塞安装或首次运行。
- 证据：community_evidence:github | https://github.com/neo4j-labs/agent-memory/issues/130 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 18. 安全/权限坑 · 来源证据：[TypeScript + Python SDK] Methods unavailable on hosted service throw NotSupportedError with no compile-time warning

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[TypeScript + Python SDK] Methods unavailable on hosted service throw NotSupportedError with no compile-time warning
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 证据：community_evidence:github | https://github.com/neo4j-labs/agent-memory/issues/127 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 19. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 证据：evidence.maintainer_signals | https://github.com/neo4j-labs/agent-memory | issue_or_pr_quality=unknown

## 20. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 证据：evidence.maintainer_signals | https://github.com/neo4j-labs/agent-memory | release_recency=unknown

<!-- canonical_name: neo4j-labs/agent-memory; human_manual_source: deepwiki_human_wiki -->
