strands/models/routing/strategy.rs
1//! The routing strategy contract.
2
3use async_trait::async_trait;
4
5use super::router::RoutingCandidate;
6use crate::agent::{InvocationContext, InvocationState};
7use crate::error::{BoxError, Error};
8use crate::types::{Message, SystemPrompt, ToolSpec};
9
10/// What failed on a [`RoutingAttempt`]: the error's name and message.
11#[derive(Debug, Clone, PartialEq, Eq)]
12#[non_exhaustive]
13pub struct RoutingFailure {
14 /// The error's name (`Error::name`), such as `ModelThrottledError` or `Error`.
15 pub name: String,
16 /// The error message.
17 pub message: String,
18}
19
20impl RoutingFailure {
21 /// A failure with a class name and message.
22 pub fn new(name: impl Into<String>, message: impl Into<String>) -> Self {
23 Self {
24 name: name.into(),
25 message: message.into(),
26 }
27 }
28}
29
30impl From<&Error> for RoutingFailure {
31 fn from(error: &Error) -> Self {
32 Self::new(error.name(), error.to_string())
33 }
34}
35
36/// A candidate used during an invocation and how that attempt went (`RoutingAttempt`).
37#[derive(Debug, Clone, PartialEq)]
38#[non_exhaustive]
39pub struct RoutingAttempt {
40 /// The configured candidate.
41 pub candidate: RoutingCandidate,
42 /// The model or candidate-resolution failure; `None` when the call succeeded.
43 pub exception: Option<RoutingFailure>,
44}
45
46impl RoutingAttempt {
47 /// A successful attempt.
48 #[must_use]
49 pub fn success(candidate: RoutingCandidate) -> Self {
50 Self {
51 candidate,
52 exception: None,
53 }
54 }
55
56 /// A failed attempt.
57 #[must_use]
58 pub fn failure(candidate: RoutingCandidate, exception: RoutingFailure) -> Self {
59 Self {
60 candidate,
61 exception: Some(exception),
62 }
63 }
64}
65
66/// What a strategy reads to choose a candidate (`RoutingContext`): copies of the request, the
67/// configured candidates and the attempts of this invocation.
68#[derive(Debug, Clone)]
69#[non_exhaustive]
70pub struct RoutingContext {
71 /// A copy of the messages.
72 pub messages: Vec<Message>,
73 /// A copy of the system prompt.
74 pub system_prompt: Option<SystemPrompt>,
75 /// A copy of the tool specs.
76 pub tool_specs: Vec<ToolSpec>,
77 /// The configured candidates; a strategy returns one of these.
78 pub candidates: Vec<RoutingCandidate>,
79 /// The caller's invocation state.
80 pub invocation_state: InvocationState,
81 /// The attempts of this invocation, oldest first.
82 pub attempts: Vec<RoutingAttempt>,
83 /// The request this decision runs for; a nested model call that joins it adds to its usage,
84 /// but its limits do not apply.
85 pub invocation_context: Option<InvocationContext>,
86}
87
88impl RoutingContext {
89 /// A context over `candidates` with an empty request and no attempts.
90 #[must_use]
91 pub fn new(candidates: Vec<RoutingCandidate>) -> Self {
92 Self {
93 messages: Vec::new(),
94 system_prompt: None,
95 tool_specs: Vec::new(),
96 candidates,
97 invocation_state: InvocationState::new(),
98 attempts: Vec::new(),
99 invocation_context: None,
100 }
101 }
102
103 /// Sets the messages.
104 #[must_use]
105 pub fn with_messages(mut self, messages: Vec<Message>) -> Self {
106 self.messages = messages;
107 self
108 }
109
110 /// Sets the system prompt.
111 #[must_use]
112 pub fn with_system_prompt(mut self, system_prompt: impl Into<SystemPrompt>) -> Self {
113 self.system_prompt = Some(system_prompt.into());
114 self
115 }
116
117 /// Sets the tool specs.
118 #[must_use]
119 pub fn with_tool_specs(mut self, tool_specs: Vec<ToolSpec>) -> Self {
120 self.tool_specs = tool_specs;
121 self
122 }
123
124 /// Sets the attempts.
125 #[must_use]
126 pub fn with_attempts(mut self, attempts: Vec<RoutingAttempt>) -> Self {
127 self.attempts = attempts;
128 self
129 }
130
131 /// Sets the invocation state.
132 #[must_use]
133 pub fn with_invocation_state(mut self, invocation_state: InvocationState) -> Self {
134 self.invocation_state = invocation_state;
135 self
136 }
137
138 /// Sets the request the decision runs for.
139 #[must_use]
140 pub fn with_invocation_context(mut self, invocation_context: Option<InvocationContext>) -> Self {
141 self.invocation_context = invocation_context;
142 self
143 }
144}
145
146/// Chooses a configured candidate (`RoutingStrategy`).
147///
148/// The router asks before the first model call, with no attempts, and after each failure no hook
149/// claimed, until routing stops. Return one of `context.candidates` (compared by identity) or
150/// `None` to decline.
151///
152/// Declining the opening selection serves the router's default model; declining after a failure
153/// ends routing and the model error surfaces. At the opening selection, errors and foreign
154/// candidates propagate; after a failure they end routing without replacing the model error. Each
155/// failure round uses a candidate once: naming one already used this round ends routing, and a
156/// nested router that cannot resolve uses up its slot while the strategy is asked again.
157///
158/// ```
159/// use strands::models::routing::{RoutingCandidate, RoutingContext, RoutingStrategy};
160///
161/// struct Last;
162///
163/// #[strands::async_trait]
164/// impl RoutingStrategy for Last {
165/// async fn select(&self, context: &RoutingContext) -> Result<Option<RoutingCandidate>, strands::BoxError> {
166/// Ok(context.candidates.last().cloned())
167/// }
168/// }
169/// ```
170#[async_trait]
171pub trait RoutingStrategy: Send + Sync + 'static {
172 /// Selects a candidate from `context.candidates`, or `None` to decline.
173 ///
174 /// # Errors
175 ///
176 /// Any error; see the trait docs for how the router treats it.
177 async fn select(&self, context: &RoutingContext) -> Result<Option<RoutingCandidate>, BoxError>;
178
179 /// The name routing logs use; defaults to the type name.
180 fn name(&self) -> &'static str {
181 let full = std::any::type_name::<Self>();
182 let path = full.split('<').next().unwrap_or(full);
183 path.rsplit("::").next().unwrap_or(path)
184 }
185}