Sessions

Add and retrieve conversation events, configure retention, and summarize older messages.

Session memory holds a conversation's transcript. Your application saves each message as an event, then retrieves the transcript when the user sends the next message. This gives the agent the history it needs to continue the conversation.

For example, a travel assistant can retrieve the cities a user mentioned earlier in the chat instead of asking again. Each chat has a session ID (sessionId) that ties its events together. The same ID lets your application retrieve the conversation later.

This page covers adding events, retrieving a conversation, and finding session IDs by owner or namespace. It also explains two settings that control the history: retention determines how long a session stays available, and summarization condenses older messages so they take less space in the model's context window.

Add session events

A session event represents one message from a user, assistant, or system. To append one, send POST /iris/data/v1/agent-memory/stores/{storeId}/sessions/{sessionId}/events, which creates the session if it does not exist. In Python, memory.conversation(owner=..., session_id=...) returns a conversation whose user and assistant methods append events. To start a session with a server-generated ID, send its first event to POST /iris/data/v1/agent-memory/stores/{storeId}/sessions instead. In Python, omit session_id and the SDK generates one; read it from conversation.session_id.

Redis Agent Memory adds the event ID and storage timestamp. The event fields are:

Field Who supplies it Purpose
eventId Server-generated. Identifies the event.
sessionId Client-supplied in the path, or server-generated when you create a session without one. Identifies the session that contains the event.
actorId Required from the client. Identifies the user, agent, or other actor that produced the event.
role Required from the client. Role of the message in the conversation.
content Required from the client. Message content, including its text.
createdAt Required from the client. Time the event occurred in the application.
systemTimestamp Server-generated. Time Redis Agent Memory stored the event.
metadata Optional from the client. Application-specific information associated with the event.

Event metadata can contain up to 120 levels of nested JSON objects and arrays. A deeper value returns 400 before the service writes the event.

  1. Set the first event's actorId to the signed-in user's account ID from your application. Use the same ID each time this user returns. The server uses it as the session owner. Later events can identify other actors, such as the assistant. In Python, conversation.user sends the owner as actorId, and conversation.assistant sends the assistant_id passed to AgentMemory.from_env().
  2. Supply a sessionId, or omit it to let the server create one. Save the returned event.sessionId for later requests. See Identify users and conversations for examples.
  3. Set the message's role, content, and createdAt timestamp.
  4. Send the request.

These examples continue from the quickstart. Load the same .env connection values and reuse its user ID. Expand an example to copy a complete program that connects for you.

Each run repeats every write in the program. Session-event writes and memory creates with a new idempotency key add new records, so run cleanup or change the identifiers before rerunning.

conversation = memory.conversation(owner=OWNER_ID, session_id=SESSION_ID)
saved = conversation.user("I am vegetarian.")
print("Saved event", saved.event_id, "in", saved.session_id)
const saved = await memory.addSessionEvent(SESSION_ID, {
  actorId: OWNER_ID,
  role: "USER",
  content: [{ text: "I am vegetarian." }],
  createdAt: new Date(),
  idempotencyKey: crypto.randomUUID(),
});
console.log("Saved event", saved.event.eventId, "in", saved.event.sessionId);
jq -n --arg owner "$OWNER_ID" --arg now "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg key "$(uuidgen)" '{
  actorId: $owner,
  role: "USER",
  content: [{text: "I am vegetarian."}],
  createdAt: $now,
  idempotencyKey: $key
}' > event.json
curl --fail-with-body --silent --show-error \
  -X POST "$MEMORY_API/sessions/$SESSION_ID/events" -H "$AUTH" \
  -H 'Content-Type: application/json' --data-binary @event.json | jq .

Send each new message once, using the same session ID throughout the conversation.

The session's ownerId comes from the first event's actorId and is returned when you retrieve the session. In on-prem deployments with server-side ownership enforcement, the first event's actorId must match the authenticated user ID.

Retrieve conversation context

When the next message arrives, retrieve the session by its ID before calling the model:

transcript = conversation.transcript()
if transcript.owner != OWNER_ID:
    raise PermissionError("This session belongs to another user.")
print("Summary:", transcript.summary)
for event in transcript.events:
    print(event.role, event.actor_id, event.text)
const transcript = await memory.getSessionMemory(SESSION_ID);
if (transcript.ownerId !== OWNER_ID) {
  throw new Error("This session belongs to another user.");
}
console.log("Summary:", transcript.summary?.text);
for (const event of transcript.events) {
  console.log(event.role, event.actorId, event.content);
}
curl --fail-with-body --silent --show-error \
  "$MEMORY_API/sessions/$SESSION_ID" -H "$AUTH" |
  jq '{ownerId, summary: .summary.text, events: [.events[] | {role, actorId, content}]}'
