strands/memory/extraction/
mod.rs1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
30#[serde(rename_all = "camelCase")]
31#[non_exhaustive]
32pub enum MemoryContentBlockType {
33 Text,
35 ToolUse,
37 ToolResult,
39 Reasoning,
41 CachePoint,
43 GuardContent,
45 Audio,
47 Image,
49 Video,
51 Document,
53 Citations,
55 Injected,
57 Summary,
59}
60
61impl MemoryContentBlockType {
62 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87pub struct MemoryMessageFilter {
88 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#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
102#[non_exhaustive]
103pub struct ExtractionResult {
104 pub content: String,
106 #[serde(default, skip_serializing_if = "Option::is_none")]
108 pub metadata: Option<JsonObject>,
109}
110
111impl ExtractionResult {
112 pub fn new(content: impl Into<String>) -> Self {
114 Self {
115 content: content.into(),
116 metadata: None,
117 }
118 }
119
120 #[must_use]
122 pub fn with_metadata(mut self, metadata: JsonObject) -> Self {
123 self.metadata = Some(metadata);
124 self
125 }
126}
127
128#[derive(Clone, Default)]
130#[non_exhaustive]
131pub struct ExtractorContext {
132 pub default_model: Option<Arc<dyn Model>>,
135 pub invocation_context: Option<InvocationContext>,
137 pub(crate) tracer: Option<Arc<Tracer>>,
140}
141
142impl ExtractorContext {
143 #[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 #[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#[async_trait]
176pub trait Extractor: Send + Sync + 'static {
177 async fn extract(&self, messages: &[Message], context: ExtractorContext) -> Result<Vec<ExtractionResult>>;
179
180 fn name(&self) -> &str {
182 "Extractor"
183 }
184}
185
186#[derive(Clone)]
188pub struct ExtractionFire(Arc<dyn Fn(Option<InvocationContext>) + Send + Sync>);
189
190impl ExtractionFire {
191 pub fn new(fire: impl Fn(Option<InvocationContext>) + Send + Sync + 'static) -> Self {
194 Self(Arc::new(fire))
195 }
196
197 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#[non_exhaustive]
214pub struct ExtractionTriggerContext<'a> {
215 pub agent: &'a LocalAgent,
217 pub fire: ExtractionFire,
219}
220
221impl<'a> ExtractionTriggerContext<'a> {
222 #[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
253pub trait ExtractionTrigger: Send + Sync + 'static {
258 fn name(&self) -> &str;
260
261 fn attach(&self, context: ExtractionTriggerContext<'_>);
263}
264
265#[derive(Clone, Default, bon::Builder)]
267pub struct ExtractionConfig {
268 pub trigger: Option<Vec<Arc<dyn ExtractionTrigger>>>,
271 pub extractor: Option<Arc<dyn Extractor>>,
275 pub filter: Option<MemoryMessageFilter>,
277}
278
279impl ExtractionConfig {
280 #[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 #[must_use]
289 pub fn with_extractor(mut self, extractor: Arc<dyn Extractor>) -> Self {
290 self.extractor = Some(extractor);
291 self
292 }
293
294 #[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}