# Session Resumption

The session resumption feature lets users continue previous conversations without losing context, significantly improving the user experience.

### How it works

When a `sessionID` is provided, AIsuru automatically checks whether the session is still valid:

* **Valid session**: retrieves the conversation history and repopulates the chat, showing the Agent's last message
* **Invalid session**: creates a new session and shows the welcome message

⏰ **Important**: Sessions expire after **1 hour** of inactivity.

### Getting the sessionID

#### From the AIsuru interface

The easiest way to find a session ID:

1. Go to the \<img src="../.gitbook/assets/conversazioni.svg" alt="" data-size="line"> **Conversations** section of your Agent
2. Click \<img src="../.gitbook/assets/URL.svg" alt="" data-size="line"> **Open** for the conversation you want
3. In the **"Session information"** section, you'll find the **Session ID**

#### Via JavaScript

To programmatically retrieve an active session ID:

```javascript
javascript// Current sessionconst sessionID = getMemoriState().sessionID;// For a widget with a specific integrationIDconst sessionID = getMemoriState("my-integration-id").sessionID;
```

### Implementation

#### Web Component

```html
html<memori-client  memoriName="MyMemori"  ownerUserName="user"  tenantID="aisuru.com"  sessionID="session-uuid-to-resume"></memori-client>
```

#### React Component

```tsx
tsx<Memori  memoriName="MyMemori"  ownerUserName="user"  tenantID="aisuru.com"  sessionID="session-uuid-to-resume"/>
```

### Common use cases

#### Saving and resuming sessions

```javascript
javascript// Save sessionIDdocument.addEventListener('MemoriNewDialogState', (e) => {  const sessionID = e.detail.sessionID;  localStorage.setItem('memori-session', sessionID);});// Resume saved sessionconst savedSessionID = localStorage.getItem('memori-session');// Use savedSessionID in the component's sessionID attribute
```

#### Integration with user authentication

```javascript
javascript// Associate session with logged-in userconst userSessionKey = `memori-session-${userId}`;localStorage.setItem(userSessionKey, sessionID);// Resume session for specific userconst userSessionID = localStorage.getItem(userSessionKey);
```

### Advanced integration via API

#### 1. Retrieving Chat Logs (History)

There are two ways to retrieve past messages, depending on whether you already know the specific session or want to show the user a chronological list.

**A. Retrieve a specific session**

Use this if you already have a session ID and want to load the associated messages.

**Endpoint:** `GET /memori/v2/SessionChatLogs/{sessionID}/{chatLogSessionID}`

**Note:** passing the same ID in both parameters, the API will return the logs for that specific session.

**B. Paginated chronological list**

Use this to show the user a history of their past conversations.

* **Endpoint:** `POST /memori/v2/UserChatLogsByTokenPaged`
* **Payload Parameters (`ChatLogFilters`):**

| Parameter                | Type    | Description                                                        |
| ------------------------ | ------- | ------------------------------------------------------------------ |
| `loginToken`             | String  | User authentication token.                                         |
| `memoriID`               | String  | Unique Memori ID (Engine).                                         |
| `from`                   | Number  | Starting index for pagination.                                     |
| `howMany`                | Number  | Number of items to retrieve.                                       |
| `dateFrom` / `dateTo`    | String  | Time range (format `yyyyMMddHHmmssfff`).                           |
| `minimumMessagesPerChat` | Number  | (Optional) Minimum number of messages to include in the chat.      |
| `showChatsWithNoHistory` | Boolean | (Optional) Include sessions that were opened but have no messages. |

#### 2. Parsing the response (JSON)

Regardless of which endpoint you use, the log structure follows this schema:

```json
{
  "chatLogs": [
    {
      "chatLogID": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
      "sessionID": "session-uuid-1111-2222",
      "lines": [
        {
          "text": "Hello, how can I help you?",
          "inbound": false,
          "emitter": "assistant"
        },
        {
          "text": "I'd like info about product X",
          "inbound": true,
          "emitter": "user"
        }
      ]
    }
  ]
}
```

> **UI Integration:** use `inbound: true` for user messages and `inbound: false` for assistant messages.

#### 3. Opening a new session (resumption)

Once you've identified the conversation to continue, you need to open a new working session by injecting the past context.

**Endpoint:** `POST /memori/v2/Session`

#### Continuation options

In the request body, you can choose **one** of the two anchor parameters:

1. `continueFromChatLogID`: use the log block ID obtained in step 1.
2. `continueFromSessionID`: use the previous session ID.

> The session lasts 5 minutes.

**Example JSON Body:**

```json
{
  "memoriID": "YOUR-AGENT-ID",
  "continueFromChatLogID": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "initialContextVars": {
    "LANG": "en"
  },
  "additionalInfo": {
    "language": "en",
    "timeZoneOffset": "-120"
  }
}
```

**Result:** the backend will return a **new** `sessionID`. From this point on, all subsequent messages must use this new ID.

***

### Technical notes

* **ID targeting:** the `chatLogID` identifies the entire conversation snapshot. **Never** pass the ID of an individual message (`line`) in the continuation field.
* **Context variables:** use `initialContextVars` to pass data such as the language or current URL path; these help the engine provide contextual responses from the very first message of the resumed session.
* **Client SDK:** for strong typing of `ChatLogFilters` parameters, we recommend using the official `@memori.ai/memori-api-client` package.

### Benefits

* **Continuity of experience**: users can pick up interrupted conversations where they left off;
* **Context retention**: the Agent remembers information from the previous conversation;
* **Automatic handling**: AIsuru automatically manages expired or invalid sessions;
* **Flexibility**: compatible with all layouts and configurations.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.aisuru.com/en/frontend/session-resumption.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
