createShortTermMemory
Problem
In LangChain agents, conversation history is usually a plain array you manage manually — pushing messages, slicing old ones, passing it around between functions. There is no standard interface, so every project does it differently and bugs creep in.
Solution
createShortTermMemory creates a typed in-memory message store for the duration of a session. It gives you a clean API to add, read, and clear messages — so your conversation management is consistent and explicit across your Node.js application.
Feature & Use-Case
Use createShortTermMemory when:
- You need per-session conversation history (one object per user, per request, per thread)
- You want a clean API instead of pushing to raw arrays
- You are building a chat agent or multi-turn assistant where messages accumulate in-memory
- You do not need persistence across restarts — for that, use
createLongTermMemory
Import
import { createShortTermMemory } from "llm-layer-engine";Function Signature
function createShortTermMemory(): ShortTermMemoryShortTermMemory Interface
interface ShortTermMemory {
add(message: Message): void;
addMany(messages: Message[]): void;
getAll(): Message[];
clear(): void;
size(): number;
}Method Reference
| Method | Description |
|---|---|
add(message) | Add a single message to memory |
addMany(messages) | Add multiple messages at once |
getAll() | Return a copy of all stored messages |
clear() | Remove all messages from memory |
size() | Return the current message count |
Example — Chat Session with Memory
import { createShortTermMemory, createAgent } from "llm-layer-engine";
import type { LLMProvider } from "llm-layer-engine";
const memory = createShortTermMemory();
const agent = createAgent({ provider: myProvider, model: "claude-3-5-sonnet-20241022" });
// Turn 1 — User sends first message
memory.add({ role: "user", content: "My name is Burhan." });
let { result } = await agent.run(memory.getAll());
memory.add({ role: "assistant", content: result });
// Turn 2 — User asks a follow-up
memory.add({ role: "user", content: "What is my name?" });
({ result } = await agent.run(memory.getAll()));
memory.add({ role: "assistant", content: result });
console.log(result); // → "Your name is Burhan."
console.log(memory.size()); // → 4Example — Reset Memory Between Sessions
const memory = createShortTermMemory();
// Session A
memory.add({ role: "user", content: "Hello from session A" });
console.log(memory.size()); // 1
// End session — clear before next user
memory.clear();
console.log(memory.size()); // 0Conclusion
createShortTermMemory keeps your conversation history clean and typed. Create one instance per session, feed memory.getAll() into every agent call, and call memory.clear() when the session ends. It is the simplest way to build a stateful chat agent in your Node.js + LangChain project.