Memory and persistence

When you use LLMs directly they all have a different approach to memory and chat persistence.

Here we standardize on a simple approach

  • By default a session always retains its history/context
  • To disable that behaviour, set a new session to incognito mode
  • Memory is stored at an app + user id level

Let's go over a few examples

Authenticated user

Open a session with memory on and tell the agent your shoe size. A week later, in a new session, it still knows. A client remembers for the user it signed in; a server names the user.

React Native
import { Client, type Session } from "@stream-io/stream-agents";

const client = new Client({ apiKey: "your_api_key" });
await client.setUser("user-123", async () => {
  // Your server mints it: https://getstream.io/agents/docs/auth/#generating-a-token
  // An app has no origin, so name your server in full.
  const response = await fetch("https://your-app.example.com/api/agent-token");
  if (!response.ok) throw new Error(`token: ${response.status}`);
  return response.text();
});
const support = client.agent("support");
// Remembers for the user setUser named.
const memory = {};

const monday = await support.sessions.create({ memory });
await ask(monday, "I wear a size 10 shoe.");
await monday.close();

const friday = await support.sessions.create({ memory });
console.log(
  await ask(friday, "What size should I order in these running shoes?"),
);
// Size 10, going by what you told me before.

async function ask(session: Session, text: string): Promise<string> {
  await session.responses.create(text);
  let answer = "";
  for await (const event of session.events()) {
    if (event.kind === "response_delta") answer += event.text;
    if (event.kind === "responded") break;
  }
  return answer;
}
React
import { Client, type Session } from "@stream-io/stream-agents";

const client = new Client({ apiKey: "your_api_key" });
await client.setUser("user-123", async () => {
  // Your server mints it: https://getstream.io/agents/docs/auth/#generating-a-token
  const response = await fetch("/api/agent-token");
  if (!response.ok) throw new Error(`token: ${response.status}`);
  return response.text();
});
const support = client.agent("support");
// Remembers for the user setUser named.
const memory = {};

const monday = await support.sessions.create({ memory });
await ask(monday, "I wear a size 10 shoe.");
await monday.close();

const friday = await support.sessions.create({ memory });
console.log(
  await ask(friday, "What size should I order in these running shoes?"),
);
// Size 10, going by what you told me before.

async function ask(session: Session, text: string): Promise<string> {
  await session.responses.create(text);
  let answer = "";
  for await (const event of session.events()) {
    if (event.kind === "response_delta") answer += event.text;
    if (event.kind === "responded") break;
  }
  return answer;
}
Kotlin
val agents = StreamAgents(apiKey = "your_api_key")
agents.setUser(User(id = "user-123")) { yourBackend.agentToken() }
val support = agents.agent("support")
// Remembers for the user setUser named.
val options = SessionOptions(memory = SessionOptions.Memory())

val monday = support.sessions.create(options)
ask(monday, "I wear a size 10 shoe.")
monday.close()

val friday = support.sessions.create(options)
println(ask(friday, "What size should I order in these running shoes?"))
// Size 10, going by what you told me before.

suspend fun ask(session: AgentSession, text: String): String = coroutineScope {
    val answer = async(start = CoroutineStart.UNDISPATCHED) {
        session.events()
            .takeWhile { it.type != "responded" }
            .filter { it.type == "response_delta" }
            .fold("") { soFar, event -> soFar + event.text }
    }
    session.responses.create(text)
    answer.await()
}
Swift
let agents = StreamAgents(apiKey: "your_api_key")
agents.setUser(User(id: "user-123")) { try await yourBackend.agentToken() }
let support = agents.agent("support")
var options = SessionOptions()
// Remembers for the user setUser named.
options.memory = SessionOptions.Memory()

let monday = try await support.sessions.create(options)
_ = try await ask(monday, "I wear a size 10 shoe.")
await monday.close()

let friday = try await support.sessions.create(options)
print(try await ask(friday, "What size should I order in these running shoes?"))
// Size 10, going by what you told me before.