iris agent-memory sessions show travel-planning-session

The events array contains the retained conversation messages. If older events have been summarized, the response also includes summary.text. Pass both to the model with the current user message; in Python, transcript.as_messages() returns them as chat messages. See Build context for each agent turn for an example.

Your application must check that the current user can access this session before using it. The request selects a session by ID; it does not include an owner filter. Compare the returned ownerId (transcript.owner in Python) with the authenticated user, as the example does.

Read part of a transcript

Use ListSessionEvents to fetch the events you need for the next agent turn. Use the SDK and connection settings from the quickstart.

Request the last 20 retained events in transcript order:

page = memory.client.list_session_events(session_id=SESSION_ID, last=20)
print(page.model_dump_json(by_alias=True, indent=2))
const recent = await memory.listSessionEvents(
  SESSION_ID,
  undefined, // afterEventId
  undefined, // beforeEventId
  undefined, // order
  undefined, // limit
  20, // last
);
console.log(recent.items);
PAGE=$(curl --fail-with-body --silent --show-error --get \
  "$MEMORY_API/sessions/$SESSION_ID/events" -H "$AUTH" \
  --data-urlencode 'last=20')
jq . <<< "$PAGE"

Use afterEventId or beforeEventId to set exclusive bounds. Use limit and order for a page in either direction, or use last on its own to page backwards while each page stays in transcript order. Pass nextCursor as cursor with the same bounds and ordering to continue.

If a long-term recap includes summarizedUpToEventId, use that event ID as the lower bound. Request the retained events after the checkpoint:

page = memory.client.list_session_events(
    session_id=SESSION_ID, after_event_id=checkpoint_event_id
)
print(page.model_dump_json(by_alias=True, indent=2))
const afterCheckpoint = await memory.listSessionEvents(SESSION_ID, checkpointEventId);
console.log(afterCheckpoint.items);
curl --fail-with-body --silent --show-error --get \
  "$MEMORY_API/sessions/$SESSION_ID/events" -H "$AUTH" \
  --data-urlencode "afterEventId=$CHECKPOINT_EVENT_ID" | jq .

If the recap has no checkpoint or the request returns 404 Event Not Found for the checkpoint, restart without afterEventId or a cursor. If the event your cursor points to was deleted, the service returns 400 Invalid Cursor. Restart the same range without the cursor.

List sessions

To let a user reopen an earlier conversation, list their sessions and retrieve the selected session by ID. Use GET /iris/data/v1/agent-memory/stores/{storeId}/sessions, memory.sessions(owner) or memory.client.list_sessions in Python, or iris agent-memory sessions list. These rows do not contain events or generated summary text. See List and sort sessions for SDK examples and pagination.

Filter the list by owner, namespace, creation time, or last update time.

For a user's personal conversations, set ownerId to that user's authenticated ID. A namespace-only query is suitable for shared conversations only after your application checks access to that namespace. Reserve includeAll=true for callers your application authorizes to list the whole store. See Authorize every memory request.

To list one user's session IDs:

for session_id in memory.sessions(OWNER_ID):
    print(session_id)
const ownerSessions = await memory.listSessions(undefined, undefined, OWNER_ID);
for (const session of ownerSessions.items) console.log(session.sessionId);
curl --fail-with-body --silent --show-error --get \
  "$MEMORY_API/sessions" -H "$AUTH" \
  --data-urlencode "ownerId=$OWNER_ID" | jq '.items[].sessionId'
iris agent-memory sessions list --owner quickstart-user

To list sessions in one namespace, filter by its stable ID. This example creates a personal namespace, starts a session in it, and lists that namespace's sessions. In an application, create the namespace once and save its ID.

created = memory.client.create_namespace(
    request={
        "name": "example-travel",
        "scope": models.NamespaceScope.PERSONAL,
        "owner_id": OWNER_ID,
    }
)
NAMESPACE_ID = created.namespace.namespace_id

trip = memory.conversation(
    owner=OWNER_ID, session_id="example-kyoto-trip", namespace_id=NAMESPACE_ID
)
trip.user("Plan two days in Kyoto.")

page = memory.client.list_sessions(namespace_id=NAMESPACE_ID)
for session in page.items:
    print(session.session_id, session.owner_id, session.namespace_id)
