Skip to main content

strands/context_manager/strategies/offload/
drop.rs

1//! The drop strategy: removes matching content from the context window entirely.
2
3use std::sync::Arc;
4
5use async_trait::async_trait;
6
7use super::base::{OffloadBehavior, OffloadCore};
8use super::conditions::OffloadConditions;
9use super::target::{OffloadTarget, block_type, media_kind};
10use crate::agent::{InvocationContext, LocalAgent};
11use crate::context_manager::archive::Archive;
12use crate::context_manager::message_trimming::{FormattedPlaceholder, remove_messages};
13use crate::context_manager::placeholder::{format_dropped, format_dropped_messages};
14use crate::context_manager::types::{ContextState, ContextStrategy};
15use crate::error::Result;
16use crate::types::{ContentBlock, Message, OffloadMethod, ToolResultContent};
17
18struct DropBehavior;
19
20#[async_trait]
21impl OffloadBehavior for DropBehavior {
22    async fn replace_block(
23        &self,
24        core: &OffloadCore,
25        block: &ContentBlock,
26        tokens: u64,
27        message: &Message,
28        _agent: &LocalAgent,
29        archive_ref: Option<&str>,
30        _tool_name: Option<&str>,
31        _invocation_context: Option<&InvocationContext>,
32    ) -> Result<Option<ContentBlock>> {
33        tracing::debug!(
34            "tracking_id=<{}>, block=<{}> | dropped block from context window",
35            message.tracking_id(),
36            block_type(block)
37        );
38        let placeholder = core.placeholder(&format_dropped(tokens, media_kind(block)), archive_ref, tokens);
39        if let ContentBlock::ToolResult(result) = block {
40            return Ok(Some(ContentBlock::ToolResult(
41                result.clone().with_content(vec![ToolResultContent::Text(placeholder)]),
42            )));
43        }
44        Ok(Some(ContentBlock::Text(placeholder)))
45    }
46
47    async fn apply_per_message(&self, core: &OffloadCore, context: &mut ContextState<'_>) -> Result<bool> {
48        let removable = core.removable_messages(context.agent).await?;
49        let text = FormattedPlaceholder::new(format_dropped_messages);
50        let archive = core.archive();
51        remove_messages(context.agent, &removable, &text, OffloadMethod::Drop, archive.as_ref()).await
52    }
53}
54
55/// Drops matching content from the context window (`Offload.drop`), built with
56/// [`Offload::drop`](super::Offload::drop).
57pub struct DropStrategy {
58    core: Arc<OffloadCore>,
59    behavior: Arc<DropBehavior>,
60}
61
62impl DropStrategy {
63    pub(crate) fn new(target: OffloadTarget, conditions: Option<OffloadConditions>) -> Result<Self> {
64        Ok(Self {
65            core: Arc::new(OffloadCore::new(OffloadMethod::Drop, target, conditions)?),
66            behavior: Arc::new(DropBehavior),
67        })
68    }
69
70    /// A copy of this strategy, with the same target, under `conditions` (`when`). A strategy keeps
71    /// per-agent state, so give each agent its own.
72    ///
73    /// # Errors
74    ///
75    /// An invalid condition value, or conditions that leave the strategy unable to run.
76    pub fn when(&self, conditions: OffloadConditions) -> Result<Self> {
77        Self::new(self.core.target().clone(), Some(conditions))
78    }
79}
80
81impl std::fmt::Debug for DropStrategy {
82    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83        f.debug_struct("DropStrategy")
84            .field("target", self.core.target())
85            .field("conditions", &self.core.offload_conditions)
86            .finish_non_exhaustive()
87    }
88}
89
90#[async_trait]
91impl ContextStrategy for DropStrategy {
92    fn name(&self) -> &str {
93        &self.core.name
94    }
95
96    fn init(&self, agent: &mut LocalAgent, archive: Option<&Archive>) -> Result<()> {
97        self.core.init(self.behavior.clone(), agent, archive)
98    }
99
100    async fn apply(&self, context: &mut ContextState<'_>) -> Result<bool> {
101        self.core.apply(self.behavior.as_ref(), context).await
102    }
103}