@MainActor
func ask(_ session: AgentSession, _ text: String) async throws -> String {
    let events = session.events()
    _ = try await session.responses.create(text)
    var answer = ""
    for await event in events {
        if event.kind == .responseDelta { answer += event.text }
        if event.kind == .responded { break }
    }
    return answer
}
Dart
final agents = StreamAgents(apiKey: 'your_api_key', userId: 'user-123', token: yourBackend.agentToken);
final support = agents.agent('support');
// Remembers for the userId given to StreamAgents.
const options = SessionOptions(memory: SessionMemory());

final monday = await support.sessions.create(options);
await ask(monday, 'I wear a size 10 shoe.');
await monday.close();

final friday = await support.sessions.create(options);
print(await ask(friday, 'What size should I order in these running shoes?'));
// Size 10, going by what you told me before.

Future<String> ask(AgentSession session, String text) async {
  final answer = session
      .events()
      .takeWhile((event) => event.kind != AgentEventKind.responded)
      .where((event) => event.kind == AgentEventKind.responseDelta)
      .fold('', (soFar, event) => soFar + event.text);
  await session.responses.create(text);
  return answer;
}

What the agent learns is saved as the conversation goes, and recalled when a session opens. Every memory is kept under your app and the user_id, so one person's memories never reach another. In a client, pass memory: {}: it remembers for the user setUser named, since a client can't name anyone else. A server names whichever of its users it means, or the one it acts for when it names none.

Incognito

An incognito session saves nothing. Tell it your shoe size and the next session has no idea, and the conversation itself is not stored anywhere.

ReactReact Native
// Remembers for the user setUser named.
const memory = {};

const secret = await support.sessions.create({ memory, incognito: true });
await ask(secret, "I wear a size 10 shoe.");
await secret.close();

const later = await support.sessions.create({ memory });
console.log(
  await ask(later, "What size should I order in these running shoes?"),
);
// I don't know your shoe size yet. What size do you wear?

await support.sessions.get(secret.id); // throws: not found
Kotlin
agents.setUser(User(id = "user-456")) { yourBackend.agentToken() }
// Remembers for user-456, the user setUser named.
val options = SessionOptions(memory = SessionOptions.Memory())

val secret = support.sessions.create(options.copy(incognito = true))
ask(secret, "I wear a size 10 shoe.")
secret.close()

val later = support.sessions.create(options)
println(ask(later, "What size should I order in these running shoes?"))
// I don't know your shoe size yet. What size do you wear?

support.sessions.get(secret.id) // throws: not found
Swift
agents.setUser(User(id: "user-456")) { try await yourBackend.agentToken() }
var options = SessionOptions()
// Remembers for user-456, the user setUser named.
options.memory = SessionOptions.Memory()

var secretOptions = options
secretOptions.incognito = true
let secret = try await support.sessions.create(secretOptions)
_ = try await ask(secret, "I wear a size 10 shoe.")
await secret.close()

let later = try await support.sessions.create(options)
print(try await ask(later, "What size should I order in these running shoes?"))
// I don't know your shoe size yet. What size do you wear?

_ = try await support.sessions.get(secret.id) // throws: not found
Dart
// Remembers for user-456, the user withUser names.
final support = agents.withUser('user-456', token: yourBackend.agentToken).agent('support');
const options = SessionOptions(memory: SessionMemory());

final secret = await support.sessions.create(const SessionOptions(memory: SessionMemory(), incognito: true));
await ask(secret, 'I wear a size 10 shoe.');
await secret.close();

final later = await support.sessions.create(options);
print(await ask(later, 'What size should I order in these running shoes?'));
// I don't know your shoe size yet. What size do you wear?

await support.sessions.get(secret.id); // throws: not found

An incognito session has no transcript, so it can't be listed, searched, forked or rewound. It still recalls what earlier sessions learned about the person; it just adds nothing.

Show an incognito chat

An incognito session has no Stream Chat channel, so session.chat() has nothing to open. The session's connection carries the conversation instead, and the AI components show it from there: each reply streams in with its reasoning, tool calls and generative UI.

