Session Management

Build stateful applications with persistent sessions and remote agent connectivity

The Session wrapper keeps state, memory, and knowledge in one place for local agents or remote HTTP endpoints.

Diagram

agent_url

Session

Local Agent

Memory

Knowledge

Remote Agent

Quick Start

python
from praisonaiagents import Session

session = Session(session_id="chat_123", user_id="user_456")

agent = session.Agent(
    name="Assistant",
    instructions="Remember our conversation history",
)

response = agent.chat("Hello! I prefer Python.")
print(response)

session.save_state({"user_preference": "Python"})

Constructor

python
Session(
    session_id: Optional[str] = None,        # auto uuid4()[:8] if None
    user_id: Optional[str] = None,            # defaults to "default_user"
    agent_url: Optional[str] = None,          # http:// auto-prefixed if missing
    memory_config: Optional[Dict[str, Any]] = None,
    knowledge_config: Optional[Dict[str, Any]] = None,
    timeout: int = 30,
    session_ttl: Optional[int] = None,       # ValueError if negative
)
ParameterDescription
session_idUnique session identifier; auto-generated when omitted
user_idUser scope for memory operations
agent_urlRemote agent URL (enables remote mode)
memory_configMemory backend config (local sessions only)
knowledge_configKnowledge backend config (local sessions only)
timeoutHTTP timeout for remote calls (seconds)
session_ttlOptional expiry in seconds

State & Memory

python
session.set_state("score", 10)
session.increment_state("score", increment=5)

session.add_memory("User prefers concise answers", memory_type="long")
results = session.search_memory("preferences")
context = session.get_context("What does the user prefer?")

session.add_knowledge("docs/guide.pdf")
MethodPurpose
save_state / restore_statePersist arbitrary dict state
get_state / set_stateSingle key access
increment_stateAtomic numeric counter helper
add_memory / search_memory / clear_memorySession-scoped memory
add_knowledge / search_knowledgeKnowledge base (local only)
get_contextBuild prompt context from memory

Session Lifecycle

python
session = Session(session_id="ttl-demo", session_ttl=3600)

if session.is_expired():
    print("Session expired")

remaining = session.time_to_expiry()  # seconds, or None

session.close()  # saves agent histories and releases resources

Remote sessions call _test_remote_connection() during init — connection failures raise before you chat.

Remote Sessions

python
session = Session(
    agent_url="192.168.1.10:8000/agent",
    session_id="remote_chat",
    timeout=30,
)

print(session.chat("Hello from a remote client"))

Memory and knowledge operations are unavailable in remote mode — run them on the agent server instead.

Related