Skip to main content

strands/memory/extraction/
model_extractor.rs

1//! An extractor that asks a model for facts.
2
3use std::fmt;
4use std::sync::Arc;
5
6use async_trait::async_trait;
7use futures::StreamExt;
8
9use super::{ExtractionResult, Extractor, ExtractorContext};
10use crate::error::{Error, Result};
11use crate::models::model_proxy::{ModelProxy, prepare_request_for};
12use crate::models::{AggregatedEvent, Model, ModelRequest, StreamAggregatedResult};
13use crate::telemetry::{EndModelSpanOptions, StartModelInvokeSpanOptions};
14use crate::types::{ContentBlock, JsonValue, Message, Role, SystemPrompt};
15
16/// Default guidance on what counts as a fact; a custom `system_prompt` replaces it.
17const DEFAULT_SYSTEM_PROMPT: &str = "You extract durable facts worth remembering across future conversations from a transcript.
18
19Each entry is one discrete, self-contained fact (a preference, decision, or stable detail about the user or task). Do not include transient chit-chat, questions, or anything already obvious.";
20
21/// The response shape the parser needs, appended after every system prompt.
22const OUTPUT_FORMAT: &str = r#"Return ONLY a JSON array of objects, each: {"content": string}. If there is nothing worth remembering, return []."#;
23
24/// Options for [`ModelExtractor`] (`ModelExtractorOptions`).
25#[derive(Clone, Default, bon::Builder)]
26pub struct ModelExtractorOptions {
27    /// The model that extracts facts. Resolution order: `this model > agent.aux_model >
28    /// agent.model`.
29    #[builder(into)]
30    pub model: Option<Arc<dyn Model>>,
31    /// What counts as a fact, replacing the default guidance. The JSON output format is always
32    /// appended after it.
33    #[builder(into)]
34    pub system_prompt: Option<String>,
35}
36
37impl fmt::Debug for ModelExtractorOptions {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        f.debug_struct("ModelExtractorOptions")
40            .field("model", &self.model.as_ref().map(|model| model.model_id()))
41            .field("system_prompt", &self.system_prompt)
42            .finish()
43    }
44}
45
46/// An [`Extractor`] that asks a model to distill messages into discrete facts
47/// (`ModelExtractor`). Malformed model output yields no entries (logged), never an error.
48#[derive(Clone)]
49pub struct ModelExtractor {
50    model: Option<Arc<dyn Model>>,
51    system_prompt: String,
52}
53
54impl ModelExtractor {
55    /// Creates the extractor.
56    #[must_use]
57    pub fn new(options: ModelExtractorOptions) -> Self {
58        let guidance = options.system_prompt.as_deref().unwrap_or(DEFAULT_SYSTEM_PROMPT);
59        Self {
60            model: options.model,
61            system_prompt: format!("{guidance}\n\n{OUTPUT_FORMAT}"),
62        }
63    }
64
65    /// The system prompt the model receives.
66    #[must_use]
67    pub fn system_prompt(&self) -> &str {
68        &self.system_prompt
69    }
70}
71
72impl Default for ModelExtractor {
73    fn default() -> Self {
74        Self::new(ModelExtractorOptions::default())
75    }
76}
77
78impl fmt::Debug for ModelExtractor {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        f.debug_struct("ModelExtractor")
81            .field("model", &self.model.as_ref().map(|model| model.model_id()))
82            .finish_non_exhaustive()
83    }
84}
85
86#[async_trait]
87impl Extractor for ModelExtractor {
88    async fn extract(&self, messages: &[Message], context: ExtractorContext) -> Result<Vec<ExtractionResult>> {
89        let Some(model) = self.model.clone().or(context.default_model) else {
90            return Err(Error::other(
91                "ModelExtractor: no model configured and no default model available",
92            ));
93        };
94        if messages.is_empty() {
95            return Ok(Vec::new());
96        }
97        // One user turn, so the system prompt governs extraction instead of the model continuing
98        // the transcript's roles.
99        let transcript = messages.iter().map(render_message).collect::<Vec<_>>().join("\n");
100        let prompt = vec![Message::user(format!(
101            "Extract facts from the following transcript:\n\n{transcript}"
102        ))];
103        let system_prompt = SystemPrompt::from(self.system_prompt.as_str());
104        let model_id = model.model_id();
105        let span = context.tracer.as_ref().map(|tracer| {
106            tracer.start_model_invoke_span(StartModelInvokeSpanOptions {
107                messages: &prompt,
108                model_id: model_id.as_deref(),
109                system_prompt: Some(&system_prompt),
110            })
111        });
112        let request = ModelRequest {
113            messages: prompt.clone(),
114            system_prompt: Some(system_prompt.clone()),
115            ..ModelRequest::default()
116        };
117        let result = match aggregate(model.as_ref(), request).await {
118            Ok(result) => result,
119            Err(error) => {
120                if let Some(span) = span {
121                    let message = error.to_string();
122                    span.end(EndModelSpanOptions {
123                        error: Some(&message),
124                        ..EndModelSpanOptions::default()
125                    });
126                }
127                return Err(error);
128            }
129        };
130        let metadata = result.metadata.as_ref();
131        if let Some(span) = span {
132            span.end(EndModelSpanOptions {
133                usage: metadata.and_then(|metadata| metadata.usage.as_ref()),
134                metrics: metadata.and_then(|metadata| metadata.metrics.as_ref()),
135                error: None,
136                output: Some(&result.message),
137                stop_reason: Some(result.stop_reason.as_str()),
138            });
139        }
140        if let Some(invocation_context) = &context.invocation_context {
141            ModelProxy::record(
142                metadata.and_then(|metadata| metadata.usage.as_ref()),
143                invocation_context,
144            );
145        }
146        let text: String = result
147            .message
148            .content
149            .iter()
150            .filter_map(ContentBlock::as_text)
151            .collect();
152        Ok(parse_entries(text.trim(), &model_name(model.as_ref())))
153    }
154
155    fn name(&self) -> &str {
156        "ModelExtractor"
157    }
158}
159
160/// Streams `request` and returns the aggregated result.
161async fn aggregate(model: &dyn Model, request: ModelRequest) -> Result<StreamAggregatedResult> {
162    let request = prepare_request_for(model, request);
163    let mut stream = model.stream_aggregated(request);
164    while let Some(event) = stream.next().await {
165        if let AggregatedEvent::Done(result) = event? {
166            return Ok(result);
167        }
168    }
169    Err(Error::other("ModelExtractor: model returned no response"))
170}
171
172fn model_name(model: &dyn Model) -> String {
173    model.model_id().unwrap_or_else(|| "unknown".to_owned())
174}
175
176/// Renders one message as `role: text`, joining its text blocks.
177fn render_message(message: &Message) -> String {
178    let text = message
179        .content
180        .iter()
181        .filter_map(ContentBlock::as_text)
182        .filter(|part| !part.is_empty())
183        .collect::<Vec<_>>()
184        .join("\n");
185    let role = match message.role {
186        Role::User => "user",
187        _ => "assistant",
188    };
189    format!("{role}: {text}")
190}
191
192/// Parses the model's reply: the first `[` to the last `]`, tolerating prose
193/// or a code fence around it.
194fn parse_entries(text: &str, model_name: &str) -> Vec<ExtractionResult> {
195    let Some(json) = extract_json_array(text) else {
196        tracing::warn!("model=<{model_name}> | ModelExtractor: no JSON array in model output, skipping");
197        return Vec::new();
198    };
199    let parsed = match serde_json::from_str::<JsonValue>(json) {
200        Ok(parsed) => parsed,
201        Err(error) => {
202            tracing::warn!("model=<{model_name}>, error=<{error}> | ModelExtractor: failed to parse output");
203            return Vec::new();
204        }
205    };
206    let JsonValue::Array(items) = parsed else {
207        return Vec::new();
208    };
209    items.iter().filter_map(entry_from).collect()
210}
211
212fn entry_from(item: &JsonValue) -> Option<ExtractionResult> {
213    let content = item.get("content")?.as_str()?.trim();
214    if content.is_empty() {
215        return None;
216    }
217    let entry = ExtractionResult::new(content);
218    Some(match item.get("metadata").and_then(JsonValue::as_object) {
219        Some(metadata) => entry.with_metadata(metadata.clone()),
220        None => entry,
221    })
222}
223
224fn extract_json_array(text: &str) -> Option<&str> {
225    let start = text.find('[')?;
226    let end = text.rfind(']')?;
227    (end >= start).then(|| &text[start..=end])
228}
229
230#[cfg(test)]
231mod tests;