const { namespace } = await memory.createNamespace({
  name: "example-travel",
  scope: "PERSONAL",
  ownerId: OWNER_ID,
});
const namespaceId = namespace.namespaceId;

await memory.addSessionEvent("example-kyoto-trip", {
  actorId: OWNER_ID,
  role: "USER",
  content: [{ text: "Plan two days in Kyoto." }],
  createdAt: new Date(),
  namespaceId,
  idempotencyKey: crypto.randomUUID(),
});
const namespaceSessions = await memory.listSessions(
  undefined, undefined, undefined, undefined, undefined, namespaceId,
);
for (const session of namespaceSessions.items) {
  console.log(session.sessionId, session.ownerId, session.namespaceId);
}
jq -n --arg owner "$OWNER_ID" \
  '{name: "example-travel", scope: "PERSONAL", ownerId: $owner}' > namespace.json
NAMESPACE_ID=$(curl --fail-with-body --silent --show-error \
  -X POST "$MEMORY_API/namespaces" -H "$AUTH" \
  -H 'Content-Type: application/json' --data-binary @namespace.json |
  jq -r '.namespace.namespaceId')

jq -n --arg owner "$OWNER_ID" --arg ns "$NAMESPACE_ID" \
  --arg now "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg key "$(uuidgen)" '{
  actorId: $owner,
  role: "USER",
  content: [{text: "Plan two days in Kyoto."}],
  createdAt: $now,
  namespaceId: $ns,
  idempotencyKey: $key
}' > trip.json
curl --fail-with-body --silent --show-error \
  -X POST "$MEMORY_API/sessions/example-kyoto-trip/events" -H "$AUTH" \
  -H 'Content-Type: application/json' --data-binary @trip.json > /dev/null

curl --fail-with-body --silent --show-error --get \
  "$MEMORY_API/sessions" -H "$AUTH" \
  --data-urlencode "namespaceId=$NAMESPACE_ID" | jq '.items'

namespaceId matches the namespace ID exactly, including case. It excludes descendant namespaces, sessions with only the older namespace string label, and sessions without a namespace resource.

Add ownerId to return sessions that match both the namespace and the owner:

page = memory.client.list_sessions(namespace_id=NAMESPACE_ID, owner_id=OWNER_ID)
for session in page.items:
    print(session.session_id, session.updated_at)
const matchingSessions = await memory.listSessions(
  undefined, undefined, OWNER_ID, undefined, undefined, namespaceId,
);
for (const session of matchingSessions.items) console.log(session.sessionId, session.updatedAt);
curl --fail-with-body --silent --show-error --get \
  "$MEMORY_API/sessions" -H "$AUTH" \
  --data-urlencode "namespaceId=$NAMESPACE_ID" \
  --data-urlencode "ownerId=$OWNER_ID" | jq '.items'

To list all sessions, omit the filters and set includeAll=true.

page = memory.client.list_sessions(include_all=True, limit=20)
for session in page.items:
    print(session.session_id, session.owner_id)
print("Next page:", page.next_cursor)
const all = await memory.listSessions(20, undefined, undefined, true);
for (const session of all.items) console.log(session.sessionId, session.ownerId);
console.log("Next page:", all.nextCursor);
curl --fail-with-body --silent --show-error --get \
  "$MEMORY_API/sessions" -H "$AUTH" \
  --data-urlencode 'includeAll=true' --data-urlencode 'limit=20' |
  jq '{sessions: [.items[] | {sessionId, ownerId}], nextCursor}'

Do not combine includeAll=true with any filter. A request without a filter must set includeAll=true.

The response contains session rows in items and no total count. If the response includes nextCursor, pass it as cursor with the same filters to fetch the next page. See the List Sessions API reference for pagination limits.

Configure session retention

The session-memory time to live (TTL) controls how long sessions remain available. Choose a duration that lets users resume conversations for as long as your application needs. When a session expires, its events are no longer available through session-memory retrieval.

In the Redis Cloud console, open your service's Configuration tab and select Edit. Set Short-term TTL under Memory configuration.

See memory configuration to configure the session-memory TTL in Redis Cloud.

Configure automatic summarization

As a conversation grows, its messages take more space in the model's context window. Automatic summarization replaces older messages with a shorter summary while keeping recent messages in full.

In the Redis Cloud console, open your service's Configuration tab and select Edit. Under Memory configuration, enable Automatic summarization and set:

  • Summarize after: The number of messages a session can contain before older messages are summarized.
  • Keep most recent: The number of recent messages that remain available in full.

