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

推荐订阅源

Spread Privacy
Spread Privacy
P
Palo Alto Networks Blog
P
Proofpoint News Feed
AI
AI
Help Net Security
Help Net Security
S
Securelist
T
Troy Hunt's Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
C
Cisco Blogs
Scott Helme
Scott Helme
Hacker News - Newest:
Hacker News - Newest: "LLM"
Vercel News
Vercel News
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
B
Blog
GbyAI
GbyAI
Recent Commits to openclaw:main
Recent Commits to openclaw:main
D
Darknet – Hacking Tools, Hacker News & Cyber Security
P
Proofpoint News Feed
S
Security Affairs
Cisco Talos Blog
Cisco Talos Blog
AWS News Blog
AWS News Blog
T
Tenable Blog
H
Help Net Security
NISL@THU
NISL@THU
F
Fortinet All Blogs
博客园_首页
G
GRAHAM CLULEY
L
LINUX DO - 最新话题
P
Privacy International News Feed
G
Google Developers Blog
博客园 - Franky
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Security Archives - TechRepublic
Security Archives - TechRepublic
The Register - Security
The Register - Security
L
LangChain Blog
aimingoo的专栏
aimingoo的专栏
T
Tor Project blog
P
Privacy & Cybersecurity Law Blog
量子位
C
Cyber Attacks, Cyber Crime and Cyber Security
Forbes - Security
Forbes - Security
S
Secure Thoughts
Simon Willison's Weblog
Simon Willison's Weblog
D
Docker
Recorded Future
Recorded Future
博客园 - 三生石上(FineUI控件)
L
Lohrmann on Cybersecurity
T
Tailwind CSS Blog

MarkTechPost

