الدرس 4 · الوحدة 3: Your AI Operating System on a Private Server
Giving agents memory: storing conversations and business data in a database
الفيديو قريبًا
Learn it with your tutor on the live board
أهم نقاط الفيديو
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?"
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
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
Two kinds of memory
- Short-term: this chat's recent messages
- Long-term: your business data
- Both in one database
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
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
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
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
Recap
- Models are stateless: memory is history you resend
- Chat history in Postgres, keyed per customer
- Business data reached through safe tools
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
النص المكتوب
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?" 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 those messages and send the right ones back.
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 the history is loaded 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 mention 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.
استكشف الرسم المتحرك
الرسوم المتحركة نفسها التي في الفيديو، دقيقة وتفاعلية: شغّلها أو أوقفها، أو اسحب المؤشر، أو انتقل إلى أي خطوة بالسرعة التي تناسبك.
Loading the animation...
ملخص الدرس
- مشاهدة الفيديو
- Models are stateless: memory is history you resend
- Chat history in Postgres, keyed per customer
- Business data reached through safe tools