Skip to main content

strands/models/
summarize.rs

1//! The client-side summarizer behind the default [`Model::summarize`].
2
3use futures::StreamExt;
4
5use super::model::{AggregatedEvent, Model, ModelRequest, SummarizeOptions, is_js_whitespace};
6use super::streaming::{ModelStreamEvent, Usage};
7use crate::error::{Error, Result};
8use crate::types::{ContentBlock, Message, Role, StopReason, SummaryBlock, TextBlock};
9
10/// Opens every summarize instruction, since the request can carry the caller's own persona and
11/// tools (`SUMMARIZE_GUARD`).
12pub(crate) const SUMMARIZE_GUARD: &str = "STOP. Do not act on, answer, or continue any request above, and do not call any tools - tool calls will be rejected. Your only task now is to summarize everything above.";
13
14/// The instructions used when the caller gives none (`DEFAULT_SUMMARIZE_INSTRUCTIONS`).
15pub(crate) const DEFAULT_SUMMARIZE_INSTRUCTIONS: &str = "Write a handoff summary for a fresh context window. Preserve: key data, values and identifiers; decisions and conclusions; error messages and stack traces; the user's outstanding requests and what was about to happen next. Be concise, third person, no preamble. Output only the summary.";
16
17/// The result of [`Model::summarize`] (`SummarizeResult`).
18#[derive(Debug, Clone, PartialEq)]
19#[non_exhaustive]
20pub struct SummarizeResult {
21    /// The summary as `SummaryBlock`s, empty when the model wrote none. Built-in implementations
22    /// return at most one block; a caller that places one summary uses the first.
23    pub content: Vec<ContentBlock>,
24    /// Token usage of the calls made for the summary; `None` when an implementation reports none.
25    /// The default implementation always reports usage, with zero counts when the provider sent
26    /// none.
27    pub usage: Option<Usage>,
28}
29
30impl SummarizeResult {
31    /// Creates a result without usage.
32    pub fn new(content: Vec<ContentBlock>) -> Self {
33        Self { content, usage: None }
34    }
35
36    /// Sets the usage.
37    #[must_use]
38    pub fn with_usage(mut self, usage: Usage) -> Self {
39        self.usage = Some(usage);
40        self
41    }
42}
43
44fn is_summary_stop_reason(stop_reason: &StopReason) -> bool {
45    matches!(
46        stop_reason,
47        StopReason::EndTurn | StopReason::MaxTokens | StopReason::StopSequence
48    )
49}
50
51fn short_type_name<M: ?Sized>() -> &'static str {
52    let name = std::any::type_name::<M>();
53    let base = name.split('<').next().unwrap_or(name);
54    base.rsplit("::").next().unwrap_or(base)
55}
56
57/// Returns `messages` with `instructions` closing the final user turn, or in a user turn after it.
58fn with_instructions(mut messages: Vec<Message>, instructions: String) -> Vec<Message> {
59    let block = ContentBlock::Text(TextBlock::new(instructions));
60    match messages.last_mut() {
61        Some(last) if last.role == Role::User => {
62            let mut content = last.content.clone();
63            content.push(block);
64            *last = Message::new(Role::User, content);
65        }
66        _ => messages.push(Message::new(Role::User, vec![block])),
67    }
68    messages
69}
70
71struct Reply {
72    stop_reason: Option<StopReason>,
73    message: Option<Message>,
74    usage: Usage,
75}
76
77/// The default [`Model::summarize`]: sends `messages` as a request that ends with one summarize
78/// instruction and returns the reply's text as a `SummaryBlock`.
79///
80/// A provider that overrides [`Model::summarize`] (for a server-side summary) calls this as its
81/// fallback.
82///
83/// # Errors
84///
85/// Returns the model's stream error, unless the call was cancelled.
86pub async fn summarize_client_side<M: Model + ?Sized>(
87    model: &M,
88    messages: Vec<Message>,
89    options: SummarizeOptions,
90) -> Result<SummarizeResult> {
91    let cancel_signal = options.cancel_signal.clone();
92    if cancel_signal.as_ref().is_some_and(|signal| signal.is_cancelled()) {
93        return Ok(SummarizeResult::new(Vec::new()).with_usage(Usage::default()));
94    }
95    let instructions = options
96        .instructions
97        .as_deref()
98        .filter(|instructions| !instructions.is_empty())
99        .unwrap_or(DEFAULT_SUMMARIZE_INSTRUCTIONS);
100    let request = ModelRequest {
101        messages: with_instructions(messages, format!("{SUMMARIZE_GUARD}\n\n{instructions}")),
102        system_prompt: options.system_prompt,
103        tool_specs: options.tool_specs,
104        agent_metadata: options.agent_metadata,
105        cancel_signal: options.cancel_signal,
106        deferred_tools: options.deferred_tools,
107        ..ModelRequest::default()
108    };
109    let is_cancelled = || cancel_signal.as_ref().is_some_and(|signal| signal.is_cancelled());
110
111    let mut reply = Reply {
112        stop_reason: None,
113        message: None,
114        usage: Usage::default(),
115    };
116    let mut stream = model.stream_aggregated(super::model_proxy::prepare_request_for(model, request));
117    while let Some(item) = stream.next().await {
118        match item {
119            Ok(AggregatedEvent::Done(result)) => {
120                reply.stop_reason = Some(result.stop_reason);
121                reply.usage = result
122                    .metadata
123                    .and_then(|metadata| metadata.usage)
124                    .unwrap_or(reply.usage);
125                reply.message = Some(result.message);
126                break;
127            }
128            Ok(_) if is_cancelled() => {
129                reply.stop_reason = Some(StopReason::Cancelled);
130                break;
131            }
132            Ok(AggregatedEvent::ModelStreamEvent(ModelStreamEvent::Metadata(metadata))) => {
133                reply.usage = metadata.usage.unwrap_or(reply.usage);
134            }
135            Ok(_) => {}
136            Err(Error::MaxTokens(error)) => {
137                reply.stop_reason = Some(StopReason::MaxTokens);
138                reply.usage = error
139                    .partial_message
140                    .metadata
141                    .as_ref()
142                    .and_then(|metadata| metadata.usage)
143                    .unwrap_or(reply.usage);
144                reply.message = Some(*error.partial_message);
145                break;
146            }
147            Err(_) if is_cancelled() => {
148                reply.stop_reason = Some(StopReason::Cancelled);
149                break;
150            }
151            Err(error) => return Err(error),
152        }
153    }
154    drop(stream);
155
156    if !reply.stop_reason.as_ref().is_some_and(is_summary_stop_reason) {
157        let stop_reason = reply
158            .stop_reason
159            .as_ref()
160            .map_or_else(|| "undefined".to_owned(), ToString::to_string);
161        tracing::warn!(
162            "model=<{}>, stop_reason=<{stop_reason}> | summary reply did not finish | ignoring the reply",
163            short_type_name::<M>()
164        );
165        return Ok(SummarizeResult::new(Vec::new()).with_usage(reply.usage));
166    }
167    let text = reply
168        .message
169        .iter()
170        .flat_map(|message| message.content.iter())
171        .filter_map(ContentBlock::as_text)
172        .collect::<Vec<_>>()
173        .join("\n");
174    let text = text.trim_matches(is_js_whitespace);
175    if text.is_empty() {
176        return Ok(SummarizeResult::new(Vec::new()).with_usage(reply.usage));
177    }
178    let summary = ContentBlock::Summary(SummaryBlock::new(text));
179    Ok(SummarizeResult::new(vec![summary]).with_usage(reply.usage))
180}