A Coding Implementation of End-to-End Brain Decoding from MEG Signals Using NeuralSet and Deep Learning for Predicting Linguistic Features Meta Introduces Autodata: An Agentic Framework That Turns AI Models into Autonomous Data Scientists for High-Quality Training Data Creation A Coding Guide on LLM Post Training with TRL from Supervised Fine Tuning to DPO and GRPO Reasoning Qwen AI Releases Qwen-Scope: An Open-Source Sparse AutoEncoders (SAE) Suite That Turns LLM Internal Features into Practical Development Tools A Coding Deep Dive into Agentic UI, Generative UI, State Synchronization, and Interrupt-Driven Approval Flows Moonshot AI Open-Sources FlashKDA: CUTLASS Kernels for Kimi Delta Attention with Variable-Length Batching and H20 Benchmarks Microsoft Research’s World-R1 Uses Flow-GRPO and 3D-Aware Rewards to Inject Geometric Consistency Into Wan 2.1 Without Architectural Changes A Coding Implementation on Pyright Type Checking Covering Generics, Protocols, Strict Mode, Type Narrowing, and Modern Python Typing IBM Releases Two Granite Speech 4.1 2B Models: Autoregressive ASR with Translation and Non-Autoregressive Editing for Fast Inference Top 10 KV Cache Compression Techniques for LLM Inference: Reducing Memory Overhead Across Eviction, Quantization, and Low-Rank Methods Qwen Team Releases FlashQLA: a High-Performance Linear Attention Kernel Library That Achieves Up to 3× Speedup on NVIDIA Hopper GPUs Step by Step Guide to Build a Complete PII Detection and Redaction Pipeline with OpenAI Privacy Filter Meta FAIR Releases NeuralSet: A Python Package for Neuro-AI That Supports fMRI, M/EEG, Spikes, and HuggingFace Embeddings smol-audio: A Colab-Friendly Notebook Collection for Fine-Tuning Whisper, Parakeet, Voxtral, Granite Speech, and Audio Flamingo 3 A Coding Implementation on Document Parsing Benchmarking with LlamaIndex ParseBench Using Python, Hugging Face, and Evaluation Metrics Poolside AI Introduces Laguna XS.2 and M.1: Agentic Coding Models Reaching 68.2% and 72.5% on SWE-bench Verified How to Build Traceable and Evaluated LLM Workflows Using Promptflow, Prompty, and OpenAI OpenAI Releases Privacy Filter: A 1.5B-Parameter Open-Source PII Redaction Model with 50M Active Parameters Top 10 Physical AI Models Powering Real-World Robots in 2026 How to Build a Lightweight Vision-Language-Action-Inspired Embodied Agent with Latent World Modeling and Model Predictive Control Meet Talkie-1930: A 13B Open-Weight LLM Trained on Pre-1931 English Text for Historical Reasoning and Generalization Research Build a Reinforcement Learning Powered Agent that Learns to Retrieve Relevant Long-Term Memories for Accurate LLM Question Answering OpenMOSS Releases MOSS-Audio: An Open-Source Foundation Model for Speech, Sound, Music, and Time-Aware Audio Reasoning Meta AI Releases Sapiens2: A High-Resolution Human-Centric Vision Model for Pose, Segmentation, Normals, Pointmap, and Albedo The LoRA Assumption That Breaks in Production How to Build a Fully Searchable AI Knowledge Base with OpenKB, OpenRouter, and Llama How to Build Smarter Multilingual Text Wrapping with BudouX Through Parsing, HTML Rendering, Model Introspection, and Toy Training Top 7 Benchmarks That Actually Matter for Agentic Reasoning in Large Language Models RAG Without Vectors: How PageIndex Retrieves by Reasoning A Coding Tutorial on Datashader on Rendering Massive Datasets with High-Performance Python Visual Analytics xAI Launches grok-voice-think-fast-1.0: Topping τ-voice Bench at 67.3%, Outperforming Gemini, GPT Realtime, and More A Coding Implementation on kvcached for Elastic KV Cache Memory, Bursty LLM Serving, and Multi-Model GPU Sharing Google DeepMind Introduces Vision Banana: An Instruction-Tuned Image Generator That Beats SAM 3 on Segmentation and Depth Anything V3 on Metric Depth Estimation Meet GitNexus: An Open-Source MCP-Native Knowledge Graph Engine That Gives Claude Code and Cursor Full Codebase Structural Awareness A Coding Implementation on Deepgram Python SDK for Transcription, Text-to-Speech, Async Audio Processing, and Text Intelligence A Coding Implementation on Microsoft’s OpenMementos with Trace Structure Analysis, Context Compression, and Fine-Tuning Data Preparation DeepSeek AI Releases DeepSeek-V4: Compressed Sparse Attention and Heavily Compressed Attention Enable One-Million-Token Contexts Google DeepMind Introduces Decoupled DiLoCo: An Asynchronous Training Architecture Achieving 88% Goodput Under High Hardware Failure Rates Mend Releases AI Security Governance Framework: Covering Asset Inventory, Risk Tiering, AI Supply Chain Security, and Maturity Model Mend.io Releases AI Security Governance Framework Covering Asset Inventory, Risk Tiering, AI Supply Chain Security, and Maturity Model OpenAI Releases GPT-5.5, a Fully Retrained Agentic Model That Scores 82.7% on Terminal-Bench 2.0 and 84.9% on GDPval A Coding Tutorial on OpenMythos on Recurrent-Depth Transformers with Depth Extrapolation, Adaptive Computation, and Mixture-of-Experts Routing Google Cloud AI Research Introduces ReasoningBank: A Memory Framework that Distills Reasoning Strategies from Agent Successes and Failures Xiaomi Releases MiMo-V2.5-Pro and MiMo-V2.5: Matching Frontier Model Benchmarks at Significantly Lower Token Cost How to Design a Production-Grade CAMEL Multi-Agent System with Planning, Tool Use, Self-Consistency, and Critique-Driven Refinement Alibaba Qwen Team Releases Qwen3.6-27B: A Dense Open-Weight Model Outperforming 397B MoE on Agentic Coding Benchmarks A Detailed Implementation on Equinox with JAX Native Modules, Filtered Transforms, Stateful Layers, and End-to-End Training Workflows Next Leap to Harness Engineering: JiuwenClaw Pioneers ‘Coordination Engineering’ Photon Releases Spectrum: An Open-Source TypeScript Framework that Deploys AI Agents Directly to iMessage, WhatsApp, and Telegram OpenAI Open-Sources Euphony: A Browser-Based Visualization Tool for Harmony Chat Data and Codex Session Logs Hugging Face Releases ml-intern: An Open-Source AI Agent that Automates the LLM Post-Training Workflow A Coding Implementation to Build a Conditional Bayesian Hyperparameter Optimization Pipeline with Hyperopt, TPE, and Early Stopping Google Introduces Simula: A Reasoning-First Framework for Generating Controllable, Scalable Synthetic Datasets Across Specialized AI Domains A Coding Implementation on Qwen 3.6-35B-A3B Covering Multimodal Inference, Thinking Control, Tool Calling, MoE Routing, RAG, and Session Persistence Moonshot AI Releases Kimi K2.6 with Long-Horizon Coding, Agent Swarm Scaling to 300 Sub-Agents and 4,000 Coordinated Steps A Coding Implementation on Microsoft’s Phi-4-Mini for Quantized Inference Reasoning Tool Use RAG and LoRA Fine-Tuning OpenAI Scales Trusted Access for Cyber Defense With GPT-5.4-Cyber: a Fine-Tuned Model Built for Verified Security Defenders Moonshot AI and Tsinghua Researchers Propose PrfaaS: A Cross-Datacenter KVCache Architecture that Rethinks How LLMs are Served at Scale Meet OpenMythos: An Open-Source PyTorch Reconstruction of Claude Mythos Where 770M Parameters Match a 1.3B Transformer How TabPFN Leverages In-Context Learning to Achieve Superior Accuracy on Tabular Datasets Compared to Random Forest and CatBoost A Coding Implementation to Build an AI-Powered File Type Detection and Security Analysis Pipeline with Magika and OpenAI NVIDIA Releases Ising: the First Open Quantum AI Model Family for Hybrid Quantum-Classical Systems xAI Launches Standalone Grok Speech-to-Text and Text-to-Speech APIs, Targeting Enterprise Voice Developers A Coding Tutorial for Running PrismML Bonsai 1-Bit LLM on CUDA with GGUF, Benchmarking, Chat, JSON, and RAG A Coding Guide for Property-Based Testing Using Hypothesis with Stateful, Differential, and Metamorphic Test Design Anthropic Releases Claude Opus 4.7: A Major Upgrade for Agentic Coding, High-Resolution Vision, and Long-Horizon Autonomous Tasks Google AI Releases Auto-Diagnose: An Large Language Model LLM-Based System to Diagnose Integration Test Failures at Scale A End-to-End Coding Guide to Running OpenAI GPT-OSS Open-Weight Models with Advanced Inference Workflows Top 19 AI Red Teaming Tools (2026): Secure Your ML Models A Coding Guide to Build a Production-Grade Background Task Processing System Using Huey with SQLite, Scheduling, Retries, Pipelines, and Concurrency Control Qwen Team Open-Sources Qwen3.6-35B-A3B: A Sparse MoE Vision-Language Model with 3B Active Parameters and Agentic Coding Capabilities OpenAI Launches GPT-Rosalind: Its First Life Sciences AI Model Built to Accelerate Drug Discovery and Genomics Research Building Transformer-Based NQS for Frustrated Spin Systems with NetKet UCSD and Together AI Research Introduces Parcae: A Stable Architecture for Looped Language Models That Achieves the Quality of a Transformer Twice the Size A Coding Implementation to Build Multi-Agent AI Systems with SmolAgents Using Code Execution, Tool Calling, and Dynamic Orchestration A Technical Deep Dive into the Essential Stages of Modern Large Language Model Training, Alignment, and Deployment Google AI Launches Gemini 3.1 Flash TTS: A New Benchmark in Expressive and Controllable AI Voice Google DeepMind Releases Gemini Robotics-ER 1.6: Bringing Enhanced Embodied Reasoning and Instrument Reading to Physical AI Google Launches ‘Skills’ in Chrome: Turning Reusable AI Prompts into One-Click Browser Workflows A Coding Implementation of Crawl4AI for Web Crawling, Markdown Generation, JavaScript Execution, and LLM-Based Structured Extraction TinyFish AI Releases Full Web Infrastructure Platform for AI Agents: Search, Fetch, Browser, and Agent Under One API Key NVIDIA and the University of Maryland Researchers Released Audio Flamingo Next (AF-Next): A Super Powerful and Open Large Audio-Language Model A Hands-On Coding Tutorial for Microsoft VibeVoice Covering Speaker-Aware ASR, Real-Time TTS, and Speech-to-Speech Pipelines Meta AI and KAUST Researchers Propose Neural Computers That Fold Computation, Memory, and I/O Into One Learned Model A Coding Implementation of MolmoAct for Depth-Aware Spatial Reasoning, Visual Trajectory Tracing, and Robotic Action Prediction MiniMax Just Open Sourced MiniMax M2.7: A Self-Evolving Agent Model that Scores 56.22% on SWE-Pro and 57.0% on Terminal Bench 2 Liquid AI Releases LFM2.5-VL-450M: a 450M-Parameter Vision-Language Model with Bounding Box Prediction, Multilingual Support, and Sub-250ms Edge Inference Researchers from MIT, NVIDIA, and Zhejiang University Propose TriAttention: A KV Cache Compression Method That Matches Full Attention at 2.5× Higher Throughput How to Build a Secure Local-First Agent Runtime with OpenClaw Gateway, Skills, and Controlled Tool Execution How Knowledge Distillation Compresses Ensemble Intelligence into a Single Deployable AI Model Alibaba’s Tongyi Lab Releases VimRAG: a Multimodal RAG Framework that Uses a Memory Graph to Navigate Massive Visual Contexts A Coding Guide to Markerless 3D Human Kinematics with Pose2Sim, RTMPose, and OpenSim NVIDIA Releases AITune: An Open-Source Inference Toolkit That Automatically Finds the Fastest Inference Backend for Any PyTorch Model Five AI Compute Architectures Every Engineer Should Know: CPUs, GPUs, TPUs, NPUs, and LPUs Compared An End-to-End Coding Guide to NVIDIA KVPress for Long-Context LLM Inference, KV Cache Compression, and Memory-Efficient Generation Meta Superintelligence Lab Releases Muse Spark: A Multimodal Reasoning Model With Thought Compression and Parallel Agents Sigmoid vs ReLU Activation Functions: The Inference Cost of Losing Geometric Context A Coding Guide to Build Advanced Document Intelligence Pipelines with Google LangExtract, OpenAI Models, Structured Extraction, and Interactive Visualization Google AI Research Introduces PaperOrchestra: A Multi-Agent Framework for Automated AI Research Paper Writing A Comprehensive Implementation Guide to ModelScope for Model Search, Inference, Fine-Tuning, Evaluation, and Export
How to Build a Universal Long-Term Memory Layer for AI Agents Using Mem0 and OpenAI
Asif Razzaq · 2026-04-16 · via MarkTechPost

