Skip to main content

Chat History Example

Memory allows your agent to remember previous interactions. This example demonstrates how to use the BufferMemory provider to maintain context across multiple runs using sessions.

What You’ll Learn

  • How to set up memory for your agent
  • How to use sessions to maintain conversation context
  • How to access and inspect conversation history
  • How memory works across multiple agent runs

Complete Code

import 'dotenv/config'

import { createAgent, AgentInstance } from '@agentlib/core'
import { openai } from '@agentlib/openai'
import { BufferMemory } from '@agentlib/memory'
import { createLogger } from '@agentlib/logger'

/**
 * Chat History Example
 * 
 * This example demonstrates how to use the MemoryProvider to maintain
 * context across multiple runs using sessions.
 */

async function main() {
    // 1. Initialize Memory
    // BufferMemory keeps history in-process. 
    // In a real app, you might use a Redis or Database provider.
    const memory = new BufferMemory({
        maxMessages: 10 // Keep last 10 messages
    })

    // 2. Setup the Agent
    const agent = createAgent({
        name: 'memory-demo-agent',
        systemPrompt: "You are a friendly assistant. Remember the user's name and preferences.",
    })
        .provider(openai({
            apiKey: process.env['OPENAI_API_KEY'] ?? '',
            model: process.env['OPENAI_MODEL'] ?? 'gpt-4o-mini'
        }))
        .memory(memory)
        .use(createLogger({ level: 'info' }))

    const sessionId = 'user-session-123'

    console.log('--- Conversation Start ---\n')

    // First Turn: Introduce ourselves
    console.log('> User: Hi! My name is Sammy and I love coding in TypeScript.')
    const res1 = await agent.run({
        input: 'Hi! My name is Sammy and I love coding in TypeScript.',
        sessionId
    })
    console.log(`\nAgent: ${res1.output}\n`)

    // Second Turn: Ask a follow-up without repeating the context
    console.log('> User: What is my favorite language?')
    const res2 = await agent.run({
        input: 'What is my favorite language?',
        sessionId
    })
    console.log(`\nAgent: ${res2.output}\n`)

    // Third Turn: Ask about the name
    console.log('> User: Do you remember my name?')
    const res3 = await agent.run({
        input: 'Do you remember my name?',
        sessionId
    })
    console.log(`\nAgent: ${res3.output}\n`)

    console.log('--- Inspecting Memory ---')
    const entries = await memory.entries(sessionId)
    console.log(`Messages in session "${sessionId}":`, entries[0]?.messages.length)

    console.log('\n--- Conversation End ---')
}

main().catch(console.error)

Code Breakdown

1. Initialize Memory

Create a memory provider to store conversation history:
const memory = new BufferMemory({
    maxMessages: 10 // Keep last 10 messages
})
BufferMemory stores messages in-process (in memory). For production applications, consider:
  • RedisMemory: Store in Redis for distributed systems
  • DatabaseMemory: Store in a database for persistence
  • Custom Memory: Implement your own MemoryProvider

2. Add Memory to Agent

Attach the memory provider to your agent:
const agent = createAgent({
    name: 'memory-demo-agent',
    systemPrompt: "You are a friendly assistant. Remember the user's name and preferences.",
})
    .provider(openai({ apiKey: process.env['OPENAI_API_KEY'], model: 'gpt-4o-mini' }))
    .memory(memory) // Attach memory

3. Use Sessions

Sessions group related conversations. Use a consistent sessionId across runs:
const sessionId = 'user-session-123'

// First run
const res1 = await agent.run({
    input: 'Hi! My name is Sammy and I love coding in TypeScript.',
    sessionId // Same session ID
})

// Second run - agent remembers the first run
const res2 = await agent.run({
    input: 'What is my favorite language?',
    sessionId // Same session ID
})
// Agent will remember: "TypeScript"

4. Conversation Flow

Here’s what happens in the example: Turn 1:
User: Hi! My name is Sammy and I love coding in TypeScript.
Agent: Hi Sammy! It's great to meet you. TypeScript is an excellent choice...
Memory stores: user message + agent response Turn 2:
User: What is my favorite language?
Agent: Your favorite language is TypeScript!
The agent has context from Turn 1 and knows the answer. Turn 3:
User: Do you remember my name?
Agent: Yes, your name is Sammy!
The agent recalls information from Turn 1.

5. Inspect Memory

Access stored conversation history:
const entries = await memory.entries(sessionId)
console.log('Messages in session:', entries[0]?.messages.length)
Each entry contains:
  • messages: Array of conversation messages
  • metadata: Custom data associated with the session

Memory Strategies

Buffer Memory (Simple)

Keeps the last N messages:
const memory = new BufferMemory({
    maxMessages: 10 // Keep last 10 messages
})
Pros: Simple, fast Cons: Limited context window

Sliding Window Memory

Keeps recent messages within a token limit:
import { SlidingWindowMemory } from '@agentlib/memory'

const memory = new SlidingWindowMemory({
    maxTokens: 4000 // Keep messages within 4000 tokens
})
Pros: Token-aware, prevents context overflow Cons: May lose important early context

Summarizing Memory

Summarizes old messages to save space:
import { SummarizingMemory } from '@agentlib/memory'

const memory = new SummarizingMemory({
    maxMessages: 20,
    summarizeAfter: 15 // Summarize when > 15 messages
})
Pros: Retains important information long-term Cons: Summarization uses extra tokens/time

Multi-User Applications

Use unique session IDs per user:
const userSessionId = `user-${userId}`

await agent.run({
    input: userMessage,
    sessionId: userSessionId
})
Each user gets independent conversation history.

Clearing History

Clear a session when needed:
await memory.clear(sessionId)
Or clear all sessions:
await memory.clearAll()

Example Output

Running the example produces:
--- Conversation Start ---

> User: Hi! My name is Sammy and I love coding in TypeScript.

Agent: Hi Sammy! It's great to meet you. TypeScript is an excellent choice 
for building robust applications. What brings you here today?

> User: What is my favorite language?

Agent: Your favorite language is TypeScript!

> User: Do you remember my name?

Agent: Yes, your name is Sammy!

--- Inspecting Memory ---
Messages in session "user-session-123": 6

--- Conversation End ---
Notice how the agent remembers:
  • The user’s name (Sammy)
  • The user’s favorite language (TypeScript)
  • All information from previous turns

Next Steps

Build docs developers (and LLMs) love