Lesson 4 · Module 3: Your AI Operating System on a Private Server
Giving agents memory: storing conversations and business data in a database
- Why AI agents forget by default
- How to store chat history in a database
- How agents read and write business data
Why this matters
An AI agent that forgets what a customer said two minutes ago frustrates the customer and can leak one person's details into another person's chat. Clients pay for automations that feel like a real member of staff, so this lesson shows how to give an agent memory: the saved conversation history and the business records it needs to answer correctly.
Key ideas
- Models are stateless. A language model keeps nothing between calls. It only knows the text you send in that one call, so "memory" is the history your software saves and sends again each time. Example: if you send only "Yes, book 3pm", the model has no idea what it refers to. If you send the earlier question too, it does.
- Short-term and long-term memory. Short-term memory is the recent messages of one conversation. Long-term memory is your business data, such as customers, bookings, leads and invoices, which many conversations share.
- Postgres stores both. Postgres is a free, reliable database that keeps data in tables, where each row is one record and each column is one field. n8n has Postgres nodes built in, so you can store and load data without writing much code.
- A session key keeps customers apart. A session key is a label that says whose conversation this is. Use something unique to the customer, such as their phone number or email, so each history loads only for that person.
- Tools give safe access to business data. A tool is one allowed action, such as "find booking by phone", that runs a single fixed query. The agent reads real answers from your tables instead of guessing.
Try it before you watch
A chat agent answers "Yes, book 3pm" without the earlier question in its input. Why can't it answer correctly, and what must the software do?
Show answerHide answer
The model keeps nothing between calls, so it cannot know what "3pm" refers to unless the software sends the earlier messages again. The software must load the saved history for that customer and send it along with the new message. This shows that memory is stored history that is resent, not something the model holds.
Words to know
- stateless: keeps no memory between separate requests; each call starts fresh.
- context window: the limited amount of text a model can read in one call.
- session key: a label, such as a phone number, that identifies one customer's conversation.
- table: a set of rows and columns in a database that holds one kind of data, like a spreadsheet tab.
- query: a question or instruction sent to a database to read or change data.
- tool: a single action an agent is allowed to take, such as looking up a booking.
What to watch for
- How the saved messages are loaded for one customer and then sent back with the new message.
- The session key used for each customer, and what happens when two customers share the same key.
- How the agent uses a booking tool to answer "When is my appointment?" from real data instead of guessing.
Learn it with your tutor on the live board
Key points from the video
The agent that forgets
- A customer books Friday at 3pm by chat
- Ten minutes later: "Can you move it to 4?"
- The agent asks: "Which booking?"
layout: wide
objects:
title: {text: "Beauty salon chat", pos: top}
req: {text: "Can I book Friday?", pos: top_left}
booked: {text: "Booked: Friday 3pm", pos: top_right}
msg: {text: "Can you move it to 4?", pos: [0, 1.4]}
calc: {tex: '3 + 1 = 4', pos: center}
reply: {text: "Sure, which booking?", pos: bottom_left, color: red}
pad: {text: "Empty notepad", pos: [0, -1.2]}
forget: {text: "No memory between messages", pos: [0, -2.2], color: red}
fix: {text: "Fix: give the agent memory", pos: bottom_right, color: green}
server: {text: "n8n and a database", pos: [0, -3.4]}
steps:
- at: "small beauty salon"
show: title
- at: "Can I book Friday afternoon"
show: req
- at: "confirms 3pm"
show: booked
- at: "Ten minutes later"
show: msg
- at: "one hour later"
show: calc
- at: "which booking"
show: reply
- at: "empty notepad"
show: pad
- at: "remembers nothing between messages"
show: forget
- at: "In this lesson we fix that"
show: fix
- at: "private server running n8n"
show: server What you will learn
- Why AI agents forget by default
- How to store chat history in a database
- How agents read and write business data
layout: wide
parts:
plan: {box: "This lesson", holds: [why, store, data]}
why: {chip: "Why agents forget", sub: "stateless by default"}
store: {chip: "Chat history", sub: "saved in Postgres"}
data: {chip: "Business data", sub: "leads, bookings, invoices"}
steps:
- at: "Here's the plan for this lesson"
zoom_out: plan
- at: "why AI agents forget by default"
highlight: why
- at: "store chat history in a database"
highlight: store
- at: "read and write business data"
highlight: data
- at: "a pattern you can reuse"
highlight: none Why agents forget
- Each AI call starts from zero ("stateless")
- The model only sees what you send it now
- That text window is the "context window"
- Memory = you send the history along
layout: wide
parts:
call: {box: "One model call", holds: [win, llm]}
win: {box: "Context window", holds: [old, new]}
old: {chip: "Old messages", sub: "sent again"}
new: {chip: "New message", sub: "sent now"}
llm: {chip: "Language model", sub: "keeps nothing"}
steps:
- at: "Let's slow down on one key idea"
zoom_out: win
- at: "A language model is stateless"
zoom_out: call
highlight: llm
- at: "only reads the ticket in front of him"
highlight: new
- at: "Old tickets go in the bin"
highlight: old
- at: "that text space is called the context window"
highlight: win
- at: "So the model never really remembers"
note: "Each call starts from zero"
- at: "sending the earlier messages again"
note: "Resent with each new message"
- at: "send the right messages along"
note: "Send the history along" Two kinds of memory
- Short-term: this chat's recent messages
- Long-term: your business data
- Both in one database
layout: wide
parts:
office: {box: "Agent memory", holds: [notes, cabinet, assistant]}
notes: {chip: "Sticky notes", sub: "short-term"}
cabinet: {chip: "Filing cabinet", sub: "long-term"}
assistant: {chip: "AI agent", sub: "reads both"}
steps:
- at: "Your agent needs two kinds of memory"
zoom_out: office
- at: "the sticky notes on the desk"
highlight: notes
- at: "the recent messages of one conversation"
note: "Short-term: this chat"
- at: "the filing cabinet in the corner"
highlight: cabinet
- at: "customers, bookings, leads, invoices and sales"
note: "Long-term: business data"
- at: "the assistant in the middle"
highlight: assistant
- at: "Both kinds live in the same database"
note: "One database on your server" Your database: Postgres
- Free, reliable, runs in your Docker panel
- Data lives in tables: rows and columns
- n8n has built-in Postgres nodes
- Records stored on your own server
layout: wide
parts:
pg: {box: "Postgres", holds: [tabs, rows, nodes]}
tabs: {chip: "Tables", sub: "like spreadsheet tabs"}
rows: {chip: "Rows and columns", sub: "one record per row"}
nodes: {chip: "n8n nodes", sub: "built in"}
steps:
- at: "The database we'll use is Postgres"
zoom_out: pg
- at: "installed it with one click"
note: "One click in Docker"
- at: "A database stores data in tables"
highlight: tabs
- at: "Each row is one record"
highlight: rows
- at: "n8n has Postgres nodes built in"
highlight: nodes
- at: "your clients' records are stored with you"
note: "Stored on your own server"
- at: "pick one with a suitable privacy policy"
note: "Check the privacy policy" Worked example: loading one chat
- Table customers: who they are
- Table messages: every line said
- Query: one customer's history, in order
layout: wide
tables:
customers:
columns: [id, name, phone]
rows: [[1, Sara, "555-0101"], [2, Omar, "555-0202"]]
messages:
columns: [id, customer_id, role, text]
rows: [[1, 1, user, "Book Friday?"], [2, 1, agent, "3pm is free"], [3, 2, user, "Price list?"], [4, 1, user, "Yes book 3pm"]]
query: |
SELECT m.role, m.text
FROM messages m
JOIN customers c ON m.customer_id = c.id
WHERE c.phone = '555-0101'
ORDER BY m.id
steps:
- at: "two small tables"
show: tables
- at: "our memory query"
show: query
- at: "matched by customer id"
show: join
- at: "keep only Sara's phone"
show: where
- at: "oldest message first"
show: order
- at: "exactly Sara's conversation"
show: result The memory loop in n8n
- Use the customer's phone or email as the session key
- Postgres Chat Memory node does load and save
- Set how many past messages to send
layout: full
parts:
loop: {box: "Memory loop", holds: [load, ai, save]}
load: {chip: "Load history", sub: "by phone or email"}
ai: {chip: "AI Agent", sub: "history and message"}
save: {chip: "Save both", sub: "back to Postgres"}
steps:
- at: "A customer message arrives"
zoom_out: loop
note: "Customer message arrives"
- at: "Then we load the history"
highlight: load
- at: "says whose conversation this is"
note: "Phone or email as the key"
- at: "The AI Agent node gets the history"
highlight: ai
- at: "both messages are saved back to Postgres"
highlight: save
- at: "how many past messages to send"
note: "How many past messages"
- at: "The Postgres Chat Memory node does the loading"
note: "Postgres Chat Memory node"
- at: "type in the session key"
highlight: none The same idea in Python
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE chat(session, role, text)")
def save(session, role, text):
db.execute("INSERT INTO chat VALUES (?,?,?)",
(session, role, text))
def load(session, last=4):
rows = db.execute(
"SELECT role, text FROM chat WHERE session=?"
" ORDER BY rowid DESC LIMIT ?", (session, last))
return list(reversed(rows.fetchall()))
save("sara", "user", "Can I book Friday?")
save("sara", "agent", "Yes, 3pm is free.")
save("omar", "user", "Send my invoice.")
save("sara", "user", "Great, book 3pm.")
for role, text in load("sara"):
print(role, ":", text) Business data as tools
- Give the agent tools: "find booking", "add lead"
- Each tool runs one safe database query
- The agent decides when to call them
- Facts come from tables, not from guesses
layout: wide
parts:
kit: {box: "Your agent", holds: [tool, db, fact]}
tool: {chip: "Find booking", sub: "one fixed query"}
db: {chip: "Bookings table", sub: "your real data"}
fact: {chip: "Real answer", sub: "never a guess"}
steps:
- at: "Chat history is only half of memory"
zoom_out: kit
- at: "agents reach it through tools"
note: "Agents use tools"
- at: "find booking by phone"
highlight: tool
- at: "with one fixed query"
note: "One fixed query per tool"
- at: "Safe means the agent"
note: "Only that query"
- at: "reads the real answer"
highlight: fact
- at: "from the bookings table"
highlight: db
- at: "invent a time that sounds right"
note: "No invented times"
- at: "come from your tables"
highlight: none
note: "Facts from your tables" Common mistake: one shared memory
- Same session key for every customer
- Sara's booking shows up in Omar's chat
- Fix: unique key per customer, never fixed text
- Test with two customers before going live
layout: wide
parts:
shared: {box: "One shared memory", holds: [key, sara, omar]}
key: {chip: "Fixed key: chat", sub: "same for everyone"}
sara: {chip: "Sara's booking", sub: "Friday 3pm"}
omar: {chip: "Omar's chat", sub: "his own chat"}
steps:
- at: "Here's the mistake that catches many beginners"
highlight: none
note: "Common mistake"
- at: "fixed text"
highlight: key
- at: "Now every customer shares one memory"
zoom_out: shared
note: "One memory for everyone"
- at: "Omar writes in"
highlight: omar
- at: "Sara's Friday booking"
highlight: sara
- at: "privacy problem for your client"
note: "A privacy problem"
- at: "something unique to the customer"
highlight: none
note: "Unique key per customer"
- at: "two different customers"
note: "Test with two customers" Recap
- Models are stateless: memory is history you resend
- Chat history in Postgres, keyed per customer
- Business data reached through safe tools
layout: wide
parts:
recap: {box: "Three takeaways", holds: [stateless, store, tools]}
stateless: {chip: "Stateless model", sub: "resend the history"}
store: {chip: "Chat in Postgres", sub: "one key per customer"}
tools: {chip: "Safe tools", sub: "business tables"}
steps:
- at: "Let's wrap up with three takeaways"
zoom_out: recap
- at: "AI models are stateless"
highlight: stateless
- at: "send back with each message"
note: "Resend the history each time"
- at: "keep chat history in Postgres"
highlight: store
- at: "unique session key per customer"
note: "One key per customer"
- at: "give your agent tools"
highlight: tools
- at: "come from real data instead of guesses"
note: "Real data, not guesses"
- at: "real member of the team"
highlight: none
note: "A real member of the team" Your exercise
- Build a chat agent in n8n with Postgres Chat Memory
- Session key: the customer's phone number
- Chat as two customers, five messages each
- Confirm no details leak between them
- Check the saved rows in n8n_chat_histories
layout: wide
parts:
ex: {box: "Your exercise", holds: [build, test, rows]}
build: {chip: "Chat agent", sub: "n8n with Postgres memory"}
test: {chip: "Sara and Omar", sub: "two chats"}
rows: {chip: "Saved rows", sub: "in the database"}
steps:
- at: "Now it's your turn"
zoom_out: ex
- at: "build a simple chat agent"
highlight: build
- at: "Use the customer's phone number"
note: "Session key: phone number"
- at: "open two chats, one as Sara and one as Omar"
highlight: test
- at: "send about five messages from each"
note: "About five each"
- at: "Does the agent remember what each person said earlier"
note: "Remembers each person"
- at: "never leak one customer's details"
note: "No leaks between them"
- at: "look at the saved rows"
highlight: rows
- at: "called n8n chat histories"
note: "n8n chat histories"
- at: "let agents answer from your own documents"
highlight: none
note: "Next: your own documents" Transcript
The agent that forgets. Picture a small beauty salon with an AI agent answering its chat. A customer writes, "Can I book Friday afternoon?" The agent finds a slot and confirms 3pm. Ten minutes later the same customer writes, "Actually, can you move it to 4?" That's one hour later, so 3 plus 1 equals 4. And the agent answers, "Sure, which booking do you mean?" To the customer, that feels broken, and they're right. The agent has an empty notepad. It remembers nothing between messages. In this lesson we fix that. You already have a private server running n8n and a database from the last lesson. Now we'll connect them so your agents remember conversations and know your business data.
What you will learn. Here's the plan for this lesson. First, you'll understand why AI agents forget by default, because once you see the reason, the fix makes sense. Second, you'll learn how to store chat history in a database, so every customer's conversation is saved and loaded back the next time they write. Third, you'll learn how agents read and write business data, like leads, bookings and invoices, so they can answer real questions such as "when is my appointment?" By the end, you'll have a pattern you can reuse for every client automation you build and sell.
Why agents forget. Let's slow down on one key idea. A language model is stateless. That's a plain word for "it keeps nothing between calls." Think of a waiter who only reads the ticket in front of him. Old tickets go in the bin. Whatever text you send in one call is all the model sees, and that text space is called the context window. So the model never really remembers. When a chatbot seems to remember, the software around it is quietly sending the earlier messages again with each new one. That's our job: store that history and send the right messages along.
Two kinds of memory. Your agent needs two kinds of memory, and this office shows both. First, the sticky notes on the desk. That's short-term memory, the recent messages of one conversation, like "the customer wants Friday at 3pm." It's small and changes every minute. Next, the filing cabinet in the corner. That's long-term memory, your business data: customers, bookings, leads, invoices and sales. It stays for months and many conversations use it. And finally the assistant in the middle, your AI agent, glancing at the notes and opening the right drawer when it needs a fact. Both kinds live in the same database on your server.
Your database: Postgres. The database we'll use is Postgres, short for PostgreSQL. It's free, very reliable, and you installed it with one click in your Docker panel last lesson. A database stores data in tables, which work like spreadsheet tabs. Each row is one record, like one message or one booking, and each column is one field, like the customer's phone number or the message text. n8n has Postgres nodes built in, so you won't write much code. And because it runs on your own server, your clients' records are stored with you, not in a third-party database. The messages you send to the AI model still go to its provider, so pick one with a suitable privacy policy, or use a self-hosted model.
Worked example: loading one chat. Let's see memory in action with two small tables. Customers holds who people are, and messages holds every line said in the chat, by the user or by the agent. Here's our memory query, the question we ask the database. First the messages are matched by customer id, so each line knows who wrote it. Next we keep only Sara's phone number, so Omar's price question drops out. Then we sort with the oldest message first, because the model needs the story in order. The result is exactly Sara's conversation, ready to send to the agent with her new message.
The memory loop in n8n. In n8n, this whole loop is a few nodes. A customer message arrives from WhatsApp, email or your website. Then we load the history using a session key. A session key is just a label that says whose conversation this is, and the customer's phone number or email works perfectly. The AI Agent node gets the history plus the new message, writes a reply, and then both messages are saved back to Postgres. In the node you also set how many past messages to send, so the context window does not overflow. The Postgres Chat Memory node does the loading and saving for you, so you just connect it to the agent and type in the session key.
The same idea in Python. If you like to see what's under the hood, here's the same memory in a few lines of Python. We use SQLite, a tiny database built into Python, so it runs anywhere, but the idea is identical in Postgres. The save function writes one line with its session key. The load function fetches the last few lines for one session, newest first, then flips them back into time order. We save three lines from Sara and one from Omar. When we load Sara's session, only her three lines come back, in order. Omar's invoice request stays out of her conversation.
Business data as tools. Chat history is only half of memory. The other half is your business data, and agents reach it through tools. A tool is a small action you allow the agent to take, like "find booking by phone" or "add new lead." In n8n, each tool is a Postgres node with one fixed query; only the value, like the phone number, changes each time. Safe means the agent can only run that query, never delete or change other data. When a customer asks, "When's my appointment?", the agent calls the find booking tool and reads the real answer from the bookings table. That matters, because without a tool the model might invent a time that sounds right. Facts should always come from your tables.
Common mistake: one shared memory. Here's the mistake that catches many beginners. They set the session key to fixed text, like "chat", while testing, and forget to change it. Now every customer shares one memory. Omar writes in and the agent mentions Sara's Friday booking, or worse, her phone number and booking time. That's a privacy problem for your client, not just a bug. The fix is simple: always build the session key from something unique to the customer, like their phone number or email. And before going live, test with two different customers and check that neither one ever sees the other's details.
Recap. Let's wrap up with three takeaways. First, AI models are stateless, so memory is really the history you store and send back with each message. Second, keep chat history in Postgres on your own server, with a unique session key per customer, so every conversation stays separate. Third, give your agent tools that run safe queries on your business tables, so answers about bookings, leads and invoices come from real data instead of guesses. With these three pieces, your agent stops feeling forgetful and starts feeling like a real member of the team.
Your exercise. Now it's your turn. In n8n on your server, build a simple chat agent for a pretend salon or small shop, and connect a Postgres Chat Memory node to it. Use the customer's phone number as the session key. Then open two chats, one as Sara and one as Omar, and send about five messages from each, including a booking request. Check two things. Does the agent remember what each person said earlier? And does it never leak one customer's details to the other? Then open Postgres and look at the saved rows in the table n8n creates for you, called n8n chat histories. Next lesson, we'll let agents answer from your own documents.
Explore the animations
The animations from the video, exact and live: play them, pause, drag the slider or jump to a step at your own pace.
Loading the animation...
Loading the animation...
Loading the animation...
Loading the animation...
Loading the animation...
Loading the animation...
Loading the animation...
Loading the animation...
Loading the animation...
Loading the animation...
Loading the animation...
Answer every question, then check. 70% passes; you can retry as often as you like.
Lesson summary
- Reading
- Video watched
- Quiz passed (70%)
- Models are stateless: memory is history you resend
- Chat history in Postgres, keyed per customer
- Business data reached through safe tools