Skip to main content

agent_runtime/model/
model_router.rs

1//! Runtime model-routing contract, lifecycle events, and fixed-model adapter.
2
3use std::sync::Arc;
4
5use agent_models::{ModelCapability, ModelError, ModelFailureCategory};
6use async_trait::async_trait;
7
8use crate::{AgentModel, CancellationToken, ModelRequest, ModelTurn};
9
10/// Events emitted while a router evaluates compatible model candidates.
11#[derive(Debug, Clone)]
12pub enum ModelRoutingEvent {
13    CandidatesDiscovered {
14        model_ids: Vec<String>,
15    },
16    CandidateAttemptStarted {
17        model_id: String,
18    },
19    CandidateAttemptFailed {
20        model_id: String,
21        category: ModelFailureCategory,
22    },
23    Fallback {
24        from_model_id: String,
25        to_model_id: String,
26        category: ModelFailureCategory,
27    },
28    ModelSelected {
29        model_id: String,
30    },
31    RoutingFailed {
32        attempted_candidates: usize,
33    },
34}
35
36/// Receives routing lifecycle events without exposing provider error payloads.
37pub trait ModelRoutingEventSink: Send + Sync {
38    fn emit(&self, event: ModelRoutingEvent);
39}
40
41/// A model response together with the provider-qualified identity that produced it.
42#[derive(Debug, Clone)]
43pub struct RoutedModelTurn {
44    pub model_id: String,
45    pub turn: ModelTurn,
46}
47
48/// Selects and invokes a model for one agent turn.
49///
50/// Implementations receive the agent's requirements on every invocation. The
51/// runtime deliberately knows nothing about provider configuration or credentials.
52#[async_trait]
53pub trait ModelRouter: Send + Sync {
54    async fn complete(
55        &self,
56        required: &[ModelCapability],
57        request: ModelRequest,
58        cancellation: CancellationToken,
59        events: Arc<dyn ModelRoutingEventSink>,
60    ) -> Result<RoutedModelTurn, ModelError>;
61}
62
63/// Adapts the legacy single-model interface for tests and embedded callers.
64pub(crate) struct FixedModelRouter(Arc<dyn AgentModel>);
65
66impl FixedModelRouter {
67    pub(crate) fn new(model: Arc<dyn AgentModel>) -> Self {
68        Self(model)
69    }
70}
71
72#[async_trait]
73impl ModelRouter for FixedModelRouter {
74    async fn complete(
75        &self,
76        _required: &[ModelCapability],
77        request: ModelRequest,
78        _cancellation: CancellationToken,
79        events: Arc<dyn ModelRoutingEventSink>,
80    ) -> Result<RoutedModelTurn, ModelError> {
81        let model_id = "fixed".to_owned();
82        events.emit(ModelRoutingEvent::CandidatesDiscovered {
83            model_ids: vec![model_id.clone()],
84        });
85        events.emit(ModelRoutingEvent::CandidateAttemptStarted {
86            model_id: model_id.clone(),
87        });
88        match self.0.complete(request).await {
89            Ok(turn) => {
90                events.emit(ModelRoutingEvent::ModelSelected {
91                    model_id: model_id.clone(),
92                });
93                Ok(RoutedModelTurn { model_id, turn })
94            }
95            Err(error) => {
96                events.emit(ModelRoutingEvent::CandidateAttemptFailed {
97                    model_id,
98                    category: error.failure_category(),
99                });
100                events.emit(ModelRoutingEvent::RoutingFailed {
101                    attempted_candidates: 1,
102                });
103                Err(error)
104            }
105        }
106    }
107}
108
109#[cfg(test)]
110mod tests {
111    use std::sync::{Arc, Mutex};
112
113    use agent_models::ModelError;
114    use async_trait::async_trait;
115
116    use super::{FixedModelRouter, ModelRouter, ModelRoutingEvent, ModelRoutingEventSink};
117    use crate::{AgentModel, CancellationToken, ModelRequest, ModelTurn};
118
119    struct CompletedModel;
120
121    #[async_trait]
122    impl AgentModel for CompletedModel {
123        async fn complete(&self, _request: ModelRequest) -> Result<ModelTurn, ModelError> {
124            Ok(ModelTurn {
125                usage: None,
126                content: Some("done".into()),
127                tool_calls: Vec::new(),
128            })
129        }
130    }
131
132    #[derive(Default)]
133    struct RecordingSink(Mutex<Vec<ModelRoutingEvent>>);
134
135    impl ModelRoutingEventSink for RecordingSink {
136        fn emit(&self, event: ModelRoutingEvent) {
137            self.0.lock().unwrap().push(event);
138        }
139    }
140
141    #[tokio::test]
142    async fn fixed_router_emits_candidate_attempt_and_selection_events() {
143        let sink = Arc::new(RecordingSink::default());
144        let router = FixedModelRouter::new(Arc::new(CompletedModel));
145
146        let routed = router
147            .complete(
148                &[],
149                ModelRequest {
150                    system_prompt: None,
151                    messages: Vec::new(),
152                    tools: Vec::new(),
153                },
154                CancellationToken::new(),
155                sink.clone(),
156            )
157            .await
158            .unwrap();
159
160        assert_eq!(routed.model_id, "fixed");
161        let events = sink.0.lock().unwrap();
162        assert!(matches!(
163            events.first(),
164            Some(ModelRoutingEvent::CandidatesDiscovered { model_ids })
165                if model_ids == &vec!["fixed".to_owned()]
166        ));
167        assert!(matches!(
168            events.get(1),
169            Some(ModelRoutingEvent::CandidateAttemptStarted { model_id })
170                if model_id == "fixed"
171        ));
172        assert!(matches!(
173            events.get(2),
174            Some(ModelRoutingEvent::ModelSelected { model_id })
175                if model_id == "fixed"
176        ));
177    }
178}