In this tutorial, we build a universal long-term memory layer for AI agents using Mem0, OpenAI models, and ChromaDB. We design a system that can extract structured memories from natural conversations, store them semantically, retrieve them intelligently, and integrate them directly into personalized agent responses. We move beyond simple chat history and implement persistent, user-scoped memory with full CRUD control, semantic search, multi-user isolation, and custom configuration. Finally, we construct a production-ready memory-augmented agent architecture that demonstrates how modern AI systems can reason with contextual continuity rather than operate statelessly.

!pip install mem0ai openai rich chromadb -q


import os
import getpass
from datetime import datetime


print("=" * 60)
print("🔐  MEM0 Advanced Tutorial — API Key Setup")
print("=" * 60)


OPENAI_API_KEY = getpass.getpass("Enter your OpenAI API key: ")
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY


print("\n✅ API key set!\n")


from openai import OpenAI
from mem0 import Memory
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.markdown import Markdown
from rich import print as rprint
import json


console = Console()
openai_client = OpenAI()


console.rule("[bold cyan]MODULE 1: Basic Memory Setup[/bold cyan]")


memory = Memory()


print(Panel(
   "[green]✓ Memory instance created with default config[/green]\n"
   "  • LLM: gpt-4.1-nano (OpenAI)\n"
   "  • Vector Store: ChromaDB (local)\n"
   "  • Embedder: text-embedding-3-small",
   title="Memory Config", border_style="cyan"
))

