Skip to Content
Nuance LabsDocs

Bring your own memory

Keep notes about each person between conversations, and give them to the AI persona when the next conversation starts.

Every conversation you start with the API begins fresh: the AI persona retains nothing from a person's earlier conversations. To help it remember someone, save your own notes about each person and give them to the persona when their next conversation starts.

How it works

  1. Key your notes by end_user_id. This is your own id for the person, the one your server sends when it mints a session token (API keys and session tokens).
  2. Start each conversation with your notes. Place them in personality.system_prompt when you mint the token, right after the lines that define who the persona is (Your own prompt).
  3. Update the notes after each conversation. When your page creates a conversation and gets its id, have it send that id to your server. Your server identifies the person from its own sign-in check, never from the page, and only processes conversations that person's page reported. It fetches what was said with Get a transcript and adds what's worth keeping to the notes. The transcript is null until it's written, shortly after the conversation ends, so retry and wait a little longer each time. A conversation that ended before it started never gets a transcript, so stop asking after a few minutes. The example trusts the ids your page reports: verify that each one belongs to the signed-in person before you fold it, fold each conversation once, and update one person's notes one conversation at a time.

Example

// On your server: keep notes about each person between conversations, and give
// them to the AI persona when the person's next conversation starts.
const NUANCE_API = process.env.NUANCE_API_URL ?? "https://api.nuancelabs.ai";
const HEADERS = {
  Authorization: `Bearer ${process.env.NUANCE_API_KEY}`,
  "Content-Type": "application/json",
};

const PROMPT = `You are Sam, the front-desk assistant at Riverside Library: calm, patient and plain-spoken.
You help members with questions about their loans, holds and library cards.`;

// Stand-ins for your own database: the notes you keep about each person and
// the conversations each person's own page reported, both by `end_user_id`,
// and the conversations already folded into notes.
const notes = new Map<string, string>();
const reported = new Map<string, Set<string>>();
const folded = new Set<string>();

/** Mints a token whose persona starts out knowing your notes about `endUserId`. */
export async function mintToken(endUserId: string): Promise<string> {
  const remembered = notes.get(endUserId);
  const systemPrompt = remembered
    ? `${PROMPT}\n\nWhat you remember about this member from earlier conversations:\n${remembered}`
    : PROMPT;
  const response = await fetch(`${NUANCE_API}/session-tokens`, {
    method: "POST",
    headers: HEADERS,
    body: JSON.stringify({
      personality: { system_prompt: systemPrompt },
      end_user_id: endUserId,
    }),
  });
  if (!response.ok) {
    throw new Error(
      `Couldn't mint a token: ${response.status} ${await response.text()}`,
    );
  }
  const { token } = (await response.json()) as { token: string };
  return token;
}

/**
 * Your page sends the id of the conversation it created. Take `endUserId`
 * from your own sign-in check, never from the page. This example trusts the
 * ids your page reports: verify that each one belongs to the signed-in person
 * before you fold it.
 */
export function reportConversation(
  endUserId: string,
  conversationId: string,
): void {
  const ids = reported.get(endUserId) ?? new Set<string>();
  reported.set(endUserId, ids.add(conversationId));
}

interface Turn {
  role: "user" | "assistant";
  content: string;
}

/**
 * The conversation's turns, once its transcript is ready. A conversation that
 * ended before it started never gets one: its transcript stays null, so this
 * gives up after about 2 minutes.
 */
async function transcript(conversationId: string): Promise<Turn[]> {
  for (let wait = 2_000; ; wait *= 2) {
    const response = await fetch(
      `${NUANCE_API}/conversation/${encodeURIComponent(conversationId)}/transcript`,
      { headers: HEADERS },
    );
    if (!response.ok) {
      throw new Error(
        `Couldn't read the transcript: ${response.status} ${await response.text()}`,
      );
    }
    const body = (await response.json()) as { turns: Turn[] } | null;
    if (body !== null) {
      return body.turns;
    }
    if (wait > 64_000) {
      throw new Error(`The transcript of ${conversationId} is not ready yet`);
    }
    // Not ready yet: it is written shortly after the conversation ends.
    await new Promise((resolve) => setTimeout(resolve, wait));
  }
}

/**
 * Your own step: rewrite the notes with what is worth keeping from `turns`,
 * for example with a language model of your choice. Write them yourself,
 * short and in English, rather than pasting what was said: they go into
 * your prompt. This one only records that a conversation took place.
 */
async function updateNotes(current: string, turns: Turn[]): Promise<string> {
  const today = new Date().toISOString().slice(0, 10);
  return `${current}\n- ${today}: a conversation of ${turns.length} turns`.trim();
}

/** After a conversation ends: folds what was said into your notes about the person. */
export async function remember(
  endUserId: string,
  conversationId: string,
): Promise<void> {
  if (!reported.get(endUserId)?.has(conversationId)) {
    throw new Error(`This person's page didn't report ${conversationId}`);
  }
  if (folded.has(conversationId)) {
    return;
  }
  const turns = await transcript(conversationId);
  // Run one update at a time for each person, so that two conversations that
  // end together don't overwrite each other's notes.
  notes.set(endUserId, await updateNotes(notes.get(endUserId) ?? "", turns));
  folded.add(conversationId);
}

updateNotes here only records that a conversation took place. In your own app, write the notes with your own summary step, for example a language model of your choice.

Write the notes yourself

Write each person's notes yourself, short and in English, rather than pasting what was said. They go into your prompt, which follows the same rules as the rest of it (Safety and acceptable use): a prompt with non-English characters, or one that asks the persona to speak another language, is refused. Your prompt also has a length limit (Your own prompt), so rewrite the notes shorter instead of cutting them off.

Notes that don't fit the prompt

  • Let the persona look things up. With a Responses delegation, its backend can call your tools, so give it a tool that searches your notes, and answer its calls from your store (Your tools).
  • Pass along what your page learns during the conversation. Send it as session.thinking.append (Events you send).

On this page