Skip to main content

strands/memory/extraction/
mod.rs

1//! Automatic memory extraction: triggers decide when a store's unsaved messages are written,
2//! extractors decide how.
3
4use std::fmt;
5use std::sync::Arc;
6
7use async_trait::async_trait;
8use serde::{Deserialize, Serialize};
9
10use crate::agent::{InvocationContext, LocalAgent};
11use crate::error::Result;
12use crate::models::Model;
13use crate::telemetry::Tracer;
14use crate::types::{ContentBlock, JsonObject, Message};
15
16pub(crate) mod coordinator;
17mod model_extractor;
18pub(crate) mod resolve;
19mod triggers;
20
21#[cfg(test)]
22mod tests;
23
24pub use model_extractor::{ModelExtractor, ModelExtractorOptions, ModelExtractorOptionsBuilder};
25pub use triggers::{IntervalTrigger, IntervalTriggerOptions, IntervalTriggerOptionsBuilder, InvocationTrigger};
26
27/// A content block kind a [`MemoryMessageFilter`] can strip (`MemoryContentBlockType`): the
28/// block's wire key.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
30#[serde(rename_all = "camelCase")]
31#[non_exhaustive]
32pub enum MemoryContentBlockType {
33    /// `text`.
34    Text,
35    /// `toolUse`.
36    ToolUse,
37    /// `toolResult`.
38    ToolResult,
39    /// `reasoning`.
40    Reasoning,
41    /// `cachePoint`.
42    CachePoint,
43    /// `guardContent`.
44    GuardContent,
45    /// `audio`.
46    Audio,
47    /// `image`.
48    Image,
49    /// `video`.
50    Video,
51    /// `document`.
52    Document,
53    /// `citations`.
54    Citations,
55    /// `injected`.
56    Injected,
57    /// `summary`.
58    Summary,
59}
60
61impl MemoryContentBlockType {
62    /// The kind of a block; a block this version does not know has none.
63    pub(crate) fn of(block: &ContentBlock) -> Option<Self> {
64        Some(match block {
65            ContentBlock::Text(_) => Self::Text,
66            ContentBlock::ToolUse(_) => Self::ToolUse,
67            ContentBlock::ToolResult(_) => Self::ToolResult,
68            ContentBlock::Reasoning(_) => Self::Reasoning,
69            ContentBlock::CachePoint(_) => Self::CachePoint,
70            ContentBlock::GuardContent(_) => Self::GuardContent,
71            ContentBlock::Audio(_) => Self::Audio,
72            ContentBlock::Image(_) => Self::Image,
73            ContentBlock::Video(_) => Self::Video,
74            ContentBlock::Document(_) => Self::Document,
75            ContentBlock::Citations(_) => Self::Citations,
76            ContentBlock::Injected(_) => Self::Injected,
77            ContentBlock::Summary(_) => Self::Summary,
78            _ => return None,
79        })
80    }
81}
82
83/// Strips content blocks before extraction (`MemoryMessageFilter`); a message left empty is
84/// dropped. The default excludes tool traffic (`toolUse`, `toolResult`); pass an empty `exclude`
85/// to keep everything.
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87pub struct MemoryMessageFilter {
88    /// The block kinds to strip.
89    pub exclude: Vec<MemoryContentBlockType>,
90}
91
92impl Default for MemoryMessageFilter {
93    fn default() -> Self {
94        Self {
95            exclude: vec![MemoryContentBlockType::ToolUse, MemoryContentBlockType::ToolResult],
96        }
97    }
98}
99
100/// An entry an [`Extractor`] produced, written through the store's `add` (`ExtractionResult`).
101#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
102#[non_exhaustive]
103pub struct ExtractionResult {
104    /// The entry text.
105    pub content: String,
106    /// Metadata stored with the entry.
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub metadata: Option<JsonObject>,
109}
110
111impl ExtractionResult {
112    /// An entry with content only.
113    pub fn new(content: impl Into<String>) -> Self {
114        Self {
115            content: content.into(),
116            metadata: None,
117        }
118    }
119
120    /// Sets the metadata.
121    #[must_use]
122    pub fn with_metadata(mut self, metadata: JsonObject) -> Self {
123        self.metadata = Some(metadata);
124        self
125    }
126}
127
128/// What [`Extractor::extract`] gets besides the messages (`ExtractorContext`).
129#[derive(Clone, Default)]
130#[non_exhaustive]
131pub struct ExtractorContext {
132    /// The model an extractor without its own uses (`agent.aux_model`, which defaults to the
133    /// agent's model).
134    pub default_model: Option<Arc<dyn Model>>,
135    /// The request this extraction runs for: the call's usage adds to it, its limits do not apply.
136    pub invocation_context: Option<InvocationContext>,
137    /// The tracer of the extraction span, so a model call nests a `chat` span under it; `None`
138    /// for standalone use.
139    pub(crate) tracer: Option<Arc<Tracer>>,
140}
141
142impl ExtractorContext {
143    /// Sets the fallback model.
144    #[must_use]
145    pub fn with_default_model(mut self, model: Arc<dyn Model>) -> Self {
146        self.default_model = Some(model);
147        self
148    }
149
150    /// Sets the request the extraction runs for.
151    #[must_use]
152    pub fn with_invocation_context(mut self, invocation_context: Option<InvocationContext>) -> Self {
153        self.invocation_context = invocation_context;
154        self
155    }
156
157    pub(crate) fn with_tracer(mut self, tracer: Arc<Tracer>) -> Self {
158        self.tracer = Some(tracer);
159        self
160    }
161}
162
163impl fmt::Debug for ExtractorContext {
164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165        f.debug_struct("ExtractorContext")
166            .field(
167                "default_model",
168                &self.default_model.as_ref().map(|model| model.model_id()),
169            )
170            .finish_non_exhaustive()
171    }
172}
173
174/// Turns conversation messages into discrete entries (`Extractor`).
175#[async_trait]
176pub trait Extractor: Send + Sync + 'static {
177    /// Extracts entries from the filtered messages.
178    async fn extract(&self, messages: &[Message], context: ExtractorContext) -> Result<Vec<ExtractionResult>>;
179
180    /// The name the extraction span records as `memory.extractor`.
181    fn name(&self) -> &str {
182        "Extractor"
183    }
184}
185
186/// Starts a store's extraction in the background (`ExtractionTriggerContext.fire`).
187#[derive(Clone)]
188pub struct ExtractionFire(Arc<dyn Fn(Option<InvocationContext>) + Send + Sync>);
189
190impl ExtractionFire {
191    /// A fire handle that calls `fire`; the memory manager builds the real one, tests of a custom
192    /// [`ExtractionTrigger`] can record the calls.
193    pub fn new(fire: impl Fn(Option<InvocationContext>) + Send + Sync + 'static) -> Self {
194        Self(Arc::new(fire))
195    }
196
197    /// Saves the store's unsaved messages now, in the background; returns at once, so it never
198    /// blocks a hook. Pass the firing event's invocation context so a client-side extractor's
199    /// model call joins that request. To wait for the save, use
200    /// [`MemoryManager::flush`](crate::memory::MemoryManager::flush).
201    pub fn fire(&self, invocation_context: Option<InvocationContext>) {
202        (self.0)(invocation_context);
203    }
204}
205
206impl fmt::Debug for ExtractionFire {
207    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208        f.write_str("ExtractionFire(..)")
209    }
210}
211
212/// What [`ExtractionTrigger::attach`] gets (`ExtractionTriggerContext`).
213#[non_exhaustive]
214pub struct ExtractionTriggerContext<'a> {
215    /// The agent to register hooks on.
216    pub agent: &'a LocalAgent,
217    /// Starts extraction for the store this trigger is attached to.
218    pub fire: ExtractionFire,
219}
220
221impl<'a> ExtractionTriggerContext<'a> {
222    /// The context a trigger attaches to `agent` with, firing through `fire`.
223    ///
224    /// ```
225    /// use std::sync::Arc;
226    /// use std::sync::atomic::{AtomicUsize, Ordering};
227    /// use strands::memory::{ExtractionFire, ExtractionTrigger, ExtractionTriggerContext, InvocationTrigger};
228    /// use strands::testing::{MockModel, test_agent};
229    ///
230    /// let agent = test_agent(MockModel::new());
231    /// let fired = Arc::new(AtomicUsize::new(0));
232    /// let counter = fired.clone();
233    /// let fire = ExtractionFire::new(move |_| {
234    ///     counter.fetch_add(1, Ordering::SeqCst);
235    /// });
236    /// InvocationTrigger::new().attach(ExtractionTriggerContext::new(agent.local(), fire));
237    /// assert_eq!(fired.load(Ordering::SeqCst), 0);
238    /// ```
239    #[must_use]
240    pub fn new(agent: &'a LocalAgent, fire: ExtractionFire) -> Self {
241        Self { agent, fire }
242    }
243}
244
245impl fmt::Debug for ExtractionTriggerContext<'_> {
246    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
247        f.debug_struct("ExtractionTriggerContext")
248            .field("agent", &self.agent.id())
249            .finish_non_exhaustive()
250    }
251}
252
253/// Decides when a store's extraction runs (`ExtractionTrigger`): [`attach`](Self::attach)
254/// registers the hooks it needs and calls `fire` when extraction should happen. A trigger that
255/// never fires never extracts; [`MemoryManager::flush`](crate::memory::MemoryManager::flush)
256/// writes everything regardless.
257pub trait ExtractionTrigger: Send + Sync + 'static {
258    /// A stable name for the trigger kind, used in logs.
259    fn name(&self) -> &str;
260
261    /// Wires the trigger into the agent; called once per store when the manager initializes.
262    fn attach(&self, context: ExtractionTriggerContext<'_>);
263}
264
265/// A store's automatic-extraction configuration (`ExtractionConfig`).
266#[derive(Clone, Default, bon::Builder)]
267pub struct ExtractionConfig {
268    /// When extraction runs; it runs whenever any trigger fires. `None` is every 5 turns; an
269    /// empty list is rejected by the manager.
270    pub trigger: Option<Vec<Arc<dyn ExtractionTrigger>>>,
271    /// How messages become entries (client-side; the store must implement `add`). `None` hands
272    /// the raw messages to `add_messages` when the store implements it, and otherwise uses a
273    /// [`ModelExtractor`].
274    pub extractor: Option<Arc<dyn Extractor>>,
275    /// Block kinds to strip first. Defaults to [`MemoryMessageFilter::default`].
276    pub filter: Option<MemoryMessageFilter>,
277}
278
279impl ExtractionConfig {
280    /// Sets the triggers.
281    #[must_use]
282    pub fn with_trigger(mut self, triggers: impl IntoIterator<Item = Arc<dyn ExtractionTrigger>>) -> Self {
283        self.trigger = Some(triggers.into_iter().collect());
284        self
285    }
286
287    /// Sets the extractor.
288    #[must_use]
289    pub fn with_extractor(mut self, extractor: Arc<dyn Extractor>) -> Self {
290        self.extractor = Some(extractor);
291        self
292    }
293
294    /// Sets the filter.
295    #[must_use]
296    pub fn with_filter(mut self, filter: MemoryMessageFilter) -> Self {
297        self.filter = Some(filter);
298        self
299    }
300}
301
302impl fmt::Debug for ExtractionConfig {
303    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
304        f.debug_struct("ExtractionConfig")
305            .field(
306                "trigger",
307                &self
308                    .trigger
309                    .as_ref()
310                    .map(|triggers| triggers.iter().map(|trigger| trigger.name()).collect::<Vec<_>>()),
311            )
312            .field("extractor", &self.extractor.as_ref().map(|_| ".."))
313            .field("filter", &self.filter)
314            .finish()
315    }
316}