We install all required dependencies and securely configure our OpenAI API key. We initialize the Mem0 Memory instance along with the OpenAI client and Rich console utilities. We establish the foundation of our long-term memory system with the default configuration powered by ChromaDB and OpenAI embeddings.

console.rule("[bold cyan]MODULE 2: Adding & Retrieving Memories[/bold cyan]")


USER_ID = "alice_tutorial"


print("\n📝 Adding memories for user:", USER_ID)


conversations = [
   [
       {"role": "user", "content": "Hi! I'm Alice. I'm a software engineer who loves Python and machine learning."},
       {"role": "assistant", "content": "Nice to meet you Alice! Python and ML are great areas to be in."}
   ],
   [
       {"role": "user", "content": "I prefer dark mode in all my IDEs and I use VS Code as my main editor."},
       {"role": "assistant", "content": "Good to know! VS Code with dark mode is a popular combo."}
   ],
   [
       {"role": "user", "content": "I'm currently building a RAG pipeline for my company's internal docs. It's for a fintech startup."},
       {"role": "assistant", "content": "That's exciting! RAG pipelines are really valuable for enterprise use cases."}
   ],
   [
       {"role": "user", "content": "I have a dog named Max and I enjoy hiking on weekends."},
       {"role": "assistant", "content": "Max sounds lovely! Hiking is a great way to recharge."}
   ],
]


