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

推荐订阅源

宝玉的分享
宝玉的分享
The GitHub Blog
The GitHub Blog
Vercel News
Vercel News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
酷 壳 – CoolShell
酷 壳 – CoolShell
Last Week in AI
Last Week in AI
F
Fortinet All Blogs
Jina AI
Jina AI
I
InfoQ
T
The Blog of Author Tim Ferriss
P
Proofpoint News Feed
博客园 - 三生石上(FineUI控件)
G
Google Developers Blog
V
Visual Studio Blog
L
LangChain Blog
WordPress大学
WordPress大学
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
T
Tor Project blog
GbyAI
GbyAI
MongoDB | Blog
MongoDB | Blog
V
V2EX
Stack Overflow Blog
Stack Overflow Blog
H
Help Net Security
Recorded Future
Recorded Future
N
News and Events Feed by Topic
云风的 BLOG
云风的 BLOG
Martin Fowler
Martin Fowler
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
罗磊的独立博客
O
OpenAI News
Google DeepMind News
Google DeepMind News
S
Schneier on Security
C
Check Point Blog
N
Netflix TechBlog - Medium
The Register - Security
The Register - Security
aimingoo的专栏
aimingoo的专栏
TaoSecurity Blog
TaoSecurity Blog
T
Tenable Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Hugging Face - Blog
Hugging Face - Blog
Cyberwarzone
Cyberwarzone
月光博客
月光博客
The Last Watchdog
The Last Watchdog
B
Blog
有赞技术团队
有赞技术团队
Blog — PlanetScale
Blog — PlanetScale
T
Tailwind CSS Blog
Hacker News: Ask HN
Hacker News: Ask HN
H
Heimdal Security Blog
美团技术团队

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Stop Guessing Memory: How to Automate LangChain Memory Testing and Catch 80% of Multi-Turn Failures
BAOFUFAN · 2026-05-11 · via DEV Community

2 a.m. The customer Slack channel explodes — the support bot just asked for the same order number three times in a row. A frustrated user screams, “Do you have amnesia?” After digging through the code and the prompt, everything looks fine. Only then do we discover that ConversationBufferMemory silently dropped context in one of the turns. The LLM had no idea what was said earlier. Right then I thought: if we could catch this memory loss automatically in CI, we’d never ship a black eye like this.

Breaking down the problem

In LLM-powered apps, memory isn’t a “nice-to-have” anymore — it’s the core experience. LangChain gives us a buffet of memory implementations: ConversationBufferMemory, ConversationSummaryMemory, VectorStoreRetrieveMemory, and more. But almost no project actually tests memory accuracy seriously.

The root cause is brutally simple: memory testing is too manual. Most teams spin up a chain locally, poke it with Postman or the CLI for a few turns, visually confirm “yeah, it remembered the name I just said,” and then merge. That approach has three fatal flaws:

  1. Minimal path coverage – manual testing only walks the happy path. Branch conditions (hitting the token limit, summary memory trigger timing, interleaving messages) are left to guesswork.
  2. Zero regression protection – next week you tweak the prompt or switch the model, and the memory logic might break, but nobody will manually re‑play every historical conversation.
  3. Fuzzy verification – “looks right” is not the same as is right. Human judgement on whether memory is complete or hallucination-free has huge error margins.

Testing a stateful, long‑context agent with this hand‑crafted approach is like walking across a highway blindfolded. What we need is an automated assertion‑based memory verification scheme: given a multi‑turn dialog script, precisely verify the content, order, and key facts stored inside the memory object — and run it in CI.

Solution design

The core idea is simple: turn the LLM into a deterministic “teleprompter,” then treat the memory object as the system under test and use pytest for assertions.

Why not let the LLM judge memory itself? (e.g., call the model again: “Please check if the conversation history contains X”). Because that would make the “judge” the same hallucination machine — not reliable. What we want are pure engineering assertions: string containment, list length, message type — deterministic checks.

Tooling choices:

  • pytest: the most universal Python test framework; its fixture mechanism fits perfectly for managing memory state.
  • LangChain’s BaseMemory: we directly interact with memory.chat_memory.messages and memory.load_memory_variables(), bypassing LLM uncertainty.
  • Custom FakeLLM: inherit from LLM, return fixed text in a predetermined sequence, with zero external API dependency. Tests complete in milliseconds and are 100% repeatable.

We avoid mocking ChatOpenAI because network jitter and model randomness directly undermine assertion stability. We also don’t treat FakeListLLM as an opaque box — we need precise control over every reply, so a custom HardcodedLLM gives us the most flexibility.

Core implementation

Let’s build automated memory testing step by step. All code is runnable (requires pip install langchain langchain-core pytest).

1. Build a “teleprompter” LLM

This snippet solves the “LLM response is uncontrollable” problem — we make each invocation return a preset sequence, like playing a cassette tape.

from typing import List, Optional
from langchain_core.language_models.llms import LLM
from langchain_core.callbacks import CallbackManagerForLLMRun

