Skip to main content

strands/agent/
invocation_context.rs

1//! The request an invocation belongs to: its limits and usage.
2
3use std::fmt;
4use std::sync::{Arc, Mutex, PoisonError};
5
6use crate::error::{Error, Result};
7use crate::models::streaming::Usage;
8use crate::types::StopReason;
9
10/// Limits for the request a top-level `invoke` or `stream` call starts (`InvokeLimits`).
11///
12/// Every limit is optional; `None` means no limit on that dimension. Token limits count every
13/// model call in the request and are checked before each turn, so the last turn can go over.
14/// When several limits are reached at once the stop reason follows the order turns, total tokens,
15/// output tokens, structured output attempts.
16#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, bon::Builder)]
17pub struct InvokeLimits {
18    /// Maximum turns (one model call plus the tool calls it requests) across the request.
19    pub turns: Option<u64>,
20    /// Maximum model-generated tokens across every model call in the request.
21    pub output_tokens: Option<u64>,
22    /// Maximum input plus output tokens across every model call in the request.
23    pub total_tokens: Option<u64>,
24    /// Maximum failed structured output attempts across the request.
25    pub structured_output_attempts: Option<u64>,
26}
27
28/// One of the [`InvokeLimits`] (`keyof InvokeLimits`).
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30#[non_exhaustive]
31pub enum LimitKey {
32    /// [`InvokeLimits::turns`].
33    Turns,
34    /// [`InvokeLimits::output_tokens`].
35    OutputTokens,
36    /// [`InvokeLimits::total_tokens`].
37    TotalTokens,
38    /// [`InvokeLimits::structured_output_attempts`].
39    StructuredOutputAttempts,
40}
41
42impl LimitKey {
43    /// The key's name, as used in error messages.
44    #[must_use]
45    pub fn as_str(self) -> &'static str {
46        match self {
47            Self::Turns => "turns",
48            Self::OutputTokens => "outputTokens",
49            Self::TotalTokens => "totalTokens",
50            Self::StructuredOutputAttempts => "structuredOutputAttempts",
51        }
52    }
53}
54
55const LIMIT_KEYS: [LimitKey; 4] = [
56    LimitKey::Turns,
57    LimitKey::OutputTokens,
58    LimitKey::TotalTokens,
59    LimitKey::StructuredOutputAttempts,
60];
61
62impl InvokeLimits {
63    /// The value of one limit.
64    #[must_use]
65    pub fn get(&self, key: LimitKey) -> Option<u64> {
66        match key {
67            LimitKey::Turns => self.turns,
68            LimitKey::OutputTokens => self.output_tokens,
69            LimitKey::TotalTokens => self.total_tokens,
70            LimitKey::StructuredOutputAttempts => self.structured_output_attempts,
71        }
72    }
73
74    /// Checks that every set limit is positive, so a zero limit fails fast instead of stopping
75    /// the call at once.
76    ///
77    /// # Errors
78    ///
79    /// `limits.<key> must be a positive finite number, got 0` for a zero limit.
80    pub fn validate(&self) -> Result<()> {
81        let zero = LIMIT_KEYS.into_iter().find(|key| self.get(*key) == Some(0));
82        match zero {
83            Some(key) => Err(Error::other(format!(
84                "limits.{} must be a positive finite number, got 0",
85                key.as_str()
86            ))),
87            None => Ok(()),
88        }
89    }
90}
91
92/// What the work in an [`InvocationContext`] has used (`InvocationContextUsage`): its turns and the
93/// token usage of every model call, nested and auxiliary calls included.
94#[derive(Debug, Clone, Default, PartialEq, Eq)]
95#[non_exhaustive]
96pub struct InvocationContextUsage {
97    /// Turns taken in the context, including its nested calls.
98    pub turns_taken: u64,
99    /// Token usage of every model call in the context.
100    pub usage: Usage,
101}
102
103#[derive(Default)]
104struct Counters {
105    usage: InvocationContextUsage,
106    structured_output_failures: u64,
107}
108
109struct Inner {
110    limits: Option<InvokeLimits>,
111    parent: Option<InvocationContext>,
112    auxiliary: bool,
113    counters: Mutex<Counters>,
114}
115
116/// Handle to the request an object belongs to (`InvocationContext`).
117///
118/// A top-level `invoke` or `stream` call starts a request; the SDK attaches its handle to the
119/// events, tool contexts and results it hands out. Pass it to a nested call to run in the same
120/// request and share its limits and usage. Only the SDK creates one; its state is read-only.
121/// Clones refer to the same request.
122#[derive(Clone)]
123pub struct InvocationContext {
124    inner: Arc<Inner>,
125}
126
127#[cfg_attr(not(test), expect(dead_code, reason = "some helpers are used only by tests"))]
128impl InvocationContext {
129    fn from_parts(limits: Option<InvokeLimits>, parent: Option<Self>, auxiliary: bool) -> Self {
130        Self {
131            inner: Arc::new(Inner {
132                limits,
133                parent,
134                auxiliary,
135                counters: Mutex::default(),
136            }),
137        }
138    }
139
140    /// Starts a request with `limits` (`new InvocationContextImpl(limits)`).
141    pub(crate) fn new(limits: Option<InvokeLimits>) -> Self {
142        Self::from_parts(limits, None, false)
143    }
144
145    /// A nested call with its own limits, bound by the parent's too.
146    pub(crate) fn nested(limits: Option<InvokeLimits>, parent: &Self) -> Self {
147        Self::from_parts(limits, Some(parent.clone()), false)
148    }
149
150    /// Joins `inherited`, or starts a new request with `limits`. A
151    /// nested call that sets its own limits gets child state bound by both.
152    pub(crate) fn resolve(limits: Option<InvokeLimits>, inherited: Option<&Self>) -> Result<Self> {
153        if let Some(limits) = &limits {
154            limits.validate()?;
155        }
156        Ok(match (inherited, limits) {
157            (None, limits) => Self::new(limits),
158            (Some(inherited), None) => inherited.clone(),
159            (Some(inherited), Some(limits)) => Self::nested(Some(limits), inherited),
160        })
161    }
162
163    /// The context for an auxiliary call made for `parent`:
164    /// its tokens add to the request's usage, but no limits apply and its turns do not count.
165    pub(crate) fn auxiliary(parent: Option<&Self>) -> Option<Self> {
166        parent.map(|parent| Self::from_parts(None, Some(parent.clone()), true))
167    }
168
169    fn counters(&self) -> std::sync::MutexGuard<'_, Counters> {
170        self.inner.counters.lock().unwrap_or_else(PoisonError::into_inner)
171    }
172
173    /// What the work in this context has used so far; it keeps growing while that work runs.
174    #[must_use]
175    pub fn usage(&self) -> InvocationContextUsage {
176        self.counters().usage.clone()
177    }
178
179    /// The limits checked against this context's usage.
180    #[must_use]
181    pub fn limits(&self) -> Option<&InvokeLimits> {
182        self.inner.limits.as_ref()
183    }
184
185    /// Failed structured output attempts counted under this context.
186    #[must_use]
187    pub(crate) fn structured_output_failures(&self) -> u64 {
188        self.counters().structured_output_failures
189    }
190
191    /// The parent whose limits also apply to this context.
192    fn limiting_parent(&self) -> Option<&Self> {
193        if self.inner.auxiliary {
194            return None;
195        }
196        self.inner.parent.as_ref()
197    }
198
199    /// Adds one model call's usage here and in every parent.
200    pub(crate) fn record_usage(&self, usage: &Usage) {
201        self.counters().usage.usage.accumulate(usage);
202        if let Some(parent) = &self.inner.parent {
203            parent.record_usage(usage);
204        }
205    }
206
207    /// Counts one turn here and in every parent whose limits apply.
208    pub(crate) fn record_turn(&self) {
209        let turns = &mut self.counters().usage.turns_taken;
210        *turns = turns.saturating_add(1);
211        if let Some(parent) = self.limiting_parent() {
212            parent.record_turn();
213        }
214    }
215
216    /// Counts one failed structured output attempt here and in every parent whose limits apply.
217    pub(crate) fn record_structured_output_failure(&self) {
218        let failures = &mut self.counters().structured_output_failures;
219        *failures = failures.saturating_add(1);
220        if let Some(parent) = self.limiting_parent() {
221            parent.record_structured_output_failure();
222        }
223    }
224
225    /// Whether this context or a parent whose limits apply sets the limit `key`.
226    #[must_use]
227    pub(crate) fn has_limit(&self, key: LimitKey) -> bool {
228        let own = self.inner.limits.is_some_and(|limits| limits.get(key).is_some());
229        own || self.limiting_parent().is_some_and(|parent| parent.has_limit(key))
230    }
231
232    /// The stop reason of the first limit reached, own limits first, then each limiting parent's.
233    #[must_use]
234    pub(crate) fn reached_limit(&self) -> Option<StopReason> {
235        self.reached_own_limit()
236            .or_else(|| self.limiting_parent().and_then(Self::reached_limit))
237    }
238
239    fn reached_own_limit(&self) -> Option<StopReason> {
240        let limits = self.inner.limits?;
241        let counters = self.counters();
242        let usage = &counters.usage;
243        let checks = [
244            (limits.turns, usage.turns_taken, StopReason::LimitTurns),
245            (
246                limits.total_tokens,
247                usage.usage.total_tokens,
248                StopReason::LimitTotalTokens,
249            ),
250            (
251                limits.output_tokens,
252                usage.usage.output_tokens,
253                StopReason::LimitOutputTokens,
254            ),
255            (
256                limits.structured_output_attempts,
257                counters.structured_output_failures,
258                StopReason::LimitStructuredOutputAttempts,
259            ),
260        ];
261        checks
262            .into_iter()
263            .find_map(|(limit, used, reason)| limit.is_some_and(|limit| used >= limit).then_some(reason))
264    }
265
266    /// Whether two handles refer to the same context.
267    #[must_use]
268    pub fn ptr_eq(&self, other: &Self) -> bool {
269        Arc::ptr_eq(&self.inner, &other.inner)
270    }
271}
272
273impl fmt::Debug for InvocationContext {
274    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275        f.debug_struct("InvocationContext")
276            .field("limits", &self.inner.limits)
277            .field("usage", &self.usage())
278            .finish_non_exhaustive()
279    }
280}
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285
286    fn limits(turns: Option<u64>, structured_output_attempts: Option<u64>) -> Option<InvokeLimits> {
287        Some(InvokeLimits {
288            turns,
289            structured_output_attempts,
290            ..InvokeLimits::default()
291        })
292    }
293
294    #[test]
295    fn counts_toward_limiting_parents_but_not_through_an_auxiliary_call() {
296        let request = InvocationContext::new(limits(None, Some(2)));
297        let nested = InvocationContext::nested(limits(Some(5), None), &request);
298        let auxiliary = InvocationContext::auxiliary(Some(&request)).unwrap();
299
300        nested.record_structured_output_failure();
301        auxiliary.record_structured_output_failure();
302
303        assert_eq!(request.structured_output_failures(), 1);
304        assert_eq!(nested.reached_limit(), None);
305        nested.record_structured_output_failure();
306        assert_eq!(nested.reached_limit(), Some(StopReason::LimitStructuredOutputAttempts));
307    }
308
309    #[test]
310    fn sees_the_limits_of_limiting_parents_only() {
311        let request = InvocationContext::new(limits(None, Some(2)));
312        let auxiliary = InvocationContext::auxiliary(Some(&request)).unwrap();
313
314        assert_eq!(
315            [
316                InvocationContext::nested(limits(Some(5), None), &request)
317                    .has_limit(LimitKey::StructuredOutputAttempts),
318                auxiliary.has_limit(LimitKey::StructuredOutputAttempts),
319                InvocationContext::new(limits(Some(5), None)).has_limit(LimitKey::StructuredOutputAttempts),
320            ],
321            [true, false, false]
322        );
323    }
324
325    #[test]
326    fn usage_adds_to_every_parent_and_turns_skip_auxiliary_parents() {
327        let request = InvocationContext::new(None);
328        let auxiliary = InvocationContext::auxiliary(Some(&request)).unwrap();
329        auxiliary.record_usage(&Usage::new(3, 2, 5));
330        auxiliary.record_turn();
331        assert_eq!(request.usage().usage, Usage::new(3, 2, 5));
332        assert_eq!(request.usage().turns_taken, 0);
333        assert_eq!(auxiliary.usage().turns_taken, 1);
334    }
335
336    #[test]
337    fn reached_limit_checks_turns_before_tokens() {
338        let context = InvocationContext::new(Some(InvokeLimits {
339            turns: Some(1),
340            total_tokens: Some(5),
341            ..InvokeLimits::default()
342        }));
343        context.record_usage(&Usage::new(3, 2, 5));
344        assert_eq!(context.reached_limit(), Some(StopReason::LimitTotalTokens));
345        context.record_turn();
346        assert_eq!(context.reached_limit(), Some(StopReason::LimitTurns));
347    }
348
349    #[test]
350    fn resolve_joins_or_nests_and_rejects_zero_limits() {
351        let request = InvocationContext::resolve(None, None).unwrap();
352        assert!(
353            InvocationContext::resolve(None, Some(&request))
354                .unwrap()
355                .ptr_eq(&request)
356        );
357        let nested = InvocationContext::resolve(limits(Some(2), None), Some(&request)).unwrap();
358        assert!(!nested.ptr_eq(&request));
359        assert!(nested.has_limit(LimitKey::Turns));
360        let error = InvocationContext::resolve(limits(Some(0), None), None).unwrap_err();
361        assert_eq!(
362            error.to_string(),
363            "limits.turns must be a positive finite number, got 0"
364        );
365    }
366}