Redis Memory

easy10 minredis-memory.ts

Conversations must survive restarts and be shared by several server instances.

What it shows

  • Configure the redis memory adapter with a key prefix and TTL

The code

redis-memory.ts
import { Agent, Cogitator } from '@cogitator-ai/core';
import { unwrap } from '@cogitator-ai/memory';

const apiKey = process.env.GOOGLE_API_KEY;
const redisUrl = process.env.REDIS_URL;
if (!apiKey || !redisUrl) throw new Error('Set GOOGLE_API_KEY and REDIS_URL');

const cog = new Cogitator({
  llm: { providers: { google: { apiKey } } },
  memory: {
    adapter: 'redis',
    redis: { url: redisUrl, keyPrefix: 'cogbot:', ttl: 7200 },
    contextBuilder: { maxTokens: 4000, strategy: 'recent' },
  },
});

const agent = new Agent({
  name: 'redis-chatbot',
  model: 'google/gemini-3.5-flash-lite',
  instructions: 'You are a helpful assistant with persistent memory. Be concise.',
  temperature: 0.3,
});

const threadId = 'redis-demo';

for (const input of [
  'My name is Jordan and I work at a startup called NovaTech.',
  "What's my name and where do I work?",
]) {
  const result = await cog.run(agent, { input, threadId });
  console.log(`User: ${input}\nAssistant: ${result.output}\n`);
}

if (cog.memory) {
  const stored = unwrap(await cog.memory.getEntries({ threadId }));
  console.log(`${stored.length} messages in Redis — run again and the agent still remembers.`);
}

await cog.close();

Run it

install · bash
pnpm add @cogitator-ai/core @cogitator-ai/memory ioredis
docker run -d --name redis -p 6379:6379 redis:7-alpine
EnvironmentGOOGLE_API_KEYREDIS_URL=redis://localhost:6379
run · bash
GOOGLE_API_KEY=your-key REDIS_URL=redis://localhost:6379 npx tsx redis-memory.ts

Or run the full example from a clone of the repository (keys in .env):

repository · bash
npx tsx examples/infrastructure/01-redis-memory.ts

Learn more