Nirmos
Examples and recipes

Exercise the Memory lifecycle

Provision a disposable policy and space, ingest evidence, and inspect derived state.

This supplemental example exercises setup, replay, search, profiles and cleanup. For an assistant that uses retrieved context in a model request, use the persistent-memory recipe.

Prerequisites and execution

Create a Dashboard API key with provider:read, model:read, memory:create, memory:read, memory:update, memory:ingest, memory:search and memory:generate. Optional cleanup additionally needs memory:update, memory:delete and memory:erase; optional credential provisioning needs credential:create.

Configure a Google provider credential in the Dashboard and verify the example's chat/embedding models are available. Managed vector storage must be enabled by the deployment. Set NIRMOS_API_KEY, a persisted MEMORY_EVENT_KEY, NIRMOS_API_BASE_URL=https://api.nirmos.com and NIRMOS_RUNTIME_BASE_URL=https://runtime.nirmos.com. Install @nirmos/sdk and tsx, save the code as memory-lifecycle.ts, then run:

NIRMOS_RUN_MEMORY_EXAMPLE=1 npx tsx memory-lifecycle.ts

Set both URL variables explicitly; this packaged example defaults to local URLs otherwise. Leave GOOGLE_API_KEY unset when the provider credential already exists. Use MEMORY_CLEANUP=1 only for this disposable space.

Complete code

import {
  APIError,
  Nirmos,
  type MemoryIngestRequest,
  type MemoryPolicyCreate,
} from "@nirmos/sdk";

declare const process: { env: Record<string, string | undefined> };

async function all<T>(
  load: (cursor?: string) => Promise<{ items: T[]; nextCursor: string | null }>,
): Promise<T[]> {
  const items: T[] = [];
  let cursor: string | undefined;
  do {
    const page = await load(cursor);
    items.push(...page.items);
    cursor = page.nextCursor ?? undefined;
  } while (cursor);
  return items;
}

/** Server-side only. Persist eventKey with the source event before first ingestion. */
export async function memoryQuickstart(
  client: Nirmos,
  options: {
    eventKey: string;
    /** A Nirmos conversation already authorized for customer-123. */
    conversationId: string;
    googleApiKey?: string;
    cleanup?: boolean;
    paceMs?: number;
  },
) {
  const pause = () =>
    new Promise((resolve) => setTimeout(resolve, options.paceMs ?? 20000));
  const provider = (
    await all((cursor) => client.providers.list({ cursor, limit: 100 }))
  ).find((p) => p.slug === "google");
  if (!provider)
    throw new Error("Google provider missing from this deployment's catalog.");
  // Optional SDK setup; dashboard Gateway Credentials → Add credential → Google is equivalent.
  if (options.googleApiKey)
    await client.providerCredentials.create({
      name: "Memory quickstart Google",
      providerId: provider.id,
      credentialType: "api_key",
      secretData: { apiKey: options.googleApiKey },
      isDefault: true,
    });
  const models = await all((cursor) =>
    client.models.list({ providerId: provider.id, limit: 100, cursor }),
  );
  const text = models.find(
    (m) => m.slug === "google-gemini-2-5-flash-lite" && m.availability,
  );
  const embedding = models.find(
    (m) => m.slug === "google-gemini-embedding-001" && m.availability,
  );
  if (!text || !embedding)
    throw new Error(
      "Configure an active Google credential and verify both models in models.list(). Availability does not guarantee provider quota.",
    );
  if (!embedding.knowledgeSupportedDimensions?.includes(768))
    throw new Error(
      "Selected embedding model does not support 768 dimensions in this deployment.",
    );
  const textModel = `${provider.slug}/${text.id}`;
  const policyInput: MemoryPolicyCreate = {
    policyKey: `${options.eventKey}-policy`,
    name: "Memory quickstart",
    version: 1,
    status: "active",
    captureTypes: [
      "preference",
      "fact",
      "project_fact",
      "decision",
      "constraint",
      "commitment",
      "event",
      "temporary_state",
    ],
    allowInferredMemories: false,
    minimumConfidence: 0.7,
    minimumFutureUtility: 0.5,
    defaultMemoryTTLSeconds: 86400,
    extractionConfig: {
      model: textModel,
      reconciliationModel: textModel,
      profileModel: textModel,
      observationModel: textModel,
      indexing: {
        model: `${provider.slug}/${embedding.id}`,
        dimensions: 768,
        distanceMetric: "cosine",
      },
    },
    privacyConfig: {
      allowPII: false,
      allowedSensitivities: ["unclassified", "public", "internal"],
    },
    retentionConfig: {
      episodeContent: "full",
      evidenceExcerpts: true,
      candidateContent: false,
    },
  };
  const existing = await client.memory.policies.list({
    policyKey: policyInput.policyKey,
    limit: 100,
  });
  const policy =
    existing.items.find((p) => p.version === 1) ??
    (await client.memory.policies.create(policyInput));
  const spaceKey = `${options.eventKey}/customer-123`;
  const spaces = await all((cursor) =>
    client.memory.spaces.list({
      externalSubjectId: "customer-123",
      cursor,
      limit: 100,
    }),
  );
  const space =
    spaces.find((s) => s.spaceKey === spaceKey) ??
    (await client.memory.spaces.create({
      spaceKey,
      name: "Disposable customer memory",
      scopeType: "user",
      scopeId: "customer-123",
      externalSubjectId: "customer-123",
      policyId: policy.id,
    }));
  const input: MemoryIngestRequest = {
    memorySpaceId: space.id,
    userId: "customer-123",
    conversationId: options.conversationId,
    idempotencyKey: options.eventKey,
    messages: [
      {
        id: `${options.eventKey}-message`,
        role: "user",
        content:
          "I prefer important notifications through email rather than WhatsApp.",
      },
    ],
  };
  let result;
  try {
    result = await client.memory.ingest(input, {
      idempotencyKey: options.eventKey,
      maxRetries: 0,
    });
  } catch (error) {
    if (error instanceof APIError) {
      // Safe identifiers/categories only; never print secrets, prompts or memory content.
      console.error({
        code: error.code,
        status: error.status,
        retryable: error.retryable,
        retryAfterMs: error.retryAfterMs,
        requestId: error.requestId,
      });
    }
    // After correcting configuration/quota, call ingest(input) with the SAME event identity.
    // Do not blindly retry, mutate the input, or generate a fresh key.
    throw error;
  }
  console.log({
    runId: result.memoryRunId,
    accepted: result.acceptedCount,
    rejected: result.rejectedCount,
    indexing: result.indexing,
  });
  if (!result.memoryRunId)
    throw new Error(
      "Memory ingestion was skipped; verify workspace, project, subject and conversation permissions.",
    );
  const run = await client.memory.runs.get(result.memoryRunId);
  if (result.indexing.failed)
    throw new Error(
      `Indexing incomplete for run ${run.id}; inspect diagnostics and repair through memory.reindex().`,
    );
  // A completed event replays without model execution or another memory write.
  const replay = await client.memory.ingest(input, {
    idempotencyKey: options.eventKey,
    maxRetries: 0,
  });
  if (replay.memoryRunId !== result.memoryRunId || !replay.replayed)
    throw new Error("Expected the original completed event to replay.");
  console.log({ replayed: replay.replayed, runId: replay.memoryRunId });
  await pause();
  const search = await client.memory.search({
    memorySpaceId: space.id,
    userId: "customer-123",
    conversationId: options.conversationId,
    query: "How should I send important notifications?",
    relevance: "relevant",
  });
  console.log({ relevantMatches: search.memories.length });
  await pause();
  const context = await client.memory.context({
    memorySpaceId: space.id,
    userId: "customer-123",
    conversationId: options.conversationId,
    messages: [{ role: "user", content: "How should you notify me?" }],
  });
  console.log({ contextMemories: context.memories.length });
  await pause();
  await client.memory.profiles.generate({ memorySpaceId: space.id });
  const profile = await client.memory.profiles.get(space.id);
  const items = await client.memory.items.list({
    memorySpaceId: space.id,
    limit: 25,
  });
  const first = items.items[0];
  if (first) {
    await client.memory.items.update(first.id, { importance: 0.8 });
    await client.memory.items.evidence(first.id, { limit: 25 });
    // Explicit cleanup only for this disposable example's space.
    if (options.cleanup) await client.memory.items.delete(first.id);
  }
  if (options.cleanup) {
    const deletion = await client.memory.spaces.delete(space.id);
    console.log({ deletionOperationId: deletion.id });
    // Poll privacy.operations.get(deletion.id) before removing the policy.
  }
  return { space, policy, result, search, context, profile };
}

