PostgreSQL Memory & Facts

medium10 minpostgres-memory.ts

You need long-term memory in your database: threads plus facts about the user that you can search.

What it shows

  • Store and search facts with PostgresAdapter
  • Use the postgres memory adapter for agent threads

The code

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

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

const pg = new PostgresAdapter({
  provider: 'postgres',
  connectionString,
  schema: 'cogitator_example',
  poolSize: 5,
});
const connected = await pg.connect();
if (!connected.success) throw new Error(`PostgreSQL: ${connected.error}`);

await pg.addFact({
  agentId: 'pg-demo-agent',
  content: 'User prefers concise answers under 50 words',
  category: 'preference',
  confidence: 0.95,
  source: 'user',
});
await pg.addFact({
  agentId: 'pg-demo-agent',
  content: 'User works in the fintech industry',
  category: 'profile',
  confidence: 0.8,
  source: 'inferred',
});

for (const fact of unwrap(await pg.searchFacts('pg-demo-agent', 'fintech'))) {
  console.log(`[${fact.category}] ${fact.content}`);
}
await pg.disconnect();

const cog = new Cogitator({
  llm: { providers: { google: { apiKey } } },
  memory: {
    adapter: 'postgres',
    postgres: { connectionString, schema: 'cogitator_example', poolSize: 5 },
    contextBuilder: { maxTokens: 4000, strategy: 'recent' },
  },
});

const agent = new Agent({
  name: 'pg-chatbot',
  model: 'google/gemini-3.5-flash-lite',
  instructions: 'You are an assistant with permanent memory stored in PostgreSQL. Be concise.',
  temperature: 0.3,
});

for (const input of [
  'Remember: my project deadline is March 15th and I need the Stripe and Plaid APIs.',
  'What is my deadline and which APIs do I need?',
]) {
  const result = await cog.run(agent, { input, threadId: 'pg-demo' });
  console.log(`User: ${input}\nAssistant: ${result.output}\n`);
}

await cog.close();

Run it

install · bash
pnpm add @cogitator-ai/core @cogitator-ai/memory pg
docker run -d --name postgres -p 5432:5432 -e POSTGRES_PASSWORD=cogitator postgres:16-alpine
EnvironmentGOOGLE_API_KEYDATABASE_URL=postgresql://postgres:cogitator@localhost:5432/postgres
run · bash
GOOGLE_API_KEY=your-key DATABASE_URL=postgresql://postgres:cogitator@localhost:5432/postgres npx tsx postgres-memory.ts

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

repository · bash
npx tsx examples/infrastructure/02-postgres-memory.ts

Learn more