0g-memory-sdk

中文文档
0.1.2发布于 2026/05/17MITTypeScriptESM + CJS

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

中文使用文档
文档目录20 节
  1. 为什么
  2. 快速启动
  3. API
  4. new ZeroGMemory(config)
  5. memory.remember(key, value) → Promise<string>
  6. memory.recall(key) → Promise<unknown | null>
  7. memory.recallByHash(rootHash) → Promise<unknown | null>
  8. memory.archive(record) → Promise<{ rootHash, storageScanUrl…
  9. memory.updateClientContext(clientName, context) → Promise<s…
  10. deriveAgentId(name, privateKey) → AgentIdentity
  11. isValidAgentId(agentId) → boolean
  12. 配置引用
  13. 模式
  14. 跨重启的会话内存
  15. Returning-client检测
  16. 可验证的审计跟踪
  17. LangChain / agent框架集成
  18. 一致性模型
  19. 参考应用
  20. 许可证

0G-Memory

0 g-memory SDK

npm version license

为人工智能代理提供持久的、可验证的记忆——由 0 g存储 (KV + Log层)和0G链。

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

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 URL作为链上可验证的证明

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


快速启动

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水龙头 支付存储交易。


API

new ZeroGMemory(config)

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 在分布式索引中。返回根哈希值。

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。

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() 当您无法等待指数结算时。

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

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

将一个类型化的永久记录写入到0G Log层。返回内容地址根散列和 StorageScan 任何人都可以使用该URL来验证数据未被修改。

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(). 专为服务多个客户机并需要每个客户机持久状态的代理而设计。返回根哈希值。

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>.

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钱包私钥-支付汽油和存储费用您的伽利略测试网密钥
rpcUrlg链JSON-RPC端点https://evmrpc-testnet.0g.ai
indexerRpc存储索引器端点https://indexer-storage-testnet-standard.0g.ai

模式

跨重启的会话内存

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检测

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.`;
}

可验证的审计跟踪

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框架集成

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


许可证

麻省理工学院

版本与发布记录

0g-memory-sdk 共发布 3 个版本,首次发布于 2026/05/16;过去 12 个月发布了 3 个版本。

版本发布日期距今
0.1.2latest2026/05/175 个月前
0.1.12026/05/165 个月前
0.1.02026/05/165 个月前

关于 0g-memory-sdk 的常见问题

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 和提交记录判断。