Sessions & Remote Agents

The session system provides stateful conversation management and remote agent connectivity, enabling persistent interactions and distributed agent deployments.

Overview

Sessions provide two powerful capabilities:

  1. Stateful Local Sessions: Maintain conversation state, memory, and knowledge across interactions
  2. Remote Agent Connectivity: Connect to agents running on other machines or cloud services

Local Sessions

Basic Usage

from praisonaiagents import Session

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

Memory Integration

Sessions can maintain memory across conversations:

# Session with memory configuration
session = Session(
    session_id="chat_123",
    user_id="user_456",
    memory_config={
        "provider": "rag",
        "use_embedding": True
    }
)

# 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_config={
        "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
    memory_config={
        "provider": "rag",  # or "mem0"
        "use_embedding": True,
        "short_db": ".sessions/short_term.db",
        "long_db": ".sessions/long_term.db"
    },
    
    # Knowledge configuration
    knowledge_config={
        "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_config={"provider": "rag"}
)

Collaborative Work

Share context between team members

session = Session(
    session_id=f"project_{project_id}",
    knowledge_config={...}
)

Distributed Systems

Deploy agents across multiple servers

session = Session(
    agent_url="https://agent.region.example.com"
)

Complete Example

from praisonaiagents import Session, Task, PraisonAIAgents

# Create or restore session
session = Session(
    session_id="personal_assistant",
    user_id="john_doe",
    memory_config={
        "provider": "rag",
        "use_embedding": True
    },
    knowledge_config={
        "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