class HardcodedLLM(LLM):
    """按固定序列返回的 LLM,用于自动化测试"""
    responses: List[str]
    call_count: int = 0

    def _call(
        self,
        prompt: str,
        stop: Optional[List[str]] = None,
        run_manager: Optional[CallbackManagerForLLMRun] = None,
    ) -> str:
        # 如果调用次数超过预设回复数量,返回一个默认值以避免抛出异常
        if self.call_count >= len(self.responses):
            return "I don't know"
        response = self.responses[self.call_count]
        self.call_count += 1
        return response

    @property
    def _llm_type(self) -> str:
        return "hardcoded"

Enter fullscreen mode Exit fullscreen mode

2. Write reusable test fixtures

This fixture eliminates the “every test assembles chain and memory from scratch” pain — we extract common initialization.

import pytest
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory

@pytest.fixture
def memory() -> ConversationBufferMemory:
    """返回一个干净的内存记忆对象,每次测试独立"""
    return ConversationBufferMemory(return_messages=True)

@pytest.fixture
def chain(memory: ConversationBufferMemory, request) -> ConversationChain:
    """
    根据测试参数定制 LLM 的回复序列。
    测试函数可以用  装饰器传入预设 responses。
    """
    # 获取测试函数传递的 responses 参数,没有则使用默认值
    responses = getattr(request, "param", ["Hello", "Sure", "Done"])
    llm = HardcodedLLM(responses=responses)
    return ConversationChain(llm=llm, memory=memory)

Enter fullscreen mode Exit fullscreen mode

3. First test: Single‑turn memory must exist

Here we verify the simplest scenario — after one utterance, is it immediately stored in memory?

def test_single_turn_memory_exists(chain, memory):
    chain.invoke("My name is Alice")
    messages = memory.chat_memory.messages
    assert any("Alice" in msg.content for msg in messages)

Enter fullscreen mode Exit fullscreen mode

That’s it. No LLM judgement, no flakiness — just a straight string check. Run pytest and it passes in under a second.

4. Multi‑turn memory retention test

The real horror show is multi‑turn memory loss. Let’s simulate a three‑turn conversation where the bot asks for the order number, the user provides it, and later the user asks to cancel. The memory must retain the order number across turns.

@pytest.mark.parametrize("chain", [["What is your order number?",
                                    "Your order #12345 has been found.",
                                    "Sure, I'll cancel order #12345."]], indirect=True)
def test_multi_turn_memory_retains_order_number(chain, memory):
    chain.invoke("I want to cancel my order")
    chain.invoke("12345")
    chain.invoke("Please proceed with cancellation")
    messages = memory.chat_memory.messages
    # Verify the order number appears in the human message AND the AI response
    assert any("12345" in msg.content for msg in messages)
    # Verify the context wasn't truncated (we should have 6 messages: 3 human, 3 AI)
    assert len(messages) == 6

Enter fullscreen mode Exit fullscreen mode

This test catches exactly the 2 a.m. bug: if ConversationBufferMemory drops messages due to token limits or misconfiguration, the assertion on message count or order number fails immediately.

5. Testing summary memory trigger logic

Summary memory is trickier — it compresses history. We need to verify that after enough conversation, the summary kicks in and the old details are still accessible.

from langchain.memory import ConversationSummaryMemory

@pytest.fixture
def summary_memory() -> ConversationSummaryMemory:
    # Use a tiny max_token_limit to force summarization quickly
    return ConversationSummaryMemory(llm=HardcodedLLM(responses=["Summary of the conversation"]),
                                     max_token_limit=10,
                                     return_messages=True)

def test_summary_memory_preserves_key_facts(chain, summary_memory):
    # Override the default chain to use our summary memory
    chain.memory = summary_memory
    chain.invoke("My name is Bob and I'm from Berlin.")
    chain.invoke("I need a hotel.")
    chain.invoke("What's my name?")
    # The summary should have captured "Bob" and "Berlin"
    memory_variables = summary_memory.load_memory_variables({})
    history = memory_variables.get("history", "")
    assert "Bob" in history
    assert "Berlin" in history

Enter fullscreen mode Exit fullscreen mode

By controlling the summarization LLM’s output with our HardcodedLLM, we make the test deterministic. No matter how many times it runs, the summary text is always the same, so assertions are rock solid.

Why this matters in CI

Put these tests into your CI pipeline and you get a safety net that catches regression instantly. When you:

  • bump the LangChain version
  • swap the underlying model
  • modify the memory configuration (e.g., k for buffer window)
  • change the prompt template that influences token usage

…any memory‑breaking change fails the build before it reaches a human. The confidence gain is enormous — especially in production agents where context loss directly damages user trust.

Moving beyond the basics

Once you have the deterministic harness, you can extend it:

  • Entity extraction memory: verify that key entities are persisted accurately.
  • Token‑limit boundary tests: push conversations right to the limit and confirm graceful handling (no silent truncation).
  • Mixed memory strategies: combine buffer and summary memory and assert that both layers retain critical information.
  • Property‑based testing: use Hypothesis to generate random conversation flows and check invariants (e.g., “all names mentioned in the last N turns are still retrievable”).

Manual “click‑and‑stare” testing can’t touch that. Automated memory assertions turn a major source of production issues into a solved problem.

The next time your support bot loses its mind at 2 a.m., you’ll already have a failing test that tells you exactly where the memory broke.