For example, with Summarize after set to 20 and Keep most recent set to 10, Redis Agent Memory summarizes the older 10 messages when the session reaches 20 messages and retains the 10 most recent messages in full.

See automatic summarization to enable summarization and configure both thresholds in Redis Cloud.

For an example that combines session events with long-term recall, follow the developer guide. For complete schemas, see the session-memory application programming interface (API) reference.

To group a session and its extracted memories, use an optional namespace.

Store searchable session recaps

Automatic summarization helps you resume a conversation. A long-term session recap is a searchable memory about a conversation. User-defined Summary Views summarize a set of long-term memories.

To enable recaps, set "longTermMemory": {"sessionSummaryEnabled": true} when creating or updating the store. The store setting defaults to false. Self-managed deployments also need recap extraction on the server and worker.

Search for the recap using the owner, session, and memory type. Check that the user can access the session before fetching its events. The example reads the latest 20 events when no recap is available.

from redis_iris.agent_memory import AgentMemory

memory = AgentMemory.from_env()

owner_id = "quickstart-user"
session_id = "travel-planning-session"

recaps = memory.client.search_long_term_memory(request={
    "filter_": {
        "owner_id": {"eq": owner_id},
        "session_id": {"eq": session_id},
        "memory_type": {"eq": "session_summary"},
    },
    "sort_by": "updatedAt",
    "sort_order": "DESC",
    "limit": 1,
})
if recaps.items:
    recap = recaps.items[0]
    page = memory.client.list_session_events(
        session_id=session_id, after_event_id=recap.summarized_up_to_event_id,
    )
    print("Recap:", recap.text)
else:
    page = memory.client.list_session_events(session_id=session_id, last=20)
for event in page.items:
    print(event.role, event.content)
import { AgentMemory } from "@redis-iris/agent-memory";

const memory = new AgentMemory({
  serverURL: process.env.IRIS_AGENT_MEMORY_URL!,
  storeId: process.env.IRIS_AGENT_MEMORY_STORE_ID!,
  apiKey: process.env.IRIS_AGENT_MEMORY_API_KEY!,
});

const ownerId = "quickstart-user";
const sessionId = "travel-planning-session";

const { items } = await memory.searchLongTermMemory({
  filter: {
    ownerId: { eq: ownerId },
    sessionId: { eq: sessionId },
    memoryType: { eq: "session_summary" },
  },
  sortBy: "updatedAt",
  sortOrder: "DESC",
  limit: 1,
});
const recap = items[0];
if (recap) console.log("Recap:", recap.text);
const page = recap
  ? await memory.listSessionEvents(sessionId, recap.summarizedUpToEventId)
  : await memory.listSessionEvents(sessionId, undefined, undefined, undefined, undefined, 20);
for (const event of page.items) console.log(event.role, event.content);
set -euo pipefail
MEMORY_API="${IRIS_AGENT_MEMORY_URL%/}/iris/data/v1/agent-memory/stores/$IRIS_AGENT_MEMORY_STORE_ID"
AUTH="Authorization: Bearer $IRIS_AGENT_MEMORY_API_KEY"

OWNER_ID=quickstart-user
SESSION_ID=travel-planning-session

RECAP=$(jq -n --arg owner "$OWNER_ID" --arg session "$SESSION_ID" '{
  filter: {
    ownerId: {eq:$owner}, sessionId: {eq:$session}, memoryType: {eq:"session_summary"}
  }, sortBy:"updatedAt", sortOrder:"DESC", limit:1
}' | curl --fail-with-body --silent --show-error -X POST "$MEMORY_API/memories/search" \
  -H "$AUTH" -H 'Content-Type: application/json' --data-binary @- | jq -c '.items[0]')

if [ "$RECAP" != "null" ]; then
  jq -r '"Recap: " + .text' <<< "$RECAP"
  CHECKPOINT=$(jq -r '.summarizedUpToEventId // empty' <<< "$RECAP")
  FILTER=()
  if [ -n "$CHECKPOINT" ]; then
    FILTER=(--data-urlencode "afterEventId=$CHECKPOINT")
  fi
else
  FILTER=(--data-urlencode 'last=20')
fi
curl --fail-with-body --silent --show-error --get "$MEMORY_API/sessions/$SESSION_ID/events" \
  -H "$AUTH" "${FILTER[@]}" | jq '.items[] | {role, content}'

The legacy memory type session_summary_view also matches these recaps. In a store with an existing custom type named session_summary, use session_summary_view to find the built-in recaps.

