# 0g-memory-sdk 中文文档

规范地址：https://npmcn.com/package/0g-memory-sdk/

版本：0\.1\.2
npm 元数据更新时间：2026-05-16T16:21:43.173Z
中文译文更新时间：2026-10-31T12:51:34.027Z
软件包许可：MIT

本文由上游 README 机器翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/0g-memory-sdk
原文对照：https://npmcn.com/package/0g-memory-sdk/?lang=original
项目主页：https://github.com/anbusan19/0g-memory-sdk#readme
源码仓库：https://github.com/anbusan19/0g-memory-sdk

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：70 kB，12 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=18
- 运行依赖：2 个
- 首次发布：2026-05-16T14:49:38.277Z
- 最新版本发布：2026-05-16T16:21:43.058Z
- 已发布版本数：3（近 12 个月 3 个）

## 中文简介

为人工智能代理提供持久、可验证的内存——由0G Storage （KV + Log）和0G Chain支持

## 安装

```sh
npm install 0g-memory-sdk
```

也可以使用：`pnpm add 0g-memory-sdk`、`yarn add 0g-memory-sdk`、`bun add 0g-memory-sdk`

## README

![0G-Memory](https://npmcn.com/readmebanner.png)

# 0 g-memory SDK

[![npm version](https://img.shields.io/npm/v/0g-memory-sdk)](https://www.npmjs.com/package/0g-memory-sdk) [![license](https://img.shields.io/npm/l/0g-memory-sdk)](https://npmcn.com/package/0g-memory-sdk/LICENSE)

为人工智能代理提供持久的、可验证的记忆——由 [0 g存储](https://0g.ai/) （KV + Log层）和0G链。

使用此SDK构建的代理可以跨会话记住客户机、上下文和历史记录——来自任何机器，不需要数据库。

```bash
npm install 0g-memory-sdk
```

* * *

## 为什么

当会话结束时，人工智能代理会忘记所有事情。上下文存在于RAM、第三方拥有的数据库中，或者根本不存在。没有密码证明存储的数据没有被修改过。

`0g-memory-sdk` 给出了三个完全在0G去中心化网络上运行的代理：

| 方法 | 它是做什么的 |
| --- | --- |
| `remember(key, value)` | 永久写入0G Log（不可变的，默克尔可证明的）并注册一个 `key → rootHash` 指针在0千伏，所以它是可从任何机器检索 |
| `recall(key)` | 通过KV索引解析键，从Log层获取值 |
| `archive(record)` | 写入键入的业务记录并返回 [StorageScan](https://storagescan-newton.0g.ai/) URL作为链上可验证的证明 |

因为密钥索引驻留在0G上——而不是磁盘上——任何具有相同私钥和 `agentId` 获取跨机器、重新启动和无服务器部署的全部内存。

* * *

## 快速启动

```ts
import { ZeroGMemory, deriveAgentId } from '0g-memory-sdk';

const { agentId } = deriveAgentId('my-agent', process.env.PRIVATE_KEY!);

const memory = new ZeroGMemory({
  agentId,
  privateKey: process.env.PRIVATE_KEY!,
  rpcUrl:     'https://evmrpc-testnet.0g.ai',
  indexerRpc: 'https://indexer-storage-testnet-standard.0g.ai',
});

// Store something
const rootHash = await memory.remember('user:alice', { plan: 'pro', credits: 42 });

// Retrieve later — from any machine
const data = await memory.recall('user:alice');
// → { plan: 'pro', credits: 42 }

// Or retrieve immediately by root hash (before KV index settles on-chain)
const same = await memory.recallByHash(rootHash);
```

> **Testnet令牌:** 得到OG [0 g水龙头](https://faucet.0g.ai/) 支付存储交易。

* * *

## API

### `new ZeroGMemory(config)`

```ts
const memory = new ZeroGMemory({
  agentId:    string,  // unique agent identifier — use deriveAgentId()
  privateKey: string,  // wallet private key, pays for 0G storage txs
  rpcUrl:     string,  // 0G chain RPC endpoint
  indexerRpc: string,  // 0G storage indexer endpoint
});
```

`ChainMemory` 的别名导出 `ZeroGMemory` 用于向后兼容。

* * *

### `memory.remember(key, value) → Promise<string>`

写 `value` 到0G日志层（永久的，内容寻址的）并触发并发的KV写入寄存器 `key → rootHash` 在分布式索引中。返回根哈希值。

```ts
const rootHash = await memory.remember('session:xyz', {
  messages: [...],
  summary: 'User asked about pricing.',
});
```

KV索引写入在几个0G块内完成。使用 `recallByHash(rootHash)` 用于在解决之前访问同一请求。

* * *

### `memory.recall(key) → Promise<unknown | null>`

查找 `key` 在0G KV索引中，然后从Log层获取该值。返回 `null` 如果密钥从未写入或KV索引尚未确定。

自动回退到旧的本地文件索引(`.chainmemory/`)，并在第一次访问时将这些条目迁移到KV。

```ts
const context = await memory.recall('session:xyz');
if (context) {
  // resume where the agent left off
}
```

* * *

### `memory.recallByHash(rootHash) → Promise<unknown | null>`

通过根哈希直接从0G Log层获取值，完全绕过KV索引。使用后立即使用 `remember()` 当您无法等待指数结算时。

```ts
const rootHash = await memory.remember('key', data);
const same     = await memory.recallByHash(rootHash); // always consistent
```

* * *

### `memory.archive(record) → Promise<{ rootHash, storageScanUrl }>`

将一个类型化的永久记录写入到0G Log层。返回内容地址根散列和 [StorageScan](https://storagescan-newton.0g.ai/) 任何人都可以使用该URL来验证数据未被修改。

```ts
const { rootHash, storageScanUrl } = await memory.archive({
  type: 'invoice',   // 'invoice' | 'payment' | 'interaction' | 'custom'
  data: invoice,
});

console.log(storageScanUrl);
// https://storagescan-newton.0g.ai/tx/0xabc...
```

* * *

### `memory.updateClientContext(clientName, context) → Promise<string>`

标准化的方便包装器 `clientName` 到一个钥匙(`client:<name>`)及电话 `remember()`． 专为服务多个客户机并需要每个客户机持久状态的代理而设计。返回根哈希值。

```ts
const rootHash = await memory.updateClientContext('Alice Johnson', {
  totalInvoiced: 4200,
  invoiceCount:  3,
  lastJobDescription: 'Frontend redesign — 40 hrs at $120/hr',
});

// Recall in a future session:
const alice = await memory.recall('client:alice_johnson');
```

* * *

### `deriveAgentId(name, privateKey) → AgentIdentity`

从人类可读的名称和钱包私钥中派生确定性的、抗冲突的代理ID。格式: `<name>:<first-8-hex-chars-of-address>`.

```ts
import { deriveAgentId } from '0g-memory-sdk';

const { agentId, walletAddress } = deriveAgentId('billing-agent', process.env.PRIVATE_KEY!);
// agentId:       "billing-agent:a3f8c201"
// walletAddress: "0xA3F8..."
```

### `isValidAgentId(agentId) → boolean`

验证字符串是否匹配 `<name>:<8-hex-chars>` 格式。

* * *

## 配置引用

| 场 | 描述 | Testnet价值 |
| --- | --- | --- |
| `agentId` | 唯一代理标识符 | `deriveAgentId('my-agent', privateKey).agentId` |
| `privateKey` | 钱包私钥-支付汽油和存储费用 | 您的伽利略测试网密钥 |
| `rpcUrl` | g链JSON-RPC端点 | `https://evmrpc-testnet.0g.ai` |
| `indexerRpc` | 存储索引器端点 | `https://indexer-storage-testnet-standard.0g.ai` |

* * *

## 模式

### 跨重启的会话内存

```ts
async function chat(sessionId: string, userMessage: string) {
  const history = (await memory.recall(`session:${sessionId}`)) as Message[] ?? [];

  const reply = await llm.complete([
    ...history,
    { role: 'user', content: userMessage },
  ]);

  await memory.remember(`session:${sessionId}`, [
    ...history,
    { role: 'user',      content: userMessage },
    { role: 'assistant', content: reply },
  ]);

  return reply;
}
```

### Returning-client检测

```ts
async function greet(clientName: string) {
  const ctx = await memory.recall(`client:${clientName.toLowerCase()}`);
  return ctx
    ? `Welcome back — you've invoiced $${ctx.totalInvoiced} across ${ctx.invoiceCount} jobs.`
    : `Welcome! Let's set up your first invoice.`;
}
```

### 可验证的审计跟踪

```ts
const { rootHash, storageScanUrl } = await memory.archive({
  type: 'invoice',
  data: { id: 'INV-042', client: 'Acme Corp', total: 6000, currency: 'USD' },
});

// Share storageScanUrl — anyone can verify the invoice was not tampered with
```

### LangChain / agent框架集成

```ts
import { ZeroGMemory, deriveAgentId } from '0g-memory-sdk';

const { agentId } = deriveAgentId('langchain-agent', process.env.PRIVATE_KEY!);
const memory = new ZeroGMemory({ agentId, privateKey: ..., rpcUrl: ..., indexerRpc: ... });

// Use as a custom memory store
const loadMemory = async (key: string) => memory.recall(key);
const saveMemory = async (key: string, value: unknown) => memory.remember(key, value);
```

* * *

## 一致性模型

| 模式 | 一致性 | 何时使用 |
| --- | --- | --- |
| `remember()` → `recallByHash()` | 立即 | 同样的请求，同样的会话 |
| `remember()` → `recall()` | 最终（几个街区，~秒） | Cross-session,跨机器 |
| `archive()` | 写一次,永久 | 发票、审计记录、证明记录 |

`recall()` 自动回退到本地 `.chainmemory/` 索引由旧SDK版本编写的数据，并将这些条目透明地迁移到KV层。

* * *

## 参考应用

**AgentBill** 是参考实现-在完整的0G堆栈上使用此SDK构建的自主发票代理：

-   **0克计算** - Qwen-2.5-7B将自然语言职位描述解析为结构化发票
-   **0 g内存** -跨会话调用每个客户端上下文 `recall()` / `updateClientContext()`
-   **0 g存储** -每张发票永久存档 `archive()`，根哈希返回作为证明
-   **0 g链** -通过托管智能合约在链上注册和支付发票

来源: [github.com/anbusan19/0g-memory](https://github.com/anbusan19/0g-memory)

* * *

## 许可证

麻省理工学院

## 常见问题

### 0g-memory-sdk 是什么？

为人工智能代理提供持久、可验证的内存——由0G Storage （KV \+ Log）和0G Chain支持

### 如何安装 0g-memory-sdk？

在项目目录运行 npm install 0g-memory-sdk，或使用 pnpm add / yarn add / bun add。

### 0g-memory-sdk 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### 0g-memory-sdk 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### 0g-memory-sdk 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=18。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### 0g-memory-sdk 可以商用吗？

0g-memory-sdk 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### 0g-memory-sdk 还在维护吗？

最新版本 0\.1\.2 发布于 2026/05/17（5 个月前）；至今共发布 3 个版本，其中过去 12 个月发布了 3 个；首次发布于 2026/05/16。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

