Agent Sessions
Sessions give your Agents memory across multiple interactions. Users can have ongoing conversations, and Agents remember the context from previous messages.Agent with Session Memory
Copy
import { Agent, Session } from 'praisonai';
const session = new Session({ id: 'user-123' });
const agent = new Agent({
name: 'Support Agent',
instructions: 'You are a helpful support agent. Use conversation history for context.',
session // Agent uses this session for memory
});
// First interaction
await agent.chat('My name is John and I need help with billing');
// Agent remembers: user's name is John, topic is billing
// Later interaction (same session)
await agent.chat('What was my issue again?');
// Agent responds: "You mentioned you need help with billing, John"
Multi-Turn Conversations
Copy
import { Agent, Session, SessionManager } from 'praisonai';
const sessionManager = new SessionManager();
const agent = new Agent({
name: 'Assistant',
instructions: 'You are a helpful assistant.'
});
async function chat(userId: string, message: string) {
// Get or create session for this user
const session = sessionManager.getOrCreate(userId);
// Add user message to session
session.addMessage({ role: 'user', content: message });
// Get full conversation history for context
const history = session.getMessagesForLLM();
// Agent responds with full context
const response = await agent.chat(history);
// Save agent response to session
session.addMessage({ role: 'assistant', content: response });
return response;
}
// User conversation
await chat('user-123', 'Hi, I want to learn TypeScript');
await chat('user-123', 'What should I start with?'); // Agent remembers the topic
await chat('user-123', 'Can you give me an example?'); // Agent knows context
Agent with Persistent Sessions
Sessions that survive server restarts:Copy
import { Agent, Session, createNeonPostgres, createPostgresSessionStorage } from 'praisonai';
const db = createNeonPostgres({ connectionString: process.env.DATABASE_URL });
const sessionStorage = createPostgresSessionStorage(db);
const agent = new Agent({
name: 'Persistent Agent',
instructions: 'You remember all previous conversations.'
});
async function persistentChat(sessionId: string, message: string) {
// Load session from database
let sessionData = await sessionStorage.getSession(sessionId);
const session = new Session({ id: sessionId });
if (sessionData) {
// Restore previous messages
const messages = await sessionStorage.getMessages(sessionId);
messages.forEach(m => session.addMessage(m));
}
// Add new message
session.addMessage({ role: 'user', content: message });
// Get Agent response
const response = await agent.chat(session.getMessagesForLLM());
session.addMessage({ role: 'assistant', content: response });
// Persist to database
await sessionStorage.createSession(sessionId, { updatedAt: new Date() });
await sessionStorage.addMessage(sessionId, { role: 'user', content: message });
await sessionStorage.addMessage(sessionId, { role: 'assistant', content: response });
return response;
}
Multi-Agent Shared Sessions
Multiple Agents sharing conversation context:Copy
import { Agent, Session, Agents } from 'praisonai';
const sharedSession = new Session({ id: 'support-case-456' });
// Agent 1: Gathers information
const intakeAgent = new Agent({
name: 'Intake',
instructions: 'Gather customer information and understand their issue.',
session: sharedSession
});
// Agent 2: Provides solutions (sees intake conversation)
const solutionAgent = new Agent({
name: 'Solution Expert',
instructions: 'Review the conversation history and provide solutions.',
session: sharedSession
});
// Agent 3: Follows up (sees entire history)
const followupAgent = new Agent({
name: 'Follow-up',
instructions: 'Check if the customer is satisfied based on the conversation.',
session: sharedSession
});
// Intake gathers info
await intakeAgent.chat('I have a problem with my subscription');
await intakeAgent.chat('It keeps charging me twice');
// Solution agent sees the full context
const solution = await solutionAgent.chat('Please provide a solution for this customer');
// Follow-up agent sees everything
await followupAgent.chat('Check if the customer is satisfied');
Session with Run Tracking
Track individual Agent executions:Copy
import { Agent, Session } from 'praisonai';
const session = new Session();
const agent = new Agent({
name: 'Tracked Agent',
instructions: 'You help with various tasks.'
});
async function trackedChat(message: string) {
// Create a run for this interaction
const run = session.createRun();
run.start();
try {
session.addMessage({ role: 'user', content: message });
const response = await agent.chat(session.getMessagesForLLM());
session.addMessage({ role: 'assistant', content: response });
run.complete({ tokensUsed: 150 });
console.log(`Run ${run.id}: ${run.duration}ms`);
return response;
} catch (error) {
run.fail(error);
throw error;
}
}
// Each chat creates a trackable run
await trackedChat('Hello');
await trackedChat('Help me with code');
// View all runs
console.log(`Total runs: ${session.runs.length}`);
console.log(`Total messages: ${session.messages.length}`);
Session Context Window Management
Handle long conversations:Copy
import { Agent, Session } from 'praisonai';
const session = new Session({
id: 'long-conversation',
maxMessages: 50 // Keep last 50 messages
});
const agent = new Agent({
name: 'Context-Aware Agent',
instructions: 'You maintain context across long conversations.'
});
async function chatWithContextManagement(message: string) {
session.addMessage({ role: 'user', content: message });
// Get messages optimized for context window
const messages = session.getMessagesForLLM({
maxTokens: 4000, // Fit within context window
strategy: 'recent' // Prioritize recent messages
});
const response = await agent.chat(messages);
session.addMessage({ role: 'assistant', content: response });
return response;
}
Session Metadata
Store user and context information:Copy
import { Agent, Session } from 'praisonai';
const session = new Session({
id: 'customer-session',
metadata: {
userId: 'user-789',
customerTier: 'premium',
language: 'en',
timezone: 'America/New_York'
}
});
const agent = new Agent({
name: 'Personalized Agent',
instructions: `You are a support agent.
Check session metadata for customer context.
Premium customers get priority support.`
});
// Agent can access session metadata for personalization
const response = await agent.chat('I need help', { session });
Core Concepts
| Concept | Description |
|---|---|
| Session | Conversation container with message history |
| Run | Single Agent execution within a session |
| Trace | Detailed span within a run (LLM call, tool call) |
Related
- Memory - Semantic memory for Agents
- Redis - Fast session storage
- PostgreSQL - Persistent session storage

