
0 g-memory SDK
为人工智能代理提供持久的、可验证的记忆——由 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 | 钱包私钥-支付汽油和存储费用 | 您的伽利略测试网密钥 |
rpcUrl | g链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
许可证
麻省理工学院