Skip to main content
Sessions enable agents to remember conversations across restarts and connect to remote agents.

Quick Start with Agent

The simplest way to use sessions is with the Agent class:
from praisonaiagents import Agent

# Create agent with session persistence
agent = Agent(
    name="Assistant",
    instructions="You are a helpful assistant",
    memory={"session_id": "my-session-123"}
)

# First conversation
agent.start("My name is Alice")

# Later, in a new process - history restored automatically!
agent = Agent(
    name="Assistant",
    instructions="You are a helpful assistant",
    memory={"session_id": "my-session-123"}
)
agent.start("What's my name?")  # Remembers: "Alice"

Using the Session Class

For advanced control over memory and knowledge, use the Session class:
from praisonaiagents import Session

# Create a session
session = Session(
    session_id="chat_123",
    user_id="user_456"
)

# Create agent within session context
agent = session.Agent(
    name="Assistant",
    instructions="You are a helpful assistant"
)

Memory Integration

Sessions can maintain memory across conversations:
# Session with memory configuration
session = Session(
    session_id="chat_123",
    user_id="user_456",
    memory=True  # Enable memory with defaults
)

# Add memories directly
session.add_memory("User prefers technical explanations")

# Search memories
memories = session.search_memory("preferences")

# Agent automatically uses session memory
agent = session.Agent(name="Assistant", memory=True)

Knowledge Integration

Attach knowledge bases to sessions:
# Session with knowledge
session = Session(
    session_id="research_session",
    user_id="researcher_1",
    knowledge={
        "vector_store": {
            "provider": "chroma",
            "config": {"collection_name": "research_docs"}
        }
    }
)

# Add knowledge to session
session.add_knowledge("research_paper.pdf")
session.add_knowledge("Important finding: AI improves efficiency by 40%")

# Search knowledge
results = session.search_knowledge("efficiency improvements")

# Agents use session knowledge
agent = session.Agent(
    name="Research Assistant",
    knowledge=True
)

Remote Agents

Connecting to Remote Agents

Remote agents follow the Google ADK (Agent Development Kit) pattern for standardised communication.
from praisonaiagents import Session

# Connect to remote agent
session = Session(
    agent_url="http://192.168.1.10:8000/agent"
)

Remote Agent Server

Create an agent server for remote access:
# remote_agent_server.py
from flask import Flask, request, jsonify
from praisonaiagents import Agent

app = Flask(__name__)

# Create your agent
agent = Agent(
    name="Remote Assistant",
    instructions="You are a helpful remote assistant.",
    tools=[...],  # Your tools
    memory=True
)

@app.route('/agent', methods=['POST'])
def handle_message():
    data = request.json
    message = data.get('message', '')
    session_id = data.get('session_id')
    
    # Process message
    response = agent.chat(message, session_id=session_id)
    
    return jsonify({
        'content': response,
        'session_id': session_id,
        'metadata': {
            'agent_name': agent.name,
            'timestamp': datetime.now().isoformat()
        }
    })

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000)

Session Configuration

Local Session Options

session = Session(
    # Required
    session_id="unique_session_id",
    
    # Optional
    user_id="user_identifier",
    
    # Memory configuration (use memory= consolidated param)
    memory=True,  # Enable memory with defaults
    
    # Knowledge configuration
    knowledge={
        "vector_store": {
            "provider": "chroma",
            "config": {
                "collection_name": "session_knowledge",
                "path": ".sessions/knowledge"
            }
        }
    }
)

Remote Session Options

session = Session(
    # Remote agent URL
    agent_url="https://api.example.com/agent",
    
    # Optional timeout (default: 30 seconds)
    timeout=60,
    
    # Optional headers for authentication
    headers={
        "Authorization": "Bearer token",
        "X-API-Key": "api_key"
    }
)

State Management

Saving Session State

# Save current state
session.save_state()

# State includes:
# - Session metadata
# - Memory contents
# - Knowledge references
# - Agent configurations

Restoring Session State

# Create new session instance
session = Session(session_id="chat_123")

# Restore previous state
session.restore_state()

# Continue where you left off
agent = session.Agent(name="Assistant")
response = agent.chat("What were we discussing?")

State Persistence Location

By default, session state is saved to:
  • .sessions/{session_id}/state.json - Session metadata
  • .sessions/{session_id}/memory/ - Memory databases
  • .sessions/{session_id}/knowledge/ - Knowledge databases

Advanced Features

Session Context

Access session context programmatically:
# Get session context
context = session.get_context()
print(f"Session ID: {context['session_id']}")
print(f"User ID: {context['user_id']}")
print(f"Created: {context['created_at']}")
print(f"Messages: {context['message_count']}")

Multi-Agent Sessions

Use multiple agents within a session:
session = Session(session_id="team_session")

# Create multiple agents in session
researcher = session.Agent(
    name="Researcher",
    instructions="You research topics"
)

writer = session.Agent(
    name="Writer", 
    instructions="You write content"
)

# Agents share session memory and knowledge
research = researcher.chat("Research AI trends")
article = writer.chat("Write an article about the research")

Session Middleware

Add custom middleware to sessions:
def logging_middleware(message, response):
    print(f"[{datetime.now()}] Message: {message}")
    print(f"[{datetime.now()}] Response: {response[:100]}...")
    return response

session = Session(
    session_id="logged_session",
    middleware=[logging_middleware]
)

Use Cases

Customer Support

Maintain conversation history across support interactions
session = Session(
    session_id=f"support_{ticket_id}",
    user_id=customer_id
)

Personal Assistants

Remember user preferences and past interactions
session = Session(
    session_id=f"assistant_{user_id}",
    memory={"provider": "rag"}
)

Collaborative Work

Share context between team members
session = Session(
    session_id=f"project_{project_id}",
    knowledge={...}
)

Distributed Systems

Deploy agents across multiple servers
session = Session(
    agent_url="https://agent.region.example.com"
)

Complete Example

from praisonaiagents import Session, Task, AgentTeam

# Create or restore session
session = Session(
    session_id="personal_assistant",
    user_id="john_doe",
    memory={
        "provider": "rag",
        "use_embedding": True
    },
    knowledge={
        "vector_store": {
            "provider": "chroma",
            "config": {"collection_name": "personal_docs"}
        }
    }
)

# Try to restore previous state
try:
    session.restore_state()
    print("Restored previous session")
except:
    print("Starting new session")

# Create session agent
assistant = session.Agent(
    name="Personal Assistant",
    instructions="""You are a personal assistant that remembers everything.
    Use your memory and knowledge to provide personalised help.""",
    memory=True,
    knowledge=True
)

# Add some knowledge
session.add_knowledge("calendar.pdf")
session.add_memory("User prefers morning meetings")

# Have a conversation
response = assistant.chat("Schedule a meeting for tomorrow")
print(response)

# Save state for next time
session.save_state()

Best Practices

Session Management

  • Use meaningful session IDs
  • Clean up old sessions periodically
  • Implement session expiry policies

State Handling

  • Save state after important interactions
  • Implement regular auto-save
  • Handle restore failures gracefully

Remote Connections

  • Implement proper error handling
  • Use timeouts for remote calls
  • Add retry logic for failures

Security

  • Validate session IDs
  • Implement authentication for remote agents
  • Encrypt sensitive session data

Next Steps