switchyard_libsy/algorithms/
vgr.rs1use std::sync::Arc;
13
14use switchyard_protocol::Request;
15
16use self::text::ToolRecord;
17use crate::Result;
18use crate::algorithms::fall_through::FallThrough;
19use crate::algorithms::util::affinity::AffinityRouter;
20use crate::core::algorithm::{Algorithm, AnswerSummary, Driver, RoutingOutcome};
21
22mod compaction;
23mod config;
24mod decide;
25mod readout;
26mod render;
27mod rungs;
28mod runtime;
29mod safety;
30mod text;
31
32pub use config::{ACTIVE_APPROVAL, ServingMode, Targets, VgrConfig};
33pub use safety::{BreakerConfig, KillSwitch};
34
35#[cfg(test)]
36mod tests;
37
38pub struct Vgr {
40 route: FallThrough,
41 classifier: Arc<runtime::VgrClassifier>,
42}
43
44impl Vgr {
45 pub fn new(config: VgrConfig) -> Result<Self> {
47 config.validate()?;
48 let mut affinity = AffinityRouter::new().with_latch_only([config.targets.capable.clone()]);
49 let reason = if config.latch_escalation && config.mode != ServingMode::Shadow {
50 "session_latched"
51 } else {
52 affinity = affinity.with_release_on_user_turn();
53 "turn_verification_latched"
54 };
55 let affinity = Arc::new(affinity);
56 let mut route = FallThrough::new_with_state().with_name("vgr");
57 if config.compact_handoff {
58 route = route.with_classifier(Arc::new(compaction::Compactor));
59 }
60 let classifier = Arc::new(runtime::VgrClassifier {
61 breaker: safety::CircuitBreaker::new(config.breaker),
62 config,
63 });
64 if classifier.config.mode != ServingMode::Shadow {
66 route = route
67 .with_processor(affinity.clone())
68 .with_classifier(Arc::new(runtime::Held(affinity, reason)));
69 }
70 let route = route.with_classifier(classifier.clone());
71 Ok(Self { route, classifier })
72 }
73}
74
75#[async_trait::async_trait]
76impl Algorithm for Vgr {
77 fn name(&self) -> &str {
78 "vgr"
79 }
80
81 async fn route(self: Arc<Self>, driver: Driver, request: Request) -> Result<RoutingOutcome> {
82 let arrived = self
85 .classifier
86 .efficient_may_stand_in(&request)
87 .then(|| request.clone());
88 let mut outcome = self.route.execute(driver.clone(), request).await?;
89 outcome.selected_model_ids.truncate(1);
91 let config = &self.classifier.config;
92 if let Some(arrived) = arrived
93 && outcome.response.is_none()
94 && outcome.selected_model_ids.first() == Some(&config.targets.capable)
95 && !driver.model_failed(&config.targets.efficient)
97 && self.classifier.efficient_may_stand_in(&arrived)
98 {
99 outcome
100 .selected_model_ids
101 .push(config.targets.efficient.clone());
102 outcome.fallback_request = Some(arrived);
103 }
104 Ok(outcome)
105 }
106
107 fn tracks_answers(&self) -> bool {
108 self.route.tracks_answers()
109 }
110
111 async fn observe_answer(&self, session_id: &str, answer: AnswerSummary) {
112 self.route.observe_answer(session_id, answer).await;
113 }
114}
115
116#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
118enum Branch {
119 Coding,
121 Answer,
123 Chat,
125 Agentic,
127 DefaultVerified,
129 #[default]
131 Unknown,
132}
133
134#[derive(Clone, Copy, Debug, Eq, PartialEq)]
136enum TaskType {
137 Coding,
138 Agentic,
139 Answer,
140 Chat,
141}
142
143#[derive(Default)]
145struct Capabilities {
146 branch: Branch,
147 transcript: Option<String>,
149 tools: Option<ToolRecord>,
151}
152
153fn derive_capabilities(
157 request: &Request,
158 attempt: &str,
159 task_type: Option<TaskType>,
160 attachments_supported: bool,
161) -> Capabilities {
162 let (turns, unsupported) = text::turns(request);
163 if (unsupported && !attachments_supported)
164 || text::user_task_text(&turns).trim().is_empty()
165 || attempt.trim().is_empty()
166 {
167 return Capabilities::default();
168 }
169 let caps = |branch, transcript| Capabilities {
170 branch,
171 transcript,
172 tools: Some(ToolRecord::from_request(request)),
173 };
174
175 if task_type == Some(TaskType::Answer) && !text::turn_has_tool_trajectory(request) {
178 return Capabilities {
179 tools: None,
180 ..caps(
181 Branch::Answer,
182 Some(render::render_session(&turns, attempt)),
183 )
184 };
185 }
186 if task_type == Some(TaskType::Agentic)
188 || (text::has_tool_trajectory(request)
189 && !matches!(task_type, Some(TaskType::Answer | TaskType::Chat)))
190 {
191 return caps(
192 Branch::Agentic,
193 Some(render::render_agentic_view(request, &turns, attempt)),
194 );
195 }
196 let transcript = Some(render::render_session(&turns, attempt));
197 if text::observed_hardening(attempt) || task_type == Some(TaskType::Coding) {
198 return caps(Branch::Coding, transcript);
199 }
200 if text::observed_tool_activity(attempt) {
201 caps(Branch::Agentic, transcript)
202 } else if matches!(task_type, Some(TaskType::Chat | TaskType::Answer)) {
203 caps(Branch::Chat, transcript)
204 } else {
205 caps(Branch::DefaultVerified, transcript)
206 }
207}