Try automatic summarization

These examples continue from the quickstart. Load the same .env connection values and reuse its user ID. Expand an example to copy a complete program that connects for you.

Each run repeats every write in the program. Session-event writes and memory creates with a new idempotency key add new records, so run cleanup or change the identifiers before rerunning.

Follow Configure automatic summarization. Set Summarize after to 6 and Keep most recent to 2 for this example. The retrieved session will contain a summary object and the two most recent events in events.

Add conversation turns

Add these events to the session from the quickstart to continue the conversation past the configured threshold:

turns = [
    ("assistant", "What dates are you traveling?"),
    ("user", "I arrive on October 10 and leave on October 18."),
    ("assistant", "Would you like formal or casual restaurants?"),
    ("user", "Mostly casual places near public transit."),
    ("assistant", "Do you have a preferred budget?"),
    ("user", "About 40 euros per person."),
]
for role, text in turns:
    add = conversation.user if role == "user" else conversation.assistant
    add(text)
const turns = [
  ["ASSISTANT", "What dates are you traveling?"],
  ["USER", "I arrive on October 10 and leave on October 18."],
  ["ASSISTANT", "Would you like formal or casual restaurants?"],
  ["USER", "Mostly casual places near public transit."],
  ["ASSISTANT", "Do you have a preferred budget?"],
  ["USER", "About 40 euros per person."],
] as const;
for (const [role, text] of turns) {
  await memory.addSessionEvent(SESSION_ID, {
    actorId: role === "USER" ? OWNER_ID : "travel-agent",
    role,
    content: [{ text }],
    createdAt: new Date(),
    idempotencyKey: crypto.randomUUID(),
  });
}
add_event() {  # add_event ROLE ACTOR_ID TEXT
  jq -n --arg role "$1" --arg actor "$2" --arg text "$3" \
    --arg now "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg key "$(uuidgen)" \
    '{actorId: $actor, role: $role, content: [{text: $text}], createdAt: $now, idempotencyKey: $key}' |
    curl --fail-with-body --silent --show-error \
      -X POST "$MEMORY_API/sessions/$SESSION_ID/events" -H "$AUTH" \
      -H 'Content-Type: application/json' --data-binary @- | jq -c '.event | {sessionId, eventId}'
}
add_event ASSISTANT travel-agent "What dates are you traveling?"
add_event USER "$OWNER_ID" "I arrive on October 10 and leave on October 18."
add_event ASSISTANT travel-agent "Would you like formal or casual restaurants?"
add_event USER "$OWNER_ID" "Mostly casual places near public transit."
add_event ASSISTANT travel-agent "Do you have a preferred budget?"
add_event USER "$OWNER_ID" "About 40 euros per person."

Run these writes once. Summarization runs in the background.

Retrieve the summarized session

Retrieve the session again. The examples check every 10 seconds, for up to two minutes, until a summary appears.

for _ in range(12):  # summarization runs in the background
    compacted = conversation.transcript()
    if compacted.summary:
        break
    time.sleep(10)
print("Summary:", compacted.summary)
print("Summarized up to event:", compacted.summarized_up_to)
for role, text in compacted.turns:
    print(role, text)
let summarized = await memory.getSessionMemory(SESSION_ID);
for (let attempt = 0; attempt < 11 && !summarized.summary; attempt += 1) {
  await new Promise((resolve) => setTimeout(resolve, 10_000));
  summarized = await memory.getSessionMemory(SESSION_ID);
}
console.log("Summary:", summarized.summary?.text);
console.log("Summarized up to event:", summarized.summary?.summarizedUpToEventId);
for (const event of summarized.events) console.log(event.role, event.content);
for _ in $(seq 12); do  # summarization runs in the background
  SESSION=$(curl --fail-with-body --silent --show-error \
    "$MEMORY_API/sessions/$SESSION_ID" -H "$AUTH")
  [ "$(jq '.summary != null' <<< "$SESSION")" = true ] && break
  sleep 10
done
jq '{summary, events: [.events[] | {role, content}]}' <<< "$SESSION"
iris agent-memory sessions show travel-planning-session

If summary is still missing, run the retrieval again. Compare summary.text with the recent events. The summary should preserve earlier trip decisions while recent turns remain available in full.

Note:

What to expect: A summary object that preserves details such as Tokyo, Kyoto, the travel dates, and food preferences. summarizedUpToEventId identifies the last event covered by the summary, while events contains the newer turns that remain in full. The exact summary text can vary.

RATE THIS PAGE
Back to top ↑