> ## Documentation Index
> Fetch the complete documentation index at: https://langchat.neurobrains.co/llms.txt
> Use this file to discover all available pages before exploring further.

# UserSession

> Per-user session object that manages conversation memory and history.

## Overview

`UserSession` manages one user's conversation state. It is created automatically when `chat()` is called for the first time for a given `user_id` + `platform` combination.

Access it via `lc.get_session()`:

```python theme={null}
session = lc.get_session(user_id="alice", platform="web")
```

***

## Attributes

<ParamField path="user_id" type="str">
  The user identifier this session belongs to.
</ParamField>

<ParamField path="platform" type="str">
  The platform namespace for this session.
</ParamField>

<ParamField path="chat_history" type="list[tuple[str, str]]">
  In-memory list of `(user_message, ai_response)` tuples. Loaded from Supabase on session creation and updated after each exchange.
</ParamField>

<ParamField path="conversation" type="CustomConversationChain">
  The LangChain chain that processes messages. Handles retrieval, reranking, prompt formatting, and LLM calling.
</ParamField>

***

## Methods

### `save_message()`

Save a chat exchange to Supabase. Called automatically after `chat()` — you don't need to call this manually.

```python theme={null}
def save_message(self, query: str, response: str) -> None
```

***

## Session lifecycle

1. **Creation** — on first `chat()` call for this user + platform
2. **History loading** — recent messages loaded from Supabase
3. **Processing** — each `chat()` call passes through `session.conversation.ainvoke()`
4. **Saving** — exchange saved to Supabase in background (non-blocking)
5. **Memory update** — in-memory `chat_history` updated
6. **Eviction** — oldest exchanges dropped when `len(chat_history) > max_chat_history`

***

## Inspecting a session

```python theme={null}
session = lc.get_session("alice", "web")

# View conversation history
for query, response in session.chat_history:
    print(f"Q: {query}")
    print(f"A: {response}")
    print()

# Check session key
print(f"Session key: alice_web")
```

***

## Session caching

Sessions are cached in `LangChatEngine.sessions` as a dict:

```python theme={null}
# Key format
session_key = "{user_id}_{platform}"

# Access all active sessions
for key, session in lc.engine.sessions.items():
    print(key, len(session.chat_history))
```

After a server restart, the cache is empty — but history is reloaded from Supabase on the first `chat()` call.