results = []
for i, convo in enumerate(conversations):
   result = memory.add(convo, user_id=USER_ID)
   extracted = result.get("results", [])
   for mem in extracted:
       results.append(mem)
   print(f"  Conversation {i+1}: {len(extracted)} memory(ies) extracted")


print(f"\n✅ Total memories stored: {len(results)}")

We simulate realistic multi-turn conversations and store them using Mem0’s automatic memory extraction pipeline. We add structured conversational data for a specific user and allow the LLM to extract meaningful long-term facts. We verify how many memories are created, confirming that semantic knowledge is successfully persisted.

console.rule("[bold cyan]MODULE 3: Semantic Search[/bold cyan]")


queries = [
   "What programming languages does the user prefer?",
   "What is Alice working on professionally?",
   "What are Alice's hobbies?",
   "What tools and IDE does Alice use?",
]


for query in queries:
   search_results = memory.search(query=query, user_id=USER_ID, limit=2)
   table = Table(title=f"🔍 Query: {query}", show_lines=True)
   table.add_column("Memory", style="white", max_width=60)
   table.add_column("Score", style="green", justify="center")
  
   for r in search_results.get("results", []):
       score = r.get("score", "N/A")
       score_str = f"{score:.4f}" if isinstance(score, float) else str(score)
       table.add_row(r["memory"], score_str)
  
   console.print(table)
   print()


console.rule("[bold cyan]MODULE 4: CRUD Operations[/bold cyan]")


all_memories = memory.get_all(user_id=USER_ID)
memories_list = all_memories.get("results", [])


print(f"\n📚 All memories for '{USER_ID}':")
for i, mem in enumerate(memories_list):
   print(f"  [{i+1}] ID: {mem['id'][:8]}...  →  {mem['memory']}")


if memories_list:
   first_id = memories_list[0]["id"]
   original_text = memories_list[0]["memory"]
  
   print(f"\n✏️  Updating memory: '{original_text}'")
   memory.update(memory_id=first_id, data=original_text + " (confirmed)")
  
   updated = memory.get(memory_id=first_id)
   print(f"   After update: '{updated['memory']}'")

We perform semantic search queries to retrieve relevant memories using natural language. We demonstrate how Mem0 ranks stored memories by similarity score and returns the most contextually aligned information. We also perform CRUD operations by listing, updating, and validating stored memory entries.

console.rule("[bold cyan]MODULE 5: Memory-Augmented Chat[/bold cyan]")


