Skip to main content

strands/context_manager/strategies/
deferred_tool_loading.rs

1//! Deferred tool loading: keeps tools' input schemas out of the model's context until the model
2//! loads them. Build it with [`Offload::defer`](super::offload::Offload::defer).
3
4use std::collections::{HashMap, HashSet};
5use std::fmt;
6use std::sync::{Arc, Mutex, PoisonError};
7
8use async_trait::async_trait;
9
10use crate::agent::{LocalAgent, ToolAgent};
11use crate::context_manager::archive::Archive;
12use crate::context_manager::retrieval_tool::RETRIEVAL_TOOL_NAME;
13use crate::context_manager::strategies::offload::ConditionValue;
14use crate::context_manager::strategies::offload::conditions::{ConditionName, ParsedCondition, parse_condition_as};
15use crate::context_manager::strategies::offload::target::{OffloadTarget, OffloadTargetMatcher};
16use crate::context_manager::types::{ContextState, ContextStrategy};
17use crate::error::{Error, Result};
18use crate::logging::warn_once;
19use crate::middleware::{ExecuteToolContext, ExecuteToolResult, ExecuteToolStage, InvokeModelStage, StageStream};
20use crate::models::model_info::{default_context_window_limit, lookup_model};
21use crate::models::model_proxy::CallTools;
22use crate::models::{DeferredToolLoading, Model, heuristic_json};
23use crate::tools::{
24    DeferredToolsFn, LOAD_TOOLS_TOOL_NAME, STRUCTURED_OUTPUT_TOOL_NAME, SdkToolRole, Tool, ToolRegistry,
25    create_load_tools, has_sdk_tool_role,
26};
27use crate::types::{
28    ContentBlock, JsonValue, Message, TextBlock, ToolReferenceBlock, ToolResultBlock, ToolResultContent, ToolSpec,
29};
30
31/// The strategy name (`'offload:defer'`).
32const STRATEGY_NAME: &str = "offload:defer";
33
34/// SDK tools that are never deferred, since SDK-injected text tells the model to call them or they
35/// load the rest. The background-tasks manage tool is one too, recognized by its role since its
36/// name is configurable. `retrieve_offloaded_content` and `skills` are named for the
37/// `ContextOffloader` and `AgentSkills` tools.
38const PROTECTED_TOOL_NAMES: [&str; 5] = [
39    LOAD_TOOLS_TOOL_NAME,
40    RETRIEVAL_TOOL_NAME,
41    STRUCTURED_OUTPUT_TOOL_NAME,
42    "retrieve_offloaded_content",
43    "skills",
44];
45
46/// Input schema keywords that describe no parameter.
47const ANNOTATION_KEYWORDS: [&str; 4] = ["$schema", "type", "title", "description"];
48
49/// Which tools [`Offload::defer`](super::offload::Offload::defer) defers (`DeferTarget`).
50#[derive(Debug, Clone, PartialEq, Eq)]
51#[non_exhaustive]
52pub enum DeferTarget {
53    /// Every tool (`'toolSpecs'`).
54    ToolSpecs,
55    /// The named tools, each optionally `tool::<name>`; a leading `!` keeps a tool in full
56    /// instead. A list of only exclusions defers every other tool.
57    Tools(Vec<String>),
58}
59
60impl DeferTarget {
61    /// The named tools (`['shell', '!read']`).
62    pub fn tools(tools: impl IntoIterator<Item = impl Into<String>>) -> Self {
63        Self::Tools(tools.into_iter().map(Into::into).collect())
64    }
65
66    fn to_json(&self) -> String {
67        match self {
68            Self::ToolSpecs => "\"toolSpecs\"".to_owned(),
69            Self::Tools(tools) => serde_json::to_string(tools).unwrap_or_default(),
70        }
71    }
72}
73
74/// When [`Offload::defer`](super::offload::Offload::defer) defers tools (`DeferConditions`).
75///
76/// Checked on every model call against that call's tools; either condition is enough, and with
77/// none it defers at any tool count. The same tools and conditions always defer the same tools,
78/// so the tools list stays the same from call to call and after a session restore. A tool change
79/// that meets a condition mid-conversation defers from the next call on, so the model then loads
80/// tools it was calling directly.
81#[derive(Debug, Clone, Default, PartialEq, bon::Builder)]
82pub struct DeferConditions {
83    /// Tools in the call at or above which it defers: a whole number above 0. The SDK's own tools
84    /// count, but not the structured output tool, so an invocation with structured output defers
85    /// the same tools as one without.
86    #[builder(into)]
87    pub tool_count: Option<ConditionValue>,
88    /// Estimated tokens of the input schemas it would defer, at or above which it defers: a whole
89    /// number above 0, or `"5%"` of the context window.
90    #[builder(into)]
91    pub schema_tokens: Option<ConditionValue>,
92}
93
94/// A matcher for a list target, or `None` for `ToolSpecs`, which covers every tool.
95fn target_matcher(target: &DeferTarget) -> Result<Option<OffloadTargetMatcher>> {
96    let DeferTarget::Tools(entries) = target else {
97        return Ok(None);
98    };
99    if entries
100        .iter()
101        .any(|entry| entry == "toolSpecs" || entry == "!toolSpecs")
102    {
103        return Err(Error::other(format!(
104            "Offload.defer target {} lists 'toolSpecs', which is not a tool name: use 'toolSpecs' alone, or list only the tools to keep in full, such as ['!shell']",
105            target.to_json()
106        )));
107    }
108    OffloadTargetMatcher::new(OffloadTarget::Tools(entries.clone())).map(Some)
109}
110
111struct Inner {
112    target: DeferTarget,
113    /// Matches a list target's tool names; `None` for `ToolSpecs`, which covers every tool.
114    matcher: Option<OffloadTargetMatcher>,
115    tool_count: Option<usize>,
116    schema_tokens: Option<ParsedCondition>,
117    /// The tools each agent's latest model call deferred, by agent id.
118    deferred: Mutex<HashMap<String, HashSet<String>>>,
119}
120
121/// A strategy that keeps tools' input schemas out of the model's context until the model loads
122/// them with `load_tools` (`DeferStrategy`, built with
123/// [`Offload::defer`](super::offload::Offload::defer)).
124///
125/// On every model call it picks the tools to defer from that call's tools and passes their names
126/// on the call as its `deferred_tools`. The call's model decides how a deferred tool reaches it
127/// (`ModelCapabilities::deferred_tool_loading`); a model that can't defer tools gets every spec.
128/// The model still sees each deferred tool's name and description and loads a schema with
129/// `load_tools`, which the context manager registers. A call to a deferred tool before its load
130/// gets the schema back instead of running. SDK tools such as `load_tools` and `retrieve_context`
131/// are never deferred, nor is a tool that takes no parameters, since its stub would leave nothing
132/// out. It never changes the messages. One per context manager, the `deferredToolLoading` preset
133/// included.
134///
135/// ```
136/// use strands::context_manager::{DeferConditions, DeferTarget, Offload};
137///
138/// // From 20 tools, or once their schemas reach 5% of the context window, defer every one but shell's.
139/// let defer = Offload::defer(DeferTarget::tools(["!shell"]))?.when(DeferConditions {
140///     tool_count: Some(20.into()),
141///     schema_tokens: Some("5%".into()),
142/// })?;
143/// # let _ = defer;
144/// # Ok::<(), strands::Error>(())
145/// ```
146#[derive(Clone)]
147pub struct DeferStrategy {
148    inner: Arc<Inner>,
149}
150
151impl fmt::Debug for DeferStrategy {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        f.debug_struct("DeferStrategy")
154            .field("target", &self.inner.target)
155            .field("tool_count", &self.inner.tool_count)
156            .field("schema_tokens", &self.inner.schema_tokens)
157            .finish_non_exhaustive()
158    }
159}
160
161impl DeferStrategy {
162    /// # Errors
163    ///
164    /// A target that is an empty list, lists `toolSpecs`, or excludes every tool it includes, or
165    /// a condition that is out of range.
166    pub(crate) fn new(target: DeferTarget, conditions: DeferConditions) -> Result<Self> {
167        let DeferConditions {
168            tool_count,
169            schema_tokens,
170        } = conditions;
171        let matcher = target_matcher(&target)?;
172        let tool_count = parse_tool_count(tool_count.as_ref())?;
173        let schema_tokens = parse_condition_as(ConditionName::BlockThreshold, schema_tokens.as_ref(), "schemaTokens")?;
174        Ok(Self {
175            inner: Arc::new(Inner {
176                target,
177                matcher,
178                tool_count,
179                schema_tokens,
180                deferred: Mutex::default(),
181            }),
182        })
183    }
184
185    /// A copy of this strategy with these conditions in place of its current ones (`when`).
186    ///
187    /// # Errors
188    ///
189    /// A `tool_count` that is not a whole number above 0, or a `schema_tokens` that is not a whole
190    /// number above 0 or a `"N%"` string below `"100%"`.
191    pub fn when(&self, conditions: DeferConditions) -> Result<Self> {
192        Self::new(self.inner.target.clone(), conditions)
193    }
194
195    /// The tools `load_tools` loads: the ones the agent's latest model call deferred. Before the
196    /// agent's first call, as when an interrupted load resumes on a restored agent, every
197    /// registered tool the target covers, since which of them the next call defers depends on that
198    /// call's tools and model.
199    pub(crate) fn deferred_tools(&self, agent: &ToolAgent) -> Vec<String> {
200        if let Some(recorded) = self.recorded(agent.id()) {
201            return recorded.into_iter().collect();
202        }
203        let registry = agent.tool_registry();
204        registry
205            .list()
206            .iter()
207            .filter(|tool| self.targets(registry, &tool.tool_spec()))
208            .map(|tool| tool.name().to_owned())
209            .collect()
210    }
211
212    /// The tools an agent's model call with these tool specs on this model sends: every spec and
213    /// the names of the ones it defers, or every spec but `load_tools` when it defers none
214    /// (`callTools`).
215    pub(crate) fn call_tools(
216        &self,
217        registry: &ToolRegistry,
218        tool_specs: &[ToolSpec],
219        model: &Arc<dyn Model>,
220    ) -> CallTools {
221        let deferred = if defers_tools(model.as_ref()) {
222            self.to_defer(registry, tool_specs, model.as_ref())
223        } else {
224            HashSet::new()
225        };
226        if !deferred.is_empty() {
227            return CallTools {
228                tool_specs: tool_specs.to_vec(),
229                deferred_tools: deferred,
230            };
231        }
232        CallTools {
233            tool_specs: tool_specs
234                .iter()
235                .filter(|spec| spec.name != LOAD_TOOLS_TOOL_NAME)
236                .cloned()
237                .collect(),
238            deferred_tools: HashSet::new(),
239        }
240    }
241
242    /// The `load_tools` tool, which loads the tools this strategy deferred on the calling agent's
243    /// latest model call.
244    pub(crate) fn load_tools(&self) -> Arc<dyn Tool> {
245        let strategy = self.clone();
246        let deferred: DeferredToolsFn = Arc::new(move |agent: &ToolAgent| strategy.deferred_tools(agent));
247        create_load_tools(deferred)
248    }
249
250    fn recorded(&self, agent_id: &str) -> Option<HashSet<String>> {
251        self.inner
252            .deferred
253            .lock()
254            .unwrap_or_else(PoisonError::into_inner)
255            .get(agent_id)
256            .cloned()
257    }
258
259    /// Records the tools an agent's call defers, and logs when they differ from its previous
260    /// call's.
261    fn record(&self, agent_id: &str, deferred: &HashSet<String>, model: &dyn Model) {
262        let mut records = self.inner.deferred.lock().unwrap_or_else(PoisonError::into_inner);
263        let changed = records
264            .get(agent_id)
265            .map_or(!deferred.is_empty(), |previous| previous != deferred);
266        if changed {
267            tracing::debug!(
268                "model_id=<{}>, deferred=<{}> | deferred tools changed",
269                model.model_id().unwrap_or_default(),
270                deferred.len()
271            );
272        }
273        records.insert(agent_id.to_owned(), deferred.clone());
274    }
275
276    /// Defers this call's tools, or sends every spec without the loader when the call defers
277    /// none.
278    fn render(&self, agent: &ToolAgent, tool_specs: &[ToolSpec], model: &Arc<dyn Model>) -> CallTools {
279        let registry = agent.tool_registry();
280        let tools = self.call_tools(registry, tool_specs, model);
281        self.record(agent.id(), &tools.deferred_tools, model.as_ref());
282        let model_id = model.model_id().unwrap_or_default();
283        if !defers_tools(model.as_ref()) && !self.to_defer(registry, tool_specs, model.as_ref()).is_empty() {
284            warn_once(&format!(
285                "model_id=<{model_id}> | model or its config can not defer tool schemas | sending every tool spec"
286            ));
287        }
288        if !tools.deferred_tools.is_empty() && takes_stubs_by_default(model.as_ref()) {
289            warn_once(&format!(
290                "model_id=<{model_id}> | model is not in the shared model info | sending deferred tools as stubs, set modelInfo.capabilities.deferredToolLoading to unsupported if it calls them badly"
291            ));
292        }
293        tools
294    }
295
296    /// The tools among these specs the target covers, when either condition is met; none
297    /// otherwise.
298    fn to_defer(&self, registry: &ToolRegistry, tool_specs: &[ToolSpec], model: &dyn Model) -> HashSet<String> {
299        let candidates: Vec<&ToolSpec> = tool_specs.iter().filter(|spec| self.targets(registry, spec)).collect();
300        if !self.conditions_met(&candidates, tool_specs, model) {
301            return HashSet::new();
302        }
303        candidates.into_iter().map(|spec| spec.name.clone()).collect()
304    }
305
306    /// Whether the target covers the agent's tool and the tool may be deferred.
307    fn targets(&self, registry: &ToolRegistry, spec: &ToolSpec) -> bool {
308        let tool = registry.get(&spec.name);
309        if PROTECTED_TOOL_NAMES.contains(&spec.name.as_str())
310            || has_sdk_tool_role(tool, SdkToolRole::ManageBackgroundTasks)
311        {
312            return false;
313        }
314        // The tool's own schema, since background tasks add a parameter to every schema in the call.
315        let own = tool.map(|tool| tool.tool_spec());
316        if !takes_parameters(own.as_ref().unwrap_or(spec)) {
317            return false;
318        }
319        self.inner
320            .matcher
321            .as_ref()
322            .is_none_or(|matcher| matcher.matches_tool(&spec.name))
323    }
324
325    /// Whether either condition is met, or there are none. `tool_count` counts every tool in the
326    /// call but the structured output tool, the SDK's own and those kept in full included;
327    /// `schema_tokens` measures what deferring saves.
328    fn conditions_met(&self, candidates: &[&ToolSpec], tool_specs: &[ToolSpec], model: &dyn Model) -> bool {
329        if self.unconditioned() {
330            return true;
331        }
332        let tool_count = tool_specs
333            .iter()
334            .filter(|spec| spec.name != STRUCTURED_OUTPUT_TOOL_NAME)
335            .count();
336        if self.inner.tool_count.is_some_and(|threshold| tool_count >= threshold) {
337            return true;
338        }
339        let Some(schema_tokens) = self.inner.schema_tokens else {
340            return false;
341        };
342        let measured: u64 = candidates.iter().map(|spec| heuristic_json(&input_schema(spec))).sum();
343        let window = model
344            .model_info()
345            .limits
346            .context_window
347            .filter(|window| *window > 0)
348            .unwrap_or_else(default_context_window_limit);
349        measured >= schema_tokens.of(window)
350    }
351
352    /// Whether the strategy has no conditions, so it defers at any tool count.
353    fn unconditioned(&self) -> bool {
354        self.inner.tool_count.is_none() && self.inner.schema_tokens.is_none()
355    }
356
357    /// Answers a call to a tool the latest model call deferred, made before the conversation
358    /// loaded its schema, with the schema instead of running the tool: a stub takes any input, and
359    /// once a summary removes a load the model can call a deferred tool from memory. Loads are read
360    /// from the messages, so a load that was summarized away is delivered again. Before the agent's
361    /// first model call, as when an interrupted call resumes on a restored agent, the guard uses
362    /// the tools a model call would defer with the agent's tools and model, so an approved call to
363    /// a tool that wouldn't be deferred runs.
364    fn unloaded_answer(&self, context: &ExecuteToolContext) -> Option<ToolResultBlock> {
365        let agent = &context.agent;
366        let name = &context.tool_use.name;
367        context.tool.as_ref()?;
368        let deferred = self.recorded(agent.id()).unwrap_or_else(|| {
369            let registry = agent.tool_registry();
370            self.call_tools(registry, &registry.tool_specs(), agent.model())
371                .deferred_tools
372        });
373        if !deferred.contains(name) || loaded_tools(agent.messages()).contains(name) {
374            return None;
375        }
376        Some(ToolResultBlock::error(
377            context.tool_use.tool_use_id.clone(),
378            vec![
379                ToolResultContent::Text(TextBlock::new(format!(
380                    "Not run: {name} was called before its parameters were loaded. They are loaded now; call it again."
381                ))),
382                ToolReferenceBlock::new(name.clone()).into(),
383            ],
384        ))
385    }
386}
387
388#[async_trait]
389impl ContextStrategy for DeferStrategy {
390    fn name(&self) -> &str {
391        STRATEGY_NAME
392    }
393
394    fn init(&self, agent: &mut LocalAgent, _archive: Option<&Archive>) -> Result<()> {
395        if self.unconditioned() {
396            warn_once(&format!(
397                "strategy=<{STRATEGY_NAME}>, target=<{}> | strategy has no conditions, so it defers every tool it targets at any tool count | use .when() to set toolCount or schemaTokens",
398                self.inner.target.to_json()
399            ));
400        }
401        let render = self.clone();
402        agent.add_middleware(InvokeModelStage::input(move |mut context| {
403            let tools = render.render(&context.agent, &context.tool_specs, &context.model);
404            context.tool_specs = tools.tool_specs;
405            context.deferred_tools = tools.deferred_tools;
406            async move { Ok(context) }
407        }));
408        let guard = self.clone();
409        agent.add_middleware(ExecuteToolStage::wrap(move |context, next| {
410            match guard.unloaded_answer(&context) {
411                Some(result) => StageStream::from_result(Ok(ExecuteToolResult::new(result))),
412                None => next.call(context),
413            }
414        }));
415        Ok(())
416    }
417
418    /// Messages are never changed; the tools list is rendered on each model call.
419    async fn apply(&self, _context: &mut ContextState<'_>) -> Result<bool> {
420        Ok(false)
421    }
422
423    fn as_defer_strategy(&self) -> Option<&DeferStrategy> {
424        Some(self)
425    }
426}
427
428fn parse_tool_count(raw: Option<&ConditionValue>) -> Result<Option<usize>> {
429    match raw {
430        None => Ok(None),
431        #[allow(
432            clippy::cast_possible_truncation,
433            clippy::cast_sign_loss,
434            reason = "a whole tool count above 0"
435        )]
436        Some(ConditionValue::Number(count)) if count.fract() == 0.0 && *count >= 1.0 => Ok(Some(*count as usize)),
437        Some(other) => Err(Error::other(format!(
438            "toolCount={other} is invalid: expected a whole tool count above 0"
439        ))),
440    }
441}
442
443fn input_schema(spec: &ToolSpec) -> JsonValue {
444    spec.input_schema
445        .clone()
446        .unwrap_or_else(|| JsonValue::Object(serde_json::Map::new()))
447}
448
449/// The tools a tool result in these messages loaded with a tool reference.
450fn loaded_tools(messages: &[Message]) -> HashSet<String> {
451    messages
452        .iter()
453        .flat_map(|message| &message.content)
454        .filter_map(|block| match block {
455            ContentBlock::ToolResult(result) => Some(&result.content),
456            _ => None,
457        })
458        .flatten()
459        .filter_map(|content| match content {
460            ToolResultContent::ToolReference(reference) => Some(reference.name.clone()),
461            _ => None,
462        })
463        .collect()
464}
465
466/// Whether a tool's input schema describes parameters, which its stub leaves out.
467fn takes_parameters(spec: &ToolSpec) -> bool {
468    let Some(JsonValue::Object(schema)) = &spec.input_schema else {
469        return false;
470    };
471    let non_empty = |key: &str, empty: fn(&JsonValue) -> bool| schema.get(key).is_some_and(|value| !empty(value));
472    non_empty("properties", |value| {
473        value.as_object().is_some_and(serde_json::Map::is_empty)
474    }) || non_empty("required", |value| value.as_array().is_some_and(Vec::is_empty))
475        || schema.get("additionalProperties").is_some_and(JsonValue::is_object)
476        || schema.keys().any(|keyword| {
477            !ANNOTATION_KEYWORDS.contains(&keyword.as_str())
478                && !["properties", "required", "additionalProperties"].contains(&keyword.as_str())
479        })
480}
481
482/// Whether the model gets stubs only because nothing says otherwise: not the shared model info,
483/// not its config.
484fn takes_stubs_by_default(model: &dyn Model) -> bool {
485    model.model_info().capabilities.deferred_tool_loading == Some(DeferredToolLoading::Stubs)
486        && model
487            .get_config()
488            .model_info
489            .is_none_or(|info| info.capabilities.deferred_tool_loading.is_none())
490        && lookup_model(&model.model_id().unwrap_or_default()).is_none()
491}
492
493/// Whether the model defers tools, which only a model that sends every full spec doesn't.
494fn defers_tools(model: &dyn Model) -> bool {
495    model
496        .model_info()
497        .capabilities
498        .deferred_tool_loading
499        .unwrap_or(DeferredToolLoading::Unsupported)
500        != DeferredToolLoading::Unsupported
501}
502
503#[cfg(test)]
504#[path = "deferred_tool_loading/tests.rs"]
505mod tests;