if (process.env.NIRMOS_RUN_MEMORY_EXAMPLE === "1") {
  const token = process.env.NIRMOS_API_KEY;
  const eventKey = process.env.MEMORY_EVENT_KEY;
  if (!token || !eventKey)
    throw new Error("Set NIRMOS_API_KEY and a persisted MEMORY_EVENT_KEY.");
  await memoryQuickstart(
    new Nirmos({
      auth: { type: "api-key", key: token },
      apiBaseUrl: process.env.NIRMOS_API_BASE_URL ?? "http://localhost:4001",
      runtimeBaseUrl:
        process.env.NIRMOS_RUNTIME_BASE_URL ?? "http://localhost:4000",
      maxRetries: 0,
    }),
    {
      eventKey,
      conversationId: process.env.MEMORY_CONVERSATION_ID ?? "",
      googleApiKey: process.env.GOOGLE_API_KEY,
      cleanup: process.env.MEMORY_CLEANUP === "1",
    },
  );
}

Catalog references are resolved to organization-visible model IDs. This example uses google/google-gemini-2-5-flash-lite and google/google-gemini-embedding-001, 768 dimensions, cosine; check your deployment's catalog and supported dimensions first. Availability indicates configured credentials, not remaining quota or an upstream health guarantee. Operator-managed Qdrant must be available; ordinary policies need no connection ID. Advanced BYO overrides must reference an active organization-owned vector-store connection.

Calls are sequential with conservative pauses. Search and context each embed the query and, by default, invoke one bounded relevance check; provider requests can therefore exceed the number of SDK calls. Avoid parallel model tests. Respect provider-specific limits, use bounded retries, and stop on quota exhaustion.

Expected behavior

The script logs ingestion counters, verifies replay identity, retrieves memories and explicitly generates a profile. Extraction may accept no candidates; provider calls and scores vary with the selected model and evidence. It spaces model operations conservatively and can take several minutes.

The space key derives from the event identity. Reuse the persisted identity for ingestion recovery, but do not rerun resource creation blindly: duplicate space or policy keys return conflicts. Keep the logged IDs and inspect current state. Memory lifecycle explains revisions, reindexing and erasure.

On this page