Skip to content

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.

  • ANTHROPIC_API_KEY environment variable set with a valid API key
Terminal window
export ANTHROPIC_API_KEY="sk-..."
cargo run -p heartbit --example memory
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(())
}

Memory storeInMemoryStore::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 type
  • memory_recall — search memories by query using BM25 scoring
  • memory_update — modify an existing memory entry
  • memory_forget — remove a memory by ID
  • memory_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:

  1. The agent receives the user message
  2. It uses memory_store to save “favorite color is blue” as a fact
  3. It uses memory_recall to retrieve all stored memories
  4. It responds with what it found

Turn budgetmax_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.

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)