def chat_with_memory(user_message: str, user_id: str, session_history: list) -> str:
  
   relevant = memory.search(query=user_message, user_id=user_id, limit=5)
   memory_context = "\n".join(
       f"- {r['memory']}" for r in relevant.get("results", [])
   ) or "No relevant memories found."
  
   system_prompt = f"""You are a highly personalized AI assistant.
You have access to long-term memories about this user.


RELEVANT USER MEMORIES:
{memory_context}


Use these memories to provide context-aware, personalized responses.
Be natural — don't explicitly announce that you're using memories."""
  
   messages = [{"role": "system", "content": system_prompt}]
   messages.extend(session_history[-6:])
   messages.append({"role": "user", "content": user_message})
  
   response = openai_client.chat.completions.create(
       model="gpt-4.1-nano-2025-04-14",
       messages=messages
   )
   assistant_response = response.choices[0].message.content
  
   exchange = [
       {"role": "user", "content": user_message},
       {"role": "assistant", "content": assistant_response}
   ]
   memory.add(exchange, user_id=user_id)
  
   session_history.append({"role": "user", "content": user_message})
   session_history.append({"role": "assistant", "content": assistant_response})
  
   return assistant_response




session = []
demo_messages = [
   "Can you recommend a good IDE setup for me?",
   "What kind of project am I currently building at work?",
   "Suggest a weekend activity I might enjoy.",
   "What's a good tech stack for my current project?",
]


print("\n🤖 Starting memory-augmented conversation with Alice...\n")


for msg in demo_messages:
   print(Panel(f"[bold yellow]User:[/bold yellow] {msg}", border_style="yellow"))
   response = chat_with_memory(msg, USER_ID, session)
   print(Panel(f"[bold green]Assistant:[/bold green] {response}", border_style="green"))
   print()

We build a fully memory-augmented chat loop that retrieves relevant memories before generating responses. We dynamically inject personalized context into the system prompt and store each new exchange back into long-term memory. We simulate a multi-turn session to demonstrate contextual continuity and personalization in action.

console.rule("[bold cyan]MODULE 6: Multi-User Memory Isolation[/bold cyan]")


USER_BOB = "bob_tutorial"


bob_conversations = [
   [
       {"role": "user", "content": "I'm Bob, a data scientist specializing in computer vision and PyTorch."},
       {"role": "assistant", "content": "Great to meet you Bob!"}
   ],
   [
       {"role": "user", "content": "I prefer Jupyter notebooks over VS Code, and I use Vim keybindings."},
       {"role": "assistant", "content": "Classic setup for data science work!"}
   ],
]


for convo in bob_conversations:
   memory.add(convo, user_id=USER_BOB)


print("\n🔐 Testing memory isolation between Alice and Bob:\n")


test_query = "What programming tools does this user prefer?"


alice_results = memory.search(query=test_query, user_id=USER_ID, limit=3)
bob_results = memory.search(query=test_query, user_id=USER_BOB, limit=3)


print("👩 Alice's memories:")
for r in alice_results.get("results", []):
   print(f"   • {r['memory']}")


print("\n👨 Bob's memories:")
for r in bob_results.get("results", []):
   print(f"   • {r['memory']}")

We demonstrate user-level memory isolation by introducing a second user with distinct preferences. We store separate conversational data and validate that searches remain scoped to the correct user_id. We confirm that memory namespaces are isolated, ensuring secure multi-user agent deployments.

print("\n✅ Memory isolation confirmed — users cannot see each other's data.")


console.rule("[bold cyan]MODULE 7: Custom Configuration[/bold cyan]")


custom_config = {
   "llm": {
       "provider": "openai",
       "config": {
           "model": "gpt-4.1-nano-2025-04-14",
           "temperature": 0.1,
           "max_tokens": 2000,
       }
   },
   "embedder": {
       "provider": "openai",
       "config": {
           "model": "text-embedding-3-small",
       }
   },
   "vector_store": {
       "provider": "chroma",
       "config": {
           "collection_name": "advanced_tutorial_v2",
           "path": "/tmp/chroma_advanced",
       }
   },
   "version": "v1.1"
}


custom_memory = Memory.from_config(custom_config)


print(Panel(
   "[green]✓ Custom memory instance created[/green]\n"
   "  • LLM: gpt-4.1-nano with temperature=0.1\n"
   "  • Embedder: text-embedding-3-small\n"
   "  • Vector Store: ChromaDB at /tmp/chroma_advanced\n"
   "  • Collection: advanced_tutorial_v2",
   title="Custom Config Applied", border_style="magenta"
))


custom_memory.add(
   [{"role": "user", "content": "I'm a researcher studying neural plasticity and brain-computer interfaces."}],
   user_id="researcher_01"
)


