惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Know Your Adversary
Know Your Adversary
小众软件
小众软件
L
LangChain Blog
月光博客
月光博客
博客园 - Franky
Microsoft Azure Blog
Microsoft Azure Blog
Y
Y Combinator Blog
有赞技术团队
有赞技术团队
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
MongoDB | Blog
MongoDB | Blog
Recorded Future
Recorded Future
V
Visual Studio Blog
TaoSecurity Blog
TaoSecurity Blog
S
Schneier on Security
C
Cybersecurity and Infrastructure Security Agency CISA
P
Privacy & Cybersecurity Law Blog
T
Threat Research - Cisco Blogs
D
DataBreaches.Net
L
LINUX DO - 热门话题
C
Check Point Blog
F
Fortinet All Blogs
Hugging Face - Blog
Hugging Face - Blog
The Hacker News
The Hacker News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Microsoft Security Blog
Microsoft Security Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
V
V2EX
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
The GitHub Blog
The GitHub Blog
P
Proofpoint News Feed
L
Lohrmann on Cybersecurity
博客园 - 司徒正美
T
Threatpost
P
Palo Alto Networks Blog
A
About on SuperTechFans
Spread Privacy
Spread Privacy
Engineering at Meta
Engineering at Meta
N
News | PayPal Newsroom
T
Tailwind CSS Blog
The Last Watchdog
The Last Watchdog
Blog — PlanetScale
Blog — PlanetScale
A
Arctic Wolf
量子位
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
博客园 - 聂微东
Google Online Security Blog
Google Online Security Blog
Google DeepMind News
Google DeepMind News
www.infosecurity-magazine.com
www.infosecurity-magazine.com
V
Vulnerabilities – Threatpost
H
Hacker News: Front Page

Towards AI

