Skip to main content

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():
session = lc.get_session(user_id="alice", platform="web")

Attributes

user_id
str
The user identifier this session belongs to.
platform
str
The platform namespace for this session.
chat_history
list[tuple[str, str]]
In-memory list of (user_message, ai_response) tuples. Loaded from Supabase on session creation and updated after each exchange.
conversation
CustomConversationChain
The LangChain chain that processes messages. Handles retrieval, reranking, prompt formatting, and LLM calling.

Methods

save_message()

Save a chat exchange to Supabase. Called automatically after chat() — you don’t need to call this manually.
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

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:
# 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.