result = custom_memory.search("What field does this person work in?", user_id="researcher_01", limit=2)
print("\n🔍 Custom memory search result:")
for r in result.get("results", []):
   print(f"   • {r['memory']}")


console.rule("[bold cyan]MODULE 8: Memory History[/bold cyan]")


all_alice = memory.get_all(user_id=USER_ID)
alice_memories = all_alice.get("results", [])


table = Table(title=f"📋 Full Memory Profile: {USER_ID}", show_lines=True, width=90)
table.add_column("#", style="dim", width=3)
table.add_column("Memory ID", style="cyan", width=12)
table.add_column("Memory Content", style="white")
table.add_column("Created At", style="yellow", width=12)


for i, mem in enumerate(alice_memories):
   mem_id = mem["id"][:8] + "..."
   created = mem.get("created_at", "N/A")
   if created and created != "N/A":
       try:
           created = datetime.fromisoformat(created.replace("Z", "+00:00")).strftime("%m/%d %H:%M")
       except:
           created = str(created)[:10]
   table.add_row(str(i+1), mem_id, mem["memory"], created)


console.print(table)


console.rule("[bold cyan]MODULE 9: Memory Deletion[/bold cyan]")


all_mems = memory.get_all(user_id=USER_ID).get("results", [])
if all_mems:
   last_mem = all_mems[-1]
   print(f"\n🗑️  Deleting memory: '{last_mem['memory']}'")
   memory.delete(memory_id=last_mem["id"])
  
   updated_count = len(memory.get_all(user_id=USER_ID).get("results", []))
   print(f"✅ Deleted. Remaining memories for {USER_ID}: {updated_count}")


console.rule("[bold cyan]✅ TUTORIAL COMPLETE[/bold cyan]")


summary = """
# 🎓 Mem0 Advanced Tutorial Summary


## What You Learned:
1. **Basic Setup** — Instantiate Memory with default & custom configs
2. **Add Memories** — From conversations (auto-extracted by LLM)
3. **Semantic Search** — Retrieve relevant memories by natural language query
4. **CRUD Operations** — Get, Update, Delete individual memories
5. **Memory-Augmented Chat** — Full pipeline: retrieve → respond → store
6. **Multi-User Isolation** — Separate memory namespaces per user_id
7. **Custom Configuration** — Custom LLM, embedder, and vector store
8. **Memory History** — View full memory profiles with timestamps
9. **Cleanup** — Delete specific or all memories


## Key Concepts:
- `memory.add(messages, user_id=...)`
- `memory.search(query, user_id=...)`
- `memory.get_all(user_id=...)`
- `memory.update(memory_id, data)`
- `memory.delete(memory_id)`
- `Memory.from_config(config)`


## Next Steps:
- Swap ChromaDB for Qdrant, Pinecone, or Weaviate
- Use the hosted Mem0 Platform (app.mem0.ai) for production
- Integrate with LangChain, CrewAI, or LangGraph agents
- Add `agent_id` for agent-level memory scoping
"""


console.print(Markdown(summary))

We create a fully custom Mem0 configuration with explicit parameters for the LLM, embedder, and vector store. We test the custom memory instance and explore memory history, timestamps, and structured profiling. Finally, we demonstrate deletion and cleanup operations, completing the full lifecycle management of long-term agent memory.

In conclusion, we implemented a complete memory infrastructure for AI agents using Mem0 as a universal memory abstraction layer. We demonstrated how to add, retrieve, update, delete, isolate, and customize long-term memories while integrating them into a dynamic chat loop. We showed how semantic memory retrieval transforms generic assistants into context-aware systems capable of personalization and continuity across sessions. With this foundation in place, we are now equipped to extend the architecture into multi-agent systems, enterprise-grade deployments, alternative vector databases, and advanced agent frameworks, turning memory into a core capability rather than an afterthought.


Check out the Full Implementation Code and Notebook. Also, feel free to follow us on Twitter and don’t forget to join our 130k+ ML SubReddit and Subscribe to our Newsletter. Wait! are you on telegram? now you can join us on telegram as well.

Need to partner with us for promoting your GitHub Repo OR Hugging Face Page OR Product Release OR Webinar etc.? Connect with us