Building AI Agents in Rust — part 4 | Towards AI Building AI Agents in Rust — part 5 | Towards AI The Verified Identity Agent Bridge | Towards AI You Can’t Prompt Your Away Your LLM Problems | Towards AI The Free Agent Trap | Towards AI Your Agentic Loop Will Drift. Here Is the KL Divergence Equation That Measures How Far It Has Wandered From Its Original Instruction. | Towards AI Beyond Chat: Processing Images, PDFs, and Documents with the OpenAI Adapter in Oracle Integration Cloud | Towards AI Building AI Agents in Rust — part 3 | Towards AI Self-Hosting Airflow at Home: Automating Stock Price Data Collection | Towards AI The 76-Hour Frontier: How the Takedown of Claude Fable 5 Birthed the Military-Industrial-AI Complex | Towards AI I Trained a Markdown File to Boost GPT-5.5 by 23 Points — It Shouldn't Work | Towards AI We Replaced ChatGPT With a Local AI Server. Six Months of Honest Data. | Towards AI What Really Makes Cars Pollute? A Data Science Deep Dive into CO₂ Emissions | Towards AI Training GPT-2 From Scratch on a GTX1050 | Towards AI Principal Component Analysis (PCA): Theory, Mathematics, and Applications Build a Zero-Cost Web Automation Pipeline With OpenRouter, OpenClaw, and MediaUse I Gave Qwen3.7-Plus a Screenshot and It Found the Exact Pixel to Click for $0.40 Beyond the Prompt: Why Autonomous AI Agents Are Replacing the Chatbot Moonshot Cracked Claude Code’s Playbook with an MIT Terminal Agent and a $0.60 Model Connections, Roles, and Warehouses: Getting CoCo Desktop Production-Ready from Day One My First $5,000 Month Writing About AI Engineering on Medium Google Shrank Gemma 4 by 72% and Unsloth Fixed the 4-Bit Bug Nobody Else Caught on One 4090, and 4-Bit Shouldn’t Be This Good LangChain Explained: Understanding Models, Prompts, Chains, Memory, Indexes, and Agents TOON: Beyond JSON for LLMs Claude Code Casual, Pro, Elite: The Three Working Personas of Claude Code Mastery MiniMax M3 Decodes 1M Tokens 15x Faster — and It Shouldn’t Be This Cheap Using Amazon SQS for AI Agent Orchestration I Ran a 1.5B-Active Model on My Laptop That Embarrassed a 26B by 46 Points How to Build a Self-Improving Company with AI Part 3 — Implementation/Engine-Level: Choosing the Runtime That Gives You These for Free Part 2 — Serve-Level Speed: System Design That Stabilizes P95/P99 3-Part Series: LLM Latency in Production (Part 1) Claude Code: The AI Coding Partner Changing How Developers Build Software Claude Code Pitfalls: Claude Code Won’t Do What You Told It: A Troubleshooting Catalog Full-Stack Data Scientists for the Agentic Coding World Building Production-Grade AI Skills with Snowflake Cortex AI Function Studio I Tried 10 AI Agent Frameworks in 2026 — Here’s the Honest Guide I Wish I Had Earlier How One Spring Boot Optimization Saved Our Startup $30,000 a Year Inside Palantir AIP: How the World’s Most Controversial AI Platform Actually Works What Is a Reverse Proxy? (And Why Every Backend Developer Should Care) What Claude Opus 4.8 Actually Changes If You’re Building Agents QWEN 3.7 Max Worked For 35 Hrs Straight And The Results Were Mind-blowing When LLMs Meet Knowledge Graphs on the Battlefield Fine-Tuning is Dead: Why Context Orchestration Won in 2026 5 Things Broke When I Shipped a RAG + MCP Agent to Production. Google Co-Scientist: Hyper Scaling Research and Discovery Microsoft Just Embarrassed Browser Web Agents — 1,000 Lines Made GPT-5.4 Beat Opus 4.6 on 200 Web Tasks The Modern Data Stack Is Broken — Here’s How to Fix It With AI, Governance, and Real Architecture Building Production MCP Servers: What the Spec Won’t Tell You When Should an Agent Stop? The Anatomy of Termination Harness Engineering: The Layer That Matters More Than the Model AI Engineers Who Can’t Debug Are Getting Fired (Here’s How I Debug with Claude Code) Claude Code Memory: Why You Keep Explaining the Same Thing to Claude (and the Five Layers That Fix It) Claude Code Subagents: The Claude Code Feature You Skip Every Day (And Why It Quietly Wrecks Your Sessions) Agentic AI and the SMB Banking Advantage Claude Code: Spec-Driven Development — Why Your AI Coding Sessions Fall Apart at Hour Three The Real Cost of Agentic AI Nobody Budgets For SVM : 40 must visit Interview Questions (Part 2) Your AI Agent Works Perfectly in the Demo. Here Are the 6 Ways It Dies in Production. Unleashing the Power of ONNX for Speedier SBERT Inference Terraform vs CI/CD for Serverless Deployments Merve Noyan Stopped Writing Training Scripts — Her Agent Just Fine-Tuned 18 Models Solo for $11.40 Why Your Sales Forecast Is Always 20% Wrong (And How To Make It 12% Wrong) Genetic Cubic n{C/A} Ratios For Elementary Robotics Design Top 20 AdaBoost Interview Questions & Answers (Part 2 of 2) Agentic AI Vs AI Agents — What Are the Key Differences? LAI #127: The Infrastructure Layer of AI Is Becoming the Product Anthropic Caught Its Own AI Planning to Blackmail Engineers RNNs Cannot Think What Transformers Think Cheaply. ICLR 2026 Proved the Gap Is Exponential. Time Series Made So Easy My Aunt Got It on the Second Read Claude Cowork 101 | Towards AI Is 3-Bit KV Cache the Holy Grail? A Reality Check on Google’s TurboQuant LangGraph Multi-Agent Architecture: Building a Self-Critiquing AI Debate System AutoML on Autopilot | Towards AI I Ran This Open-Source AI Tool on a Messy Codebase and Got 71x Fewer Tokens — Here Is Exactly What Happened Month in 4 Papers (April 2026) AI Kept Forgetting My Notes. Fixing That Taught Me How It Actually Works. How ChatGPT Makes You Addicted Crack ML Interviews with Confidence: K-Nearest Neighbors (KNN 20 Q&A) The Event-Driven Blueprint: How I Scaled a Spring Boot System to 10 Million Kafka Messages/Day Building Vector Search? Why FAISS Alone Isn’t Enough TAI #202: GPT-5.5 Moves Codex Into Real Work Machine Learning System Design -The Model Serving Triangle, With One Forward Pass Flowing Through Every Trade-off (Part3) AI Orchestration in Action: How MuleSoft and LLMs Fuel the Future of Enterprise AI GPT-4 Has 1.8 Trillion Parameters. It Uses 2% of Them Per Token. Part 20: Data Manipulation in Multi-Dimensional Aggregation A Fundamental Introduction to Genetic Algorithm -Part Two TAI #200: Anthropic’s Mythos Capability Step Change and Gated Release From Notebook to Production: Running ML in the Real World (Part 4) Sqribble’s Template‑Driven Document Automation Anthropic Just Shipped the Layer That’s Already Going to Zero The L1 Loss Gradient, Explained From Scratch Your Postcode Is Deciding Your Care. I Built a Pipeline to Prove It. I Directed AI Agents to Build a Tool That Stress-Tests Incentive Designs. Here’s What It Found. Your System Prompt Is the Product — Not the Feature The LLM Wiki Trend Has a Retention Problem Nobody Mentions Top 20 Data Preparation Interview Questions and Answers (Part 2 of 2) LAI #122: Word Embeddings Started in 1948, Not With Word2Vec Top 15 Computer Vision Datasets [2026] 40 Generative AI Interview Questions That Actually Get Asked in 2026 (With Answers)
Long-Term vs Short-Term Memory for AI Agents: A Practical Guide Without the Hype
2026-04-10 · via Towards AI

