How sessions work
Everychat() call is tied to a user_id and an optional platform. Together they form a session key:
UserSession per key. Within a session:
- The last N exchanges are kept in memory (default: 20, configured via
max_chat_history) - Full history is loaded from Supabase when the session is first accessed
- Each new exchange is saved to Supabase in the background (non-blocking)
user_id
Identifies the person chatting. Use any stable, unique identifier — a database UUID, an email address, or a session token.user_id has its own isolated conversation history. User A never sees User B’s messages.
platform
Groups conversations by application or context. Use it when multiple apps or surfaces share the same LangChat backend.platform, it defaults to "default".
History window
max_chat_history controls how many past exchanges are included in each prompt. One exchange = one user message + one AI response.
| Setting | Context quality | Token cost | Speed |
|---|---|---|---|
| Higher (e.g. 50) | Better memory of the conversation | Higher | Slower |
| Lower (e.g. 5) | May forget earlier context | Lower | Faster |
| Default (20) | Good balance | Moderate | Normal |
Get a session object
Access the underlyingUserSession directly if you need to inspect or manipulate it:
How history is loaded
When you first callchat() for a user:
- LangChat checks the in-memory session cache — if the session exists, it uses that
- If not, it creates a new
UserSessionwhich loads recent messages from Supabase - The loaded history is stored in memory for subsequent calls
Database schema
Chat history is stored in thechat_history table:
| Column | Type | Description |
|---|---|---|
id | bigint | Auto-incrementing primary key |
user_id | text | User identifier |
platform | text | Platform namespace (default: "default") |
message | text | User’s message |
response | text | AI’s response |
created_at | timestamptz | UTC timestamp |
Multi-tenant isolation
When running LangChat as a shared API, conversations are naturally isolated because:- Each
user_id+platformcombination is a separate session - History queries always filter by both
user_idandplatform - In-memory session cache is keyed by
"{user_id}_{platform}"
