1use std::fmt;
4use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
5
6use async_trait::async_trait;
7use futures::future::BoxFuture;
8
9use super::fallback_strategy::FallbackStrategy;
10use super::strategy::{RoutingAttempt, RoutingContext, RoutingFailure, RoutingStrategy};
11use crate::agent::{InvocationContext, InvocationState, LocalAgent};
12use crate::error::{Error, Result};
13use crate::hooks::{AfterInvocationEvent, AfterModelCallEvent, BeforeInvocationEvent, HookCallbackOptions, HookOrder};
14use crate::middleware::{InvokeModelContext, InvokeModelStage, StageResult};
15use crate::models::Model;
16use crate::plugins::Plugin;
17use crate::types::{JsonObject, Message, SystemPrompt, ToolSpec};
18
19#[derive(Clone)]
21#[non_exhaustive]
22pub enum CandidateModel {
23 Model(Arc<dyn Model>),
25 Router(ModelRouter),
27}
28
29impl From<Arc<dyn Model>> for CandidateModel {
30 fn from(model: Arc<dyn Model>) -> Self {
31 Self::Model(model)
32 }
33}
34
35impl<M: Model> From<M> for CandidateModel {
36 fn from(model: M) -> Self {
37 Self::Model(Arc::new(model))
38 }
39}
40
41impl<M: Model> From<Arc<M>> for CandidateModel {
42 fn from(model: Arc<M>) -> Self {
43 Self::Model(model)
44 }
45}
46
47impl From<ModelRouter> for CandidateModel {
48 fn from(router: ModelRouter) -> Self {
49 Self::Router(router)
50 }
51}
52
53impl fmt::Debug for CandidateModel {
54 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55 match self {
56 Self::Model(model) => f.debug_tuple("Model").field(&model.model_id()).finish(),
57 Self::Router(router) => f.debug_tuple("Router").field(router).finish(),
58 }
59 }
60}
61
62#[derive(Debug, Clone, bon::Builder)]
65#[non_exhaustive]
66pub struct RoutingCandidateOptions {
67 #[builder(into)]
69 pub model: CandidateModel,
70 #[builder(into)]
72 pub name: Option<String>,
73 #[builder(into)]
75 pub description: Option<String>,
76 pub metadata: Option<JsonObject>,
79}
80
81impl RoutingCandidateOptions {
82 pub fn new(model: impl Into<CandidateModel>) -> Self {
84 Self {
85 model: model.into(),
86 name: None,
87 description: None,
88 metadata: None,
89 }
90 }
91
92 #[must_use]
94 pub fn with_name(mut self, name: impl Into<String>) -> Self {
95 self.name = Some(name.into());
96 self
97 }
98
99 #[must_use]
101 pub fn with_description(mut self, description: impl Into<String>) -> Self {
102 self.description = Some(description.into());
103 self
104 }
105
106 #[must_use]
108 pub fn with_metadata(mut self, metadata: JsonObject) -> Self {
109 self.metadata = Some(metadata);
110 self
111 }
112}
113
114struct CandidateInner {
115 model: CandidateModel,
116 name: Option<String>,
117 description: Option<String>,
118 metadata: Option<JsonObject>,
119}
120
121#[derive(Clone)]
139pub struct RoutingCandidate(Arc<CandidateInner>);
140
141impl RoutingCandidate {
142 #[must_use]
144 pub fn new(options: RoutingCandidateOptions) -> Self {
145 Self(Arc::new(CandidateInner {
146 model: options.model,
147 name: options.name,
148 description: options.description,
149 metadata: options.metadata,
150 }))
151 }
152
153 #[must_use]
155 pub fn model(&self) -> &CandidateModel {
156 &self.0.model
157 }
158
159 #[must_use]
161 pub fn name(&self) -> Option<&str> {
162 self.0.name.as_deref()
163 }
164
165 #[must_use]
167 pub fn description(&self) -> Option<&str> {
168 self.0.description.as_deref()
169 }
170
171 #[must_use]
173 pub fn metadata(&self) -> Option<&JsonObject> {
174 self.0.metadata.as_ref()
175 }
176
177 pub(crate) fn label(&self) -> String {
179 if let Some(name) = self.name().filter(|name| !name.is_empty()) {
180 return name.to_owned();
181 }
182 match self.model() {
183 CandidateModel::Model(model) => model_label(model.as_ref()),
184 CandidateModel::Router(_) => "ModelRouter".to_owned(),
185 }
186 }
187}
188
189impl PartialEq for RoutingCandidate {
190 fn eq(&self, other: &Self) -> bool {
191 Arc::ptr_eq(&self.0, &other.0)
192 }
193}
194
195impl Eq for RoutingCandidate {}
196
197impl fmt::Debug for RoutingCandidate {
198 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199 f.debug_struct("RoutingCandidate")
200 .field("model", &self.0.model)
201 .field("name", &self.0.name)
202 .field("description", &self.0.description)
203 .field("metadata", &self.0.metadata)
204 .finish()
205 }
206}
207
208impl From<RoutingCandidateOptions> for RoutingCandidate {
209 fn from(options: RoutingCandidateOptions) -> Self {
210 Self::new(options)
211 }
212}
213
214impl From<CandidateModel> for RoutingCandidate {
215 fn from(model: CandidateModel) -> Self {
216 Self::new(RoutingCandidateOptions::new(model))
217 }
218}
219
220impl From<Arc<dyn Model>> for RoutingCandidate {
221 fn from(model: Arc<dyn Model>) -> Self {
222 CandidateModel::from(model).into()
223 }
224}
225
226impl<M: Model> From<M> for RoutingCandidate {
227 fn from(model: M) -> Self {
228 CandidateModel::from(model).into()
229 }
230}
231
232impl<M: Model> From<Arc<M>> for RoutingCandidate {
233 fn from(model: Arc<M>) -> Self {
234 CandidateModel::from(model).into()
235 }
236}
237
238impl From<ModelRouter> for RoutingCandidate {
239 fn from(router: ModelRouter) -> Self {
240 CandidateModel::from(router).into()
241 }
242}
243
244#[derive(Clone, Default, bon::Builder)]
246pub struct ModelRouterOptions {
247 pub strategy: Option<Arc<dyn RoutingStrategy>>,
249 pub max_switches: Option<u32>,
251}
252
253impl fmt::Debug for ModelRouterOptions {
254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255 f.debug_struct("ModelRouterOptions")
256 .field("strategy", &self.strategy.as_ref().map(|strategy| strategy.name()))
257 .field("max_switches", &self.max_switches)
258 .finish()
259 }
260}
261
262struct RouterInner {
263 candidates: Vec<RoutingCandidate>,
264 default_model: Arc<dyn Model>,
265 strategy: Arc<dyn RoutingStrategy>,
266 max_switches: Option<u32>,
267}
268
269#[derive(Clone)]
292pub struct ModelRouter(Arc<RouterInner>);
293
294impl fmt::Debug for ModelRouter {
295 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296 f.debug_struct("ModelRouter")
297 .field("candidates", &self.0.candidates.len())
298 .field("strategy", &self.0.strategy.name())
299 .field("max_switches", &self.0.max_switches)
300 .finish()
301 }
302}
303
304fn model_label(model: &dyn Model) -> String {
305 model.model_id().unwrap_or_else(|| "Model".to_owned())
306}
307
308fn model_ptr(model: &Arc<dyn Model>) -> *const () {
309 Arc::as_ptr(model).cast::<()>()
310}
311
312pub(crate) fn same_model(a: &Arc<dyn Model>, b: &Arc<dyn Model>) -> bool {
313 std::ptr::eq(model_ptr(a), model_ptr(b))
314}
315
316fn reachable_models(candidate: &RoutingCandidate, models: &mut Vec<Arc<dyn Model>>) {
317 match candidate.model() {
318 CandidateModel::Model(model) => models.push(model.clone()),
319 CandidateModel::Router(router) => {
320 for nested in router.candidates() {
321 reachable_models(nested, models);
322 }
323 }
324 }
325}
326
327fn reject_duplicates(candidates: &[RoutingCandidate]) -> Result<()> {
331 let mut seen_models: Vec<Arc<dyn Model>> = Vec::new();
332 let mut seen_names: Vec<&str> = Vec::new();
333 for (index, candidate) in candidates.iter().enumerate() {
334 if candidates[..index].contains(candidate) {
335 return Err(Error::other("duplicate RoutingCandidate instance"));
336 }
337 let mut models = Vec::new();
338 reachable_models(candidate, &mut models);
339 for model in models {
340 if seen_models.iter().any(|seen| same_model(seen, &model)) {
341 return Err(Error::other(format!(
342 "candidate=<{}> repeats a model already routed to; construct a separate instance so each candidate has its own health",
343 candidate.label()
344 )));
345 }
346 seen_models.push(model);
347 }
348 let Some(name) = candidate.name() else {
349 continue;
350 };
351 if seen_names.contains(&name) {
352 return Err(Error::other(format!("duplicate candidate name=<{name}>")));
353 }
354 seen_names.push(name);
355 }
356 Ok(())
357}
358
359fn reject_stateful(candidates: &[RoutingCandidate]) -> Result<()> {
360 for candidate in candidates {
361 if let CandidateModel::Model(model) = candidate.model()
362 && model.stateful()
363 {
364 return Err(Error::other(format!(
365 "candidate=<{}> is stateful; routing among stateful models is not supported",
366 candidate.label()
367 )));
368 }
369 }
370 Ok(())
371}
372
373impl ModelRouter {
374 pub fn new(
382 models: impl IntoIterator<Item = impl Into<RoutingCandidate>>,
383 options: ModelRouterOptions,
384 ) -> Result<Self> {
385 let candidates: Vec<RoutingCandidate> = models.into_iter().map(Into::into).collect();
386 if candidates.is_empty() {
387 return Err(Error::other("ModelRouter requires at least one candidate model"));
388 }
389 reject_stateful(&candidates)?;
390 reject_duplicates(&candidates)?;
391 let default_model = match candidates[0].model() {
392 CandidateModel::Model(model) => model.clone(),
393 CandidateModel::Router(router) => router.default_model(),
394 };
395 Ok(Self(Arc::new(RouterInner {
396 candidates,
397 default_model,
398 strategy: options.strategy.unwrap_or_else(|| Arc::new(FallbackStrategy)),
399 max_switches: options.max_switches,
400 })))
401 }
402
403 #[must_use]
405 pub fn name(&self) -> &'static str {
406 MODEL_ROUTER_NAME
407 }
408
409 #[must_use]
411 pub fn candidates(&self) -> &[RoutingCandidate] {
412 &self.0.candidates
413 }
414
415 #[must_use]
417 pub fn default_model(&self) -> Arc<dyn Model> {
418 self.0.default_model.clone()
419 }
420
421 fn strategy_name(&self) -> &'static str {
422 self.0.strategy.name()
423 }
424
425 fn routing_context(
427 &self,
428 messages: Vec<Message>,
429 system_prompt: Option<SystemPrompt>,
430 tool_specs: Vec<ToolSpec>,
431 invocation_state: InvocationState,
432 invocation_context: Option<&InvocationContext>,
433 attempts: Vec<RoutingAttempt>,
434 ) -> RoutingContext {
435 RoutingContext {
436 messages,
437 system_prompt,
438 tool_specs,
439 candidates: self.0.candidates.clone(),
440 invocation_state,
441 attempts,
442 invocation_context: InvocationContext::auxiliary(invocation_context),
443 }
444 }
445
446 fn nested_context(&self, context: &RoutingContext) -> RoutingContext {
447 RoutingContext {
448 candidates: self.0.candidates.clone(),
449 attempts: Vec::new(),
450 ..context.clone()
451 }
452 }
453
454 fn validated(&self, candidate: Option<RoutingCandidate>) -> Result<Option<RoutingCandidate>> {
455 match candidate {
456 Some(candidate) if !self.0.candidates.contains(&candidate) => Err(Error::other(
457 "strategy.select must return a candidate from context.candidates",
458 )),
459 candidate => Ok(candidate),
460 }
461 }
462
463 async fn ask(&self, context: &RoutingContext) -> Result<Option<RoutingCandidate>> {
464 let candidate = self.0.strategy.select(context).await.map_err(Error::from_boxed)?;
465 self.validated(candidate)
466 }
467
468 fn resolve<'r>(
470 &'r self,
471 candidate: &'r RoutingCandidate,
472 context: &'r RoutingContext,
473 ) -> BoxFuture<'r, Result<Arc<dyn Model>>> {
474 Box::pin(async move {
475 match candidate.model() {
476 CandidateModel::Model(model) => Ok(model.clone()),
477 CandidateModel::Router(router) => router.select_model(&router.nested_context(context)).await,
478 }
479 })
480 }
481
482 async fn select_model(&self, context: &RoutingContext) -> Result<Arc<dyn Model>> {
483 match self.ask(context).await? {
484 None => Ok(self.default_model()),
485 Some(candidate) => self.resolve(&candidate, context).await,
486 }
487 }
488
489 async fn open(&self, context: &RoutingContext) -> Result<(RoutingCandidate, Arc<dyn Model>)> {
491 let strategy = self.strategy_name();
492 let Some(candidate) = self.ask(context).await? else {
493 let fallback = self.0.candidates[0].clone();
494 let model = self.default_model();
495 tracing::info!(
496 "strategy=<{strategy}>, candidate=<{}>, model=<{}> | strategy declined the opening choice, using the default model",
497 fallback.label(),
498 model_label(model.as_ref())
499 );
500 return Ok((fallback, model));
501 };
502 let model = self.resolve(&candidate, context).await?;
503 tracing::info!(
504 "strategy=<{strategy}>, candidate=<{}>, model=<{}> | candidate selected",
505 candidate.label(),
506 model_label(model.as_ref())
507 );
508 Ok((candidate, model))
509 }
510}
511
512pub(crate) const MODEL_ROUTER_NAME: &str = "strands:model-router";
514
515pub(crate) struct ModelRouterPlugin;
519
520#[async_trait]
521impl Plugin for ModelRouterPlugin {
522 fn name(&self) -> &str {
523 MODEL_ROUTER_NAME
524 }
525
526 async fn init_agent(&self, _agent: &mut LocalAgent) -> Result<()> {
527 Ok(())
528 }
529}
530
531struct RoutingState {
533 candidate: RoutingCandidate,
534 model: Arc<dyn Model>,
535 attempts: Vec<RoutingAttempt>,
536 switched_to: Vec<RoutingCandidate>,
537 switches: u32,
538}
539
540impl RoutingState {
541 fn new(candidate: RoutingCandidate, model: Arc<dyn Model>) -> Self {
542 Self {
543 switched_to: vec![candidate.clone()],
544 candidate,
545 model,
546 attempts: Vec::new(),
547 switches: 0,
548 }
549 }
550}
551
552#[derive(Clone)]
555pub(crate) struct RouterAttachment {
556 router: ModelRouter,
557 state: Arc<Mutex<Option<RoutingState>>>,
558}
559
560impl RouterAttachment {
561 pub(crate) fn attach(router: ModelRouter, agent: &LocalAgent) -> Self {
563 let attachment = Self {
564 router,
565 state: Arc::default(),
566 };
567 let selection = attachment.clone();
568 agent.add_middleware(InvokeModelStage::input(move |context| {
569 let selection = selection.clone();
570 async move { selection.select(context).await }
571 }));
572 let routing = attachment.clone();
573 agent.add_async_hook_with::<AfterModelCallEvent<'_>>(
574 move |event| {
575 let routing = routing.clone();
576 Box::pin(async move { routing.on_model_result(event).await })
577 },
578 HookCallbackOptions {
579 order: HookOrder::MODEL_ROUTING,
580 },
581 );
582 let after = attachment.clone();
583 agent.add_hook_with(
584 move |_: &mut AfterInvocationEvent<'_>| after.clear(),
585 HookCallbackOptions {
586 order: HookOrder::SDK_LAST,
587 },
588 );
589 let before = attachment.clone();
590 agent.add_hook_with(
591 move |_: &mut BeforeInvocationEvent<'_>| before.clear(),
592 HookCallbackOptions {
593 order: HookOrder::SDK_FIRST,
594 },
595 );
596 attachment
597 }
598
599 fn lock(&self) -> MutexGuard<'_, Option<RoutingState>> {
600 self.state.lock().unwrap_or_else(PoisonError::into_inner)
601 }
602
603 pub(crate) fn routed_model(&self) -> Option<Arc<dyn Model>> {
605 self.lock().as_ref().map(|state| state.model.clone())
606 }
607
608 fn clear(&self) {
609 *self.lock() = None;
610 }
611
612 async fn select(&self, mut context: InvokeModelContext) -> StageResult<InvokeModelContext> {
614 if let Some(model) = self.routed_model() {
615 context.model = model;
616 return Ok(context);
617 }
618 let routing = self.router.routing_context(
619 context.messages.clone(),
620 context.system_prompt.clone(),
621 context.tool_specs.clone(),
622 context.invocation_state.clone(),
623 context.invocation_context.as_ref(),
624 Vec::new(),
625 );
626 let (candidate, model) = self.router.open(&routing).await?;
627 *self.lock() = Some(RoutingState::new(candidate, model.clone()));
628 context.model = model;
629 Ok(context)
630 }
631
632 async fn on_model_result(&self, event: &mut AfterModelCallEvent<'_>) {
634 let Some(candidate) = self.lock().as_ref().map(|state| state.candidate.clone()) else {
635 return;
636 };
637 if event.error().is_some_and(crate::agent::is_cancelled_error) {
638 return;
639 }
640 if event.stop_data().is_some() {
641 if let Some(state) = self.lock().as_mut() {
642 state.attempts.push(RoutingAttempt::success(candidate.clone()));
643 state.switched_to = vec![candidate];
644 }
645 return;
646 }
647 let Some(failure) = event.error().filter(|_| !event.retry()).map(RoutingFailure::from) else {
648 return;
649 };
650 let capped = {
651 let mut guard = self.lock();
652 let Some(state) = guard.as_mut() else {
653 return;
654 };
655 state.attempts.push(RoutingAttempt::failure(candidate, failure));
656 self.router.0.max_switches.filter(|cap| state.switches >= *cap)
657 };
658 if let Some(cap) = capped {
659 tracing::warn!("maxSwitches=<{cap}> | switch cap reached, leaving the error to surface");
660 return;
661 }
662 if self.advance(event).await {
663 event.set_retry(true);
664 }
665 }
666
667 fn attempts(&self) -> Vec<RoutingAttempt> {
668 self.lock()
669 .as_ref()
670 .map(|state| state.attempts.clone())
671 .unwrap_or_default()
672 }
673
674 fn used_this_round(&self, candidate: &RoutingCandidate) -> bool {
675 self.lock()
676 .as_ref()
677 .is_some_and(|state| state.switched_to.contains(candidate))
678 }
679
680 async fn advance(&self, event: &AfterModelCallEvent<'_>) -> bool {
685 let strategy = self.router.strategy_name();
686 loop {
687 let agent = event.agent();
688 let context = self.router.routing_context(
689 agent.messages().to_vec(),
690 agent.system_prompt().cloned(),
691 agent.tool_registry().tool_specs(),
692 event.invocation_state().clone(),
693 event.invocation_context(),
694 self.attempts(),
695 );
696 let candidate = match self.router.ask(&context).await {
698 Ok(candidate) => candidate,
699 Err(error) => {
700 tracing::warn!(
701 "strategy=<{strategy}>, error=<{error}> | routing failed, leaving the error to surface"
702 );
703 return false;
704 }
705 };
706 let Some(candidate) = candidate else {
707 return false;
708 };
709 if self.used_this_round(&candidate) {
710 tracing::info!(
711 "candidate=<{}> | already used this round, leaving the error to surface",
712 candidate.label()
713 );
714 return false;
715 }
716 let model = match self.router.resolve(&candidate, &context).await {
717 Ok(model) => model,
718 Err(error) => {
719 tracing::warn!(
720 "candidate=<{}>, error=<{error}> | candidate could not be resolved, asking again",
721 candidate.label()
722 );
723 if let Some(state) = self.lock().as_mut() {
724 state
725 .attempts
726 .push(RoutingAttempt::failure(candidate.clone(), RoutingFailure::from(&error)));
727 state.switched_to.push(candidate);
728 }
729 continue;
730 }
731 };
732 let mut guard = self.lock();
733 let Some(state) = guard.as_mut() else {
734 return false;
735 };
736 tracing::info!(
737 "from_candidate=<{}>, to_candidate=<{}>, error=<{}> | model call failed, switching candidate",
738 state.candidate.label(),
739 candidate.label(),
740 event.error().map_or("undefined", Error::name)
741 );
742 state.switched_to.push(candidate.clone());
743 state.candidate = candidate;
744 state.model = model;
745 state.switches += 1;
746 return true;
747 }
748 }
749}
750
751#[cfg(test)]
752mod tests;