Atlas 代理 引擎 (Typescript) 的统一内存外观。Python agent-engine-sdk-memory 包的对应版本:Typescript 代理通过相同的路由从 Memory 服务器读取数据并写入其中,其内存可在多轮对话和会话中持久保存。
安装
npm install @mongodb-js/agent-engine-sdk-memoryThe Memory facade
Memory 在一个与传输无关的统一表面之后,暴露所有内存类型:
类型 | 写入 | 读取 |
|---|---|---|
对话轮次 (STM) |
| (订阅源 |
语义(事实) |
|
|
情境式(对话) |
|
|
分类(知识库) |
|
|
程序化(操作指南) |
|
|
自定义类型(按项目声明) |
|
|
统一 | — |
|
所有方法都是异步的。每次调用时都会解析身份 (userId / sessionId) — 从参数、绑定上下文和运行时的环境上下文中解析。自定义类型的操作是个例外:它们不带有身份字段 — 平台会为请求中的 org、 项目和 user 打上标记 — 因此它们不会解析客户端身份,并且需要一个可以为其打上标记的后端(project-作用域的网关路由或执行作用域的运行时)。
两种模式
两者的外观相同;只有提供 URL、身份验证和身份的方式不同。
HTTP-direct(独立运行的实例/平台外)
一个用于在平台外部运行脚本、测试和代码的独立客户端。通过构造函数参数或 AGENTIC_MEMORY_* 环境变量进行配置。
import { Memory } from "@mongodb-js/agent-engine-sdk-memory";
const memory = new Memory({ serviceAccountToken: process.env.AGENTIC_MEMORY_SERVICE_ACCOUNT_TOKEN, // service-account access token projectId: "my-project", // set => project-scoped Gateway routes}); // unset => flat OE routes
await memory.saveSemantic({ text: "favorite color is teal", label: "favorite_color", userId: "u1", metadata: { channel: "web", priority: "high" }, // optional caller-supplied metadata});const hits = await memory.searchSemantic({ query: "color", userId: "u1" });await memory.close();Env var | 用途 |
|---|---|
| 服务帐户访问令牌(设置时回退到托管的 Gateway URL)。 |
| 后端地址。 |
| 设置 => 项目级网关路由;空 => 扁平 OE 路由。 |
绑定到应用(在已部署的代理中)
代理代码使用 app.memory(来自 @mongodb-js/agent-engine-sdk-langgraph)。身份来自环境请求上下文,并通过编排引擎的内存代理路由调用 — 无需管理令牌,也无需 userId 线程:
// inside a tool or entrypointawait app.memory.saveSemantic({ text: "prefers email over SMS", label: "contact_pref" });const context = await app.memory.buildContext({ query: "how does the user like to be contacted?" });仅在处理平台请求时才能访问应用程序绑定的内存(它需要执行上下文的 OE_URL)。
上下文令牌预算
buildContext({ maxTokens }) 设置一个可选的总上下文构建预算(非获取费用)。检索和排名后,服务器会减去 500 个标记的格式预留,然后贪婪地选择适合剩余空间的完整内存数据块。等于或低于 500 的正值不会为内存留下预算。当没有数据块适合时,高于 500 的值仍可能产生空上下文。metadata.token_count 仅报告格式化输出,不包括预留部分。省略 maxTokens 以保留服务器默认设置。
Errors
Typed errors let callers branch on failure mode: MemoryAuthError (401/403), MemoryRouteNotFoundError (404 with a route-shape hint), MemoryBadRequestError, MemoryServerError (5xx / bad body), MemoryConnectionError, MemoryNotSupportedError (capability gap), and MemoryIdentityError (a required identity field could not be resolved). MemoryNotSupportedError covers both client-side gaps and, on the custom-type routes, capability gaps only the platform can report: a bare 404/405 (platform too old to serve the route) or the gateway's structured 400 reporting custom memory types disabled on the deployment. A structured unknown-type 404 raises MemoryBadRequestError. Transport retries 502/503/504 up to three times.
开发中
npm installnpm test # vitestnpm run build # tsc