use crate::error::{Error, ProviderFailure, Result};
use crate::hooks::RequestPatch;
use crate::message::Message;
use crate::provider::ChatProvider;
use crate::stream::DeltaFn;
use crate::tools::ToolSpec;
use crate::usage::TurnUsage;
use async_trait::async_trait;
use std::fmt;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Hop {
pub from: String,
pub to: String,
pub reason: String,
}
impl fmt::Display for Hop {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} \u{2192} {}: {}", self.from, self.to, self.reason)
}
}
pub fn describe_hops(hops: &[Hop]) -> Option<String> {
let first = hops.first()?;
let mut chain = first.from.clone();
for h in hops {
chain.push_str(" \u{2192} ");
chain.push_str(&h.to);
}
let reasons: Vec<&str> = hops.iter().map(|h| h.reason.as_str()).collect();
Some(format!("route: {chain} ({})", reasons.join("; ")))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RouteStop {
Failed,
Exhausted,
AfterText,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RouteInfo {
pub name: String,
pub model: String,
pub endpoint: String,
}
pub const ROLES: &[&str] = &["judgement", "delegate"];
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RoleRoute {
pub role: &'static str,
pub route: String,
pub set: bool,
pub pinned: bool,
}
impl RoleRoute {
pub fn key(&self) -> &'static str {
match self.role {
"delegate" => "delegate",
_ => "aux",
}
}
}
impl fmt::Display for RoleRoute {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} \u{2192} {}", self.role, self.route)?;
if self.pinned {
write!(f, " (pinned)")?;
} else if !self.set {
write!(f, " (no {} route set)", self.key())?;
}
Ok(())
}
}
pub fn role_table(
aux: Option<&str>,
delegate: Option<&str>,
selected: &str,
pinned: bool,
) -> Vec<RoleRoute> {
ROLES
.iter()
.map(|role| {
let own = match *role {
"delegate" => delegate,
_ => aux,
};
RoleRoute {
role,
route: if pinned {
selected.to_string()
} else {
own.unwrap_or(selected).to_string()
},
set: !pinned && own.is_some(),
pinned,
}
})
.collect()
}
pub struct RouterEntry {
pub name: String,
pub provider: Arc<dyn ChatProvider>,
}
struct State {
next: usize,
hops: Vec<Hop>,
usage: Option<TurnUsage>,
}
pub struct Router {
entries: Vec<RouterEntry>,
state: Mutex<State>,
}
enum Call<'a> {
Chat,
Stream(DeltaFn<'a>),
Patched(DeltaFn<'a>, &'a RequestPatch),
}
impl Router {
pub fn new(entries: Vec<RouterEntry>) -> Result<Self> {
if entries.is_empty() {
return Err(Error::Config(
"a router needs at least one route to try".into(),
));
}
Ok(Self {
entries,
state: Mutex::new(State {
next: 0,
hops: Vec::new(),
usage: None,
}),
})
}
fn state(&self) -> MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(|e| e.into_inner())
}
pub fn hops(&self) -> Vec<Hop> {
self.state().hops.clone()
}
pub fn current(&self) -> &str {
let idx = self.state().next;
self.entries.get(idx).map(|e| e.name.as_str()).unwrap_or("")
}
async fn dispatch(
&self,
messages: &[Message],
tools: &[ToolSpec],
call: Call<'_>,
) -> Result<Message> {
let mut idx = self.state().next;
loop {
let Some(entry) = self.entries.get(idx) else {
return Err(Error::provider("the route chain ran out of routes"));
};
let shown = AtomicUsize::new(0);
let result = match &call {
Call::Chat => entry.provider.chat(messages, tools).await,
Call::Stream(on_delta) => {
let counted = |d: crate::stream::Delta| {
if let crate::stream::Delta::Text(t) = &d {
shown.fetch_add(t.len(), Ordering::Relaxed);
}
on_delta(d);
};
entry.provider.chat_stream(messages, tools, &counted).await
}
Call::Patched(on_delta, patch) => {
let counted = |d: crate::stream::Delta| {
if let crate::stream::Delta::Text(t) = &d {
shown.fetch_add(t.len(), Ordering::Relaxed);
}
on_delta(d);
};
entry
.provider
.chat_stream_patched(messages, tools, &counted, patch)
.await
}
};
let err = match result {
Ok(reply) => {
let mut st = self.state();
st.next = idx;
st.usage = entry.provider.take_usage();
return Ok(reply);
}
Err(e) => e,
};
let Error::Provider(failure) = err else {
return Err(err);
};
let trail = self.state().hops.clone();
let next_name = self.entries.get(idx + 1).map(|e| e.name.clone());
let has_next = next_name.is_some();
let stop = if !failure.is_retryable() {
Some(RouteStop::Failed)
} else if !has_next {
Some(if trail.is_empty() {
RouteStop::Failed
} else {
RouteStop::Exhausted
})
} else if shown.load(Ordering::Relaxed) > 0 {
Some(RouteStop::AfterText)
} else {
None
};
if let Some(stop) = stop {
return Err(Error::Provider(ProviderFailure::Routed {
route: entry.name.clone(),
trail,
stop,
cause: Box::new(failure),
}));
}
let mut st = self.state();
st.hops.push(Hop {
from: entry.name.clone(),
to: next_name.unwrap_or_default(),
reason: failure.short_reason(),
});
idx += 1;
st.next = idx;
}
}
}
#[async_trait]
impl ChatProvider for Router {
async fn chat(&self, messages: &[Message], tools: &[ToolSpec]) -> Result<Message> {
self.dispatch(messages, tools, Call::Chat).await
}
async fn chat_stream(
&self,
messages: &[Message],
tools: &[ToolSpec],
on_delta: DeltaFn<'_>,
) -> Result<Message> {
self.dispatch(messages, tools, Call::Stream(on_delta)).await
}
async fn chat_stream_patched(
&self,
messages: &[Message],
tools: &[ToolSpec],
on_delta: DeltaFn<'_>,
patch: &RequestPatch,
) -> Result<Message> {
self.dispatch(messages, tools, Call::Patched(on_delta, patch))
.await
}
fn take_usage(&self) -> Option<TurnUsage> {
self.state().usage.take()
}
fn can_see(&self) -> bool {
let next = {
let state = self.state();
state.next
};
self.entries
.get(next)
.map(|entry| entry.provider.can_see())
.unwrap_or(false)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::error::HttpFailure;
use std::collections::VecDeque;
struct Scripted {
replies: Mutex<VecDeque<Result<Message>>>,
text_first: Option<&'static str>,
calls: AtomicUsize,
patch_seen: Mutex<Option<bool>>,
usage: Option<TurnUsage>,
}
impl Scripted {
fn new(replies: Vec<Result<Message>>) -> Arc<Self> {
Arc::new(Self {
replies: Mutex::new(replies.into()),
text_first: None,
calls: AtomicUsize::new(0),
patch_seen: Mutex::new(None),
usage: None,
})
}
fn streaming_then(text: &'static str, reply: Result<Message>) -> Arc<Self> {
Arc::new(Self {
replies: Mutex::new(vec![reply].into()),
text_first: Some(text),
calls: AtomicUsize::new(0),
patch_seen: Mutex::new(None),
usage: None,
})
}
fn with_usage(replies: Vec<Result<Message>>, usage: TurnUsage) -> Arc<Self> {
Arc::new(Self {
replies: Mutex::new(replies.into()),
text_first: None,
calls: AtomicUsize::new(0),
patch_seen: Mutex::new(None),
usage: Some(usage),
})
}
fn calls(&self) -> usize {
self.calls.load(Ordering::SeqCst)
}
fn next(&self) -> Result<Message> {
self.calls.fetch_add(1, Ordering::SeqCst);
self.replies
.lock()
.unwrap_or_else(|e| e.into_inner())
.pop_front()
.unwrap_or_else(|| Err(Error::provider("script exhausted")))
}
}
#[async_trait]
impl ChatProvider for Scripted {
async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> Result<Message> {
self.next()
}
async fn chat_stream(
&self,
_: &[Message],
_: &[ToolSpec],
on_delta: DeltaFn<'_>,
) -> Result<Message> {
if let Some(t) = self.text_first {
on_delta(crate::stream::Delta::Text(t.into()));
}
self.next()
}
async fn chat_stream_patched(
&self,
m: &[Message],
t: &[ToolSpec],
on_delta: DeltaFn<'_>,
patch: &RequestPatch,
) -> Result<Message> {
*self.patch_seen.lock().unwrap_or_else(|e| e.into_inner()) = Some(!patch.is_empty());
self.chat_stream(m, t, on_delta).await
}
fn take_usage(&self) -> Option<TurnUsage> {
self.usage.clone()
}
}
fn reply(text: &str) -> Result<Message> {
Ok(Message::assistant(text))
}
fn down() -> Result<Message> {
Err(Error::Provider(ProviderFailure::Transport {
url: "http://x/v1".into(),
message: "the connection could not be established: refused".into(),
sent: false,
}))
}
fn timeout() -> Result<Message> {
Err(Error::Provider(ProviderFailure::Transport {
url: "http://x/v1".into(),
message: "the request timed out: deadline".into(),
sent: true,
}))
}
fn http(status: u16) -> HttpFailure {
HttpFailure {
status,
body: "nope".into(),
..HttpFailure::default()
}
}
fn status(code: u16) -> Result<Message> {
Err(Error::Provider(match code {
401 => ProviderFailure::Unauthorized(http(code)),
400 => ProviderFailure::InvalidRequest(http(code)),
_ => ProviderFailure::Http(http(code)),
}))
}
fn router(chain: &[(&str, &Arc<Scripted>)]) -> Router {
let entries = chain
.iter()
.map(|(name, p)| RouterEntry {
name: (*name).to_string(),
provider: Arc::clone(*p) as Arc<dyn ChatProvider>,
})
.collect();
Router::new(entries).unwrap()
}
fn text(m: &Message) -> &str {
m.content.as_deref().unwrap_or("")
}
fn routed(e: Error) -> (String, Vec<Hop>, RouteStop, ProviderFailure) {
match e {
Error::Provider(ProviderFailure::Routed {
route,
trail,
stop,
cause,
}) => (route, trail, stop, *cause),
other => panic!("not a routed failure: {other}"),
}
}
#[tokio::test]
async fn a_router_with_nothing_to_try_is_refused() {
assert!(Router::new(Vec::new()).is_err());
}
#[tokio::test]
async fn the_first_route_answers_and_nothing_hops() {
let a = Scripted::new(vec![reply("from a")]);
let b = Scripted::new(vec![reply("from b")]);
let r = router(&[("a", &a), ("b", &b)]);
let got = r.chat(&[Message::user("hi")], &[]).await.unwrap();
assert_eq!(text(&got), "from a");
assert!(r.hops().is_empty());
assert_eq!(b.calls(), 0);
assert_eq!(describe_hops(&r.hops()), None);
}
#[tokio::test]
async fn the_chain_is_tried_in_order_and_each_route_at_most_once() {
let a = Scripted::new(vec![timeout(), reply("a again")]);
let b = Scripted::new(vec![status(503), reply("b again")]);
let c = Scripted::new(vec![reply("from c"), reply("c again")]);
let r = router(&[("a", &a), ("b", &b), ("c", &c)]);
let got = r.chat(&[Message::user("hi")], &[]).await.unwrap();
assert_eq!(text(&got), "from c");
assert_eq!((a.calls(), b.calls(), c.calls()), (1, 1, 1));
let again = r.chat(&[Message::user("more")], &[]).await.unwrap();
assert_eq!(text(&again), "c again");
assert_eq!((a.calls(), b.calls(), c.calls()), (1, 1, 2));
assert_eq!(r.current(), "c");
}
#[tokio::test]
async fn a_route_that_failed_is_not_tried_again_when_a_later_one_fails() {
let a = Scripted::new(vec![down(), reply("never")]);
let b = Scripted::new(vec![reply("one"), down()]);
let c = Scripted::new(vec![reply("two")]);
let r = router(&[("a", &a), ("b", &b), ("c", &c)]);
assert_eq!(text(&r.chat(&[], &[]).await.unwrap()), "one");
assert_eq!(text(&r.chat(&[], &[]).await.unwrap()), "two");
assert_eq!(a.calls(), 1, "a failed in this run and stays failed");
}
#[tokio::test]
async fn every_hop_is_recorded_with_why_it_happened() {
let a = Scripted::new(vec![timeout()]);
let b = Scripted::new(vec![status(503)]);
let c = Scripted::new(vec![reply("ok")]);
let r = router(&[("local", &a), ("big", &b), ("cloud", &c)]);
r.chat(&[], &[]).await.unwrap();
let hops = r.hops();
assert_eq!(hops.len(), 2);
assert_eq!(hops[0].to_string(), "local \u{2192} big: timeout");
assert_eq!(hops[1].to_string(), "big \u{2192} cloud: HTTP 503");
assert_eq!(
describe_hops(&hops).as_deref(),
Some("route: local \u{2192} big \u{2192} cloud (timeout; HTTP 503)")
);
}
#[tokio::test]
async fn a_refused_connection_hops_and_says_unreachable() {
let a = Scripted::new(vec![down()]);
let b = Scripted::new(vec![reply("ok")]);
let r = router(&[("local", &a), ("big", &b)]);
r.chat(&[], &[]).await.unwrap();
assert_eq!(r.hops()[0].reason, "unreachable");
}
#[tokio::test]
async fn a_401_on_the_first_route_does_not_hop_and_names_the_route() {
let a = Scripted::new(vec![status(401)]);
let b = Scripted::new(vec![reply("never asked")]);
let r = router(&[("local", &a), ("big", &b)]);
let (route, trail, stop, cause) = routed(r.chat(&[], &[]).await.unwrap_err());
assert_eq!(route, "local");
assert!(trail.is_empty());
assert_eq!(stop, RouteStop::Failed);
assert_eq!(cause.status(), Some(401));
assert_eq!(b.calls(), 0, "a wrong key is not a transport hiccup");
assert!(r.hops().is_empty());
}
#[tokio::test]
async fn a_400_fails_the_run_instead_of_hiding_a_config_error() {
let a = Scripted::new(vec![status(400)]);
let b = Scripted::new(vec![reply("never asked")]);
let r = router(&[("local", &a), ("big", &b)]);
let err = r.chat(&[], &[]).await.unwrap_err();
assert!(err.to_string().contains("route `local` failed"), "{err}");
assert_eq!(b.calls(), 0);
}
#[tokio::test]
async fn a_failure_after_a_hop_names_the_route_it_failed_on_and_the_earlier_hop() {
let a = Scripted::new(vec![timeout()]);
let b = Scripted::new(vec![status(401)]);
let r = router(&[("local", &a), ("big", &b)]);
let err = r.chat(&[], &[]).await.unwrap_err();
let text = err.to_string();
assert!(text.contains("route `big` failed"), "{text}");
assert!(text.contains("local: timeout"), "{text}");
}
#[tokio::test]
async fn an_exhausted_chain_lists_every_route_and_why_each_failed() {
let a = Scripted::new(vec![timeout()]);
let b = Scripted::new(vec![status(503)]);
let r = router(&[("local", &a), ("big", &b)]);
let err = r.chat(&[], &[]).await.unwrap_err();
let shown = err.to_string();
assert!(shown.contains("every route failed"), "{shown}");
assert!(shown.contains("local: timeout"), "{shown}");
assert!(shown.contains("big: HTTP 503"), "{shown}");
let (route, trail, stop, _) = routed(err);
assert_eq!(
(route.as_str(), trail.len(), stop),
("big", 1, RouteStop::Exhausted)
);
}
#[tokio::test]
async fn a_single_route_that_fails_is_a_plain_failure_naming_it() {
let a = Scripted::new(vec![timeout()]);
let r = router(&[("local", &a)]);
let (route, _, stop, cause) = routed(r.chat(&[], &[]).await.unwrap_err());
assert_eq!((route.as_str(), stop), ("local", RouteStop::Failed));
assert!(cause.is_retryable());
}
#[tokio::test]
async fn a_stream_cut_before_any_text_hops_to_the_next_route() {
let a = Scripted::new(vec![Err(Error::Provider(ProviderFailure::Truncated {
message: "eof".into(),
streamed_chars: 0,
}))]);
let b = Scripted::new(vec![reply("whole")]);
let r = router(&[("a", &a), ("b", &b)]);
let seen = Mutex::new(String::new());
let got = r
.chat_stream(&[], &[], &|d| {
if let crate::stream::Delta::Text(t) = d {
seen.lock().unwrap().push_str(&t);
}
})
.await
.unwrap();
assert_eq!(text(&got), "whole");
assert_eq!(r.hops()[0].reason, "stream cut");
}
#[tokio::test]
async fn a_stream_cut_after_text_is_not_replayed_on_the_next_route() {
let a = Scripted::streaming_then(
"half an ans",
Err(Error::Provider(ProviderFailure::Truncated {
message: "eof".into(),
streamed_chars: 11,
})),
);
let b = Scripted::new(vec![reply("the whole answer")]);
let r = router(&[("a", &a), ("b", &b)]);
let seen = Mutex::new(String::new());
let err = r
.chat_stream(&[], &[], &|d| {
if let crate::stream::Delta::Text(t) = d {
seen.lock().unwrap().push_str(&t);
}
})
.await
.unwrap_err();
assert_eq!(b.calls(), 0, "the reader already has the start of a reply");
assert_eq!(&*seen.lock().unwrap(), "half an ans");
let shown = err.to_string();
assert!(shown.contains("already shown"), "{shown}");
assert!(shown.contains("route `a`"), "{shown}");
assert!(r.hops().is_empty());
assert_eq!(routed(err).2, RouteStop::AfterText);
}
#[tokio::test]
async fn the_last_route_cut_after_text_is_a_plain_failure_not_a_claim_of_replay() {
let a = Scripted::new(vec![timeout()]);
let b = Scripted::streaming_then(
"partial",
Err(Error::Provider(ProviderFailure::Truncated {
message: "eof".into(),
streamed_chars: 7,
})),
);
let r = router(&[("a", &a), ("b", &b)]);
let err = r.chat_stream(&[], &[], &|_| {}).await.unwrap_err();
assert_eq!(routed(err).2, RouteStop::Exhausted);
}
#[tokio::test]
async fn streaming_text_reaches_the_caller_once_when_the_answer_comes_from_a_later_route() {
let a = Scripted::new(vec![down()]);
let b = Scripted::streaming_then("hello", reply("hello"));
let r = router(&[("a", &a), ("b", &b)]);
let seen = Mutex::new(String::new());
r.chat_stream(&[], &[], &|d| {
if let crate::stream::Delta::Text(t) = d {
seen.lock().unwrap().push_str(&t);
}
})
.await
.unwrap();
assert_eq!(&*seen.lock().unwrap(), "hello");
}
#[tokio::test]
async fn the_patch_reaches_the_route_that_answers() {
let a = Scripted::new(vec![down()]);
let b = Scripted::new(vec![reply("ok")]);
let r = router(&[("a", &a), ("b", &b)]);
let patch = RequestPatch {
tool_choice: Some(crate::hooks::ToolChoice::None),
..RequestPatch::default()
};
r.chat_stream_patched(&[], &[], &|_| {}, &patch)
.await
.unwrap();
assert_eq!(*b.patch_seen.lock().unwrap(), Some(true));
}
#[tokio::test]
async fn usage_is_the_answering_routes_not_the_failed_ones() {
let usage = TurnUsage {
prompt_tokens: Some(7),
completion_tokens: Some(3),
..TurnUsage::default()
};
let a = Scripted::new(vec![down()]);
let b = Scripted::with_usage(vec![reply("ok")], usage.clone());
let r = router(&[("a", &a), ("b", &b)]);
r.chat(&[], &[]).await.unwrap();
assert_eq!(r.take_usage(), Some(usage));
assert_eq!(r.take_usage(), None, "taken, not borrowed");
}
#[test]
fn a_routed_failure_answers_a_callers_questions_as_its_cause_does() {
let f = ProviderFailure::Routed {
route: "local".into(),
trail: Vec::new(),
stop: RouteStop::Failed,
cause: Box::new(ProviderFailure::Unauthorized(http(401))),
};
assert_eq!(f.status(), Some(401));
assert!(!f.is_retryable());
assert_eq!(f.short_reason(), "HTTP 401");
assert_eq!(f.body(), Some("nope"));
}
}