Memory
This example shows how to equip an agent with memory. By wiring an InMemoryStore into the agent, it gains tools to store and recall facts across turns within a session.
Prerequisites
Section titled “Prerequisites”ANTHROPIC_API_KEYenvironment variable set with a valid API key
Running
Section titled “Running”export ANTHROPIC_API_KEY="sk-..."cargo run -p heartbit --example memorySource
Section titled “Source”use std::sync::Arc;
use heartbit::{AgentRunner, AnthropicProvider, InMemoryStore};
#[tokio::main]async fn main() -> Result<(), Box<dyn std::error::Error>> { let api_key = std::env::var("ANTHROPIC_API_KEY").expect("set ANTHROPIC_API_KEY environment variable"); let provider = Arc::new(AnthropicProvider::new(api_key, "claude-sonnet-4-20250514"));
let memory = Arc::new(InMemoryStore::new());
let agent = AgentRunner::builder(provider) .name("memory-agent") .system_prompt( "You are an assistant with memory. Store important facts the user tells you \ and recall them when asked. Use memory tools proactively.", ) .memory(memory) .max_turns(10) .max_tokens(4096) .build()?;
let output = agent .execute("Remember that my favorite color is blue, then recall all your memories.") .await?;
println!("{}", output.result);
Ok(())}Walkthrough
Section titled “Walkthrough”Memory store — InMemoryStore::new() creates an in-memory store for development and testing. For production, Heartbit also provides PostgresMemoryStore for durable persistence across sessions.
Wiring memory — .memory(memory) on the builder automatically injects 5 memory tools into the agent:
memory_store— save a new memory with optional keywords and memory typememory_recall— search memories by query using BM25 scoringmemory_update— modify an existing memory entrymemory_forget— remove a memory by IDmemory_consolidate— merge related memories into higher-level summaries
Memory types — Memories are categorized as:
- Episodic (default) — specific events and interactions
- Semantic — general facts and knowledge
- Reflection — synthesized insights from multiple memories
How it works at runtime:
- The agent receives the user message
- It uses
memory_storeto save “favorite color is blue” as a fact - It uses
memory_recallto retrieve all stored memories - It responds with what it found
Turn budget — max_turns(10) allows enough room for the agent to make multiple tool calls (store + recall) within a single execution.
Advanced features — The memory system includes Ebbinghaus strength decay (memories weaken over time without reinforcement), automatic linking between related memories, and consolidation pipelines that cluster similar entries.
What to expect
Section titled “What to expect”The agent stores the fact and then recalls it:
I've stored that your favorite color is blue. Here are all my current memories:
1. Your favorite color is blue (stored just now)