React, React Native only

AgentChat does this for you: open the session with incognito: true in the chat UI from the quickstart.

Kotlin, Swift only

turnMessages is the conversation in the shape a Stream Chat message has: a message for each of the user's questions and one for each reply, the reply's rounds of thinking and tool calls as its steps, and the whole of each round in reasoning, by its step's id. Give them to the AI components from your conversation's transport, in place of a channel's messages.

Not in the Flutter SDK yet. Showing React.

ReactReact Native
const sessions = api.agent("my-agent").sessions;
// Nothing is kept, so there's no earlier conversation to carry on.
const chat = new AgentChat<LocalMessage>({
  open: () => sessions.create({ incognito: true, tools }),
});
const conversation = new AIConversationController({
  transport: agentChatTransport(chat, {
    adapt: (message, reasoningText) =>
      fromStreamMessage(message, { reasoningText }),
  }),
  // An incognito reply can't be written again, and a question can't be edited.
  actions: { edit: false, regenerate: false },
  approver: {
    userId: "jlahey",
    clientId: AIClientIdentity.installId(),
    decide: (call, allowed) => chat.decide(call.id, { allowed }),
  },
});
Kotlin
val session = agents.agent("my-agent").sessions.create(
    SessionOptions(incognito = true, tools = tools),
)
// A new list each time the conversation, a waiting tool call or the connection changes.
session.turnMessages.collect { messages ->
    for (message in messages) {
        val steps = AIMessagePart.parts(message.steps.map { it.type to it.fields })
        // A round of thinking in full is message.reasoning[step.id].
    }
}
// A tool that asks first waits on its step: session.decide(toolCallId, allowed) answers it.
Swift
var options = SessionOptions(tools: tools)
options.incognito = true
let session = try await agents.agent("my-agent").sessions.create(options)

// Read it again whenever the session, an ObservableObject, changes.
for message in session.turnMessages {
    let steps = AIMessagePart.parts(from: message.steps.map { ($0.type, $0.payload) })
    // A round of thinking in full is message.reasoning[step.id].
}
// A tool that asks first waits on its step: session.decide(toolCallID, allowed:) answers it.

The agent's replies between two of the user's messages show as one reply, with every round of its thinking and every tool it called, by name. A tool your app gives the session that asks first shows its question on its step, for the user the session belongs to.

What the chat shows lives only on the device: it's gone once the page or app closes, and the user can't come back to it.

React, React Native only

The approver answers a tool's question, and chat.close() ends the session.

Kotlin, Swift only

The Swift assistant and Android assistant samples each have a transport that shows an incognito conversation and a kept one alike.

Info:

Showing an incognito session needs @stream-io/stream-agents 0.5.0 or later in React and React Native, and the Swift SDK 0.7.1 or later. The Flutter SDK shows only a conversation kept in Stream Chat.

Forgetting

Ending a session keeps what it learned. To forget one session, delete its memories. To forget a person, truncate their memories.

Warning:

Truncating a person's memories deletes everything learned about them, in every session and by every agent.

Regenerating, editing or rewinding a turn forgets nothing: what the agent learned on a branch the person left is kept and can still be recalled. Truncating a person's memories also deletes the router's copies of their hidden branches, which can then no longer be read or brought back.

Not documented for Python yet. Showing Node.js.

Not documented for Ruby yet. Showing Node.js.

Not documented for PHP yet. Showing Node.js.

Not documented for .NET yet. Showing Node.js.

Not documented for Rust yet. Showing Node.js.

Node.js
import { Client } from "@stream-io/stream-agents";

const api = new Client();

await api.agent("support").sessions.deleteMemories(sessionId);
await api.memories.truncate("user-123");
Go
api, err := client.New(stream.Backend{})
if err != nil {
	return err
}
if err := api.Agent("support").Sessions.DeleteMemories(ctx, sessionID); err != nil {
	return err
}
if err := api.Memories().Truncate(ctx, "user-123"); err != nil {
	return err
}