Author(s): Andrii Tkachuk

Originally published on Towards AI.

Over the past year, memory has become one of the most overused — and misunderstood — concepts in AI agent design.

But before I start, I want to add a few words, most of us building AI agents today didn’t start as “AI engineers”. We come from backend engineering, data engineering, or data science.

That background shapes how we think about systems: scalability, reliability, clear lifecycles, and predictable failure modes.

And when we bring LLMs and agents into production, we still care about the same things:

  • we don’t want state explosions
  • we don’t want hidden coupling
  • and we definitely don’t want to create systems that make life harder for backend engineers and architects down the line.

This article is written from that mindset, not “what sounds impressive in demos”, but what leads to a reasonable trade-off between AI capabilities, backend architecture, and long-term system health.

You hear phrases like long-term memory, short-term memory, context engineering, persistent agents, and stateful conversations everywhere.
But if you look closely at most real implementations, many teams either:

  • don’t actually use memory at all, or
  • use it in ways that introduce serious scalability and reliability issues.

This article aims to cut through the hype and explain, in practical terms, how memory for AI agents actually works, which approaches exist today, and what trade-offs they come with.

Long-Term vs Short-Term Memory for AI Agents: A Practical Guide Without the Hype
Photo by dianne clifford on Unsplash

Before we start!🦾

If this piece gives you something practical you can take into your own system:
👏 leave 50 claps (yes, you can!) — Medium’s algorithm favors this, increasing visibility to others who then discover the article.
🔔 Follow me on Medium and LinkedIn for more deep dives into agentic systems, LLM architecture, and production-grade AI engineering.

First, Let’s Define the Terms Clearly

Long-Term Memory (LTM)

Long-term memory is anything that persists across sessions, restarts, and disconnections (includes the agent’s past behaviors and thoughts that need to be retained and recalled over an extended period of time; this often leverages an external vector store accessible through fast and scalable retrieval to provide relevant information for the agent as needed).

Typical characteristics:

  • Stored in databases, object storage, or vector stores
  • Survives process restarts
  • Not necessarily injected into the model on every request

Common forms of LTM:

  • Full chat history stored in a relational database
  • Events or messages stored in an append-only log
  • Vector embeddings of conversations or summaries
  • User preferences, profiles, or behavioral facts

Think of long-term memory as durable knowledge, not working context.

Short-Term Memory (STM) / Working Memory

Short-term memory (often called working memory or execution state, includes context information about the agent’s current situations; this is typically realized by in-context learning which means it is short and finite due to context window constraints) is:

  • Ephemeral
  • Session-scoped
  • Typically stored in RAM
  • Used during active interaction

In practice, what we call “short-term memory” in agents usually combines:

  • conversational state (messages)
  • execution state (tool outputs, intermediate results)
  • control flow metadata

Short-term memory exists to reduce overhead and improve reasoning continuity, not to replace persistence.

Approach #1 — The Legacy Stateless Approach (Still Very Common)

The most widespread approach today is actually stateless.

How it works

For every user request:

  1. Fetch chat history from a persistent data store
  2. Truncate or limit it
  3. Inject it into the prompt
  4. Run the agent
  5. Repeat on the next request
history = db.load_last_messages(user_id, limit=20)
prompt = build_prompt(history, user_message)
response = llm(prompt)

Pros

  • Extremely simple
  • Easy to reason about
  • No RAM management concerns
  • Works well in serverless environments

Cons

  • Database is hit on every request
  • Context is always injected, even when not needed
  • Hard limits must be enforced aggressively
  • Becomes expensive and slow at scale

This approach does not use short-term memory at all.
Each request is fully independent.

Approach #2 — Short-Term Memory via In-Memory State (LangGraph-Style)

A more advanced approach introduces explicit short-term memory.

This is the model used by frameworks like LangGraph.

Core idea

  • Load long-term memory once
  • Keep a mutable state object in RAM
  • Update it as messages arrive
  • Use it throughout the agent flow
  • Dispose of it when the session ends

Conceptually:

class ChatState(TypedDict):
user_id: str
messages: list[dict]

Typical flow (e.g., with WebSockets or Socket.IO)

SocketIO one of the most common and well-known framework for building chat based applications.

On connect

  • Load chat history from the database
  • Store it in an in-memory state object

On each message

  • Read state from RAM
  • Update messages
  • Run the agent

On disconnect

  • Optionally persist summary
  • Remove state from memory

Pros

  • No database calls on every message
  • Much faster per interaction
  • Natural conversational continuity
  • Clean separation between LTM and STM

Cons (and they are important)

RAM usage grows with:

  • number of concurrent users
  • length of conversations

Requires:

  • strict size limits
  • trimming or summarization
  • TTL / garbage collection

Socket-based systems have edge cases:

  • dropped connections
  • multiple tabs per user
  • missing disconnect events

This approach can be production-ready, but only if memory management is treated as a first-class concern.

Context Variables: What They Are (and What They Are Not)

Many implementations add context variables (for example, ContextVar in Python) to avoid passing state through every function.

This is useful — but limited.

Context variables:

  • ✔️ Improve code readability
  • ✔️ Allow access to state “from anywhere” in the execution flow
  • ❌ Do NOT persist state across events
  • ❌ Do NOT replace an in-memory store

They are an access pattern, not a memory strategy.

What context variables are good for

  • Avoiding passing state through dozens of function calls
  • Accessing the current execution state inside deep agent logic
  • Improving code readability
state = get_current_state()
state["messages"].append(new_message)

What they do not do

  • They do not persist memory across events
  • They do not replace an in-memory store
  • They do not solve session lifecycle problems

Context variables are a convenience layer, not a memory system.

Approach #3 — Memory as a Tool (The New Emerging Pattern)

A newer and increasingly popular approach is Memory as a Tool.

Before dismissing this approach as “too complex”, I would strongly recommend trying it at least once.

Even if you don’t end up using Memory as a Tool in production, it forces you to think differently about agent design:

  • how and when an agent decides to fetch information
  • how tool invocation is triggered intentionally rather than implicitly
  • and how much context is actually needed to solve a task.

In practice, this approach is one of the best ways to truly understand:

  • how tool usage works
  • how to guide an agent to call the right tool at the right time
  • and how modern reasoning-based agents operate internally.

Many engineers are familiar with prompts and APIs, but far fewer have hands-on experience with ReAct-style loops or explicit reasoning-driven tool calls. Trying this pattern — even in a small prototype — helps close that gap.

I’ll link a few articles below that go deeper into ReAct, reasoning models, and tool-based agents for those who want to explore this further.

Building AI Agents: Reasoning, Tools, and the Role of MCP

In the era of advanced language models, it’s tempting to treat every LLM as interchangeable — a black box that takes a…

medium.com

Designing AI Agents Like Microservices: A Practical Mental Model for Modern Architectures

If you’ve spent years building microservice architectures and are now staring at the “multi-agent AI” hype wondering…

medium.com

Core idea

Instead of automatically injecting memory, you expose memory retrieval as a tool:

Tool: retrieve_chat_history(user_id, chat_id, offset=0, limit=10)

The agent decides:

  • whether it needs past context
  • how much of it
  • when to fetch more

How it works

  1. Agent receives a user message
  2. Agent reasons whether history is required
  3. Agent calls the retrieval tool
  4. Tool returns paginated history
  5. Agent may repeat if needed

Pros

  • Minimal context injection
  • Lower token usage
  • Memory is fetched only when relevant
  • Excellent fit for modern reasoning models

Cons

  • Requires stronger models
  • Harder to debug
  • More complex agent logic
  • Latency depends on retrieval calls

Critical requirement: Reasoning + ReAct loop

This pattern assumes:

  • a reasoning-capable model
  • multi-step planning
  • tool invocation loops
  • reflection on observations

Without a ReAct-style agent:

  • the model may never request memory
  • or request it too late
  • or request irrelevant parts

This is not a drop-in replacement for traditional memory injection.

When it works best

  • Strong reasoning models
  • Well-designed ReAct prompts
  • Non-critical memory requirements
  • Systems tolerant to occasional mistakes

When it’s risky

  • If history is always required
  • If correctness is critical
  • If missing context causes failure
  • If the model is weak or unstable

With modern multi-step reasoning models, this approach is becoming increasingly viable — and often superior for large-scale systems.

!!! Many people might immediately start talking about security risks and so on, and they will be absolutely right, but let’s figure it out.

Memory used as a tool does introduce security considerations, but not fundamentally different from any other tool.

Prompt injection can attempt to trigger a memory read or write, but it cannot access anything beyond what the memory tool explicitly allows. The real security boundary is not the prompt, but the tool implementation.

This is why memory must:

  • be accessed only via a tool (never auto-injected)
  • be strictly scoped (user_id / tenant_id / namespace)
  • validate both read and write operations
  • explicitly control what can be recalled and how much (so called wrapper should always be)

In practice, prompt injection cannot recall another user’s memory unless there is already a bug in isolation or authorization logic. The larger risk is memory poisoning (writing bad memory), which should be mitigated by validation and write policies inside the tool wrapper, but that’s an absolutely different topic, my folks. If you are interested in this topic, I can also write my observations, experience, and thoughts on this matter.

Choosing the Right Approach

There is no single “correct” memory strategy.

Use hybrid memory, since it integrates both short-term memory and long-term memory to improve an agent’s ability for long-range reasoning and accumulation of experiences.

In practice, hybrid architectures work best:

  • Long-term memory for durability
  • Short-term memory for performance
  • Tool-based retrieval for flexibility

Final Thoughts

Memory is not magic.

Most problems attributed to “lack of memory” are actually:

  • poor context selection
  • uncontrolled state growth
  • missing lifecycle management

Before adding complexity, ask:

  • Does the agent really need this context?
  • For how long?
  • Who is responsible for cleaning it up?

If you answer those questions honestly, the right architecture usually becomes obvious.

And that’s a wrap! If you’ve read this far, it probably means you found this article useful or insightful. If that’s the case, consider leaving a few claps or sharing it with your team, please. Thanks for reading! 🚀

Published via Towards AI