use std::num::NonZeroUsize;
use std::sync::Arc;
use std::time::Duration;
use crate::server::{Agent, Runner, StreamTransformer, TransformerChain};
use axum::Router;
use axum::http::{HeaderMap, header};
use axum::response::{IntoResponse, Response};
use axum::routing::post;
use crate::axum::error::Error;
use crate::axum::extract::AgUiInput;
use crate::axum::respond::SseResponse;
type TransformerFactory = Arc<dyn Fn(&mut TransformerChain) + Send + Sync>;
pub struct AgentEndpoint<A> {
agent: Arc<A>,
transformers: Vec<TransformerFactory>,
echo_input: bool,
keep_alive: Option<Duration>,
event_buffer_capacity: Option<NonZeroUsize>,
}
impl<A> AgentEndpoint<A> {
pub fn new(agent: A) -> Self {
Self {
agent: Arc::new(agent),
transformers: Vec::new(),
echo_input: false,
keep_alive: None,
event_buffer_capacity: None,
}
}
#[must_use]
pub fn transformer<F, T>(mut self, factory: F) -> Self
where
F: Fn() -> T + Send + Sync + 'static,
T: StreamTransformer + 'static,
{
self.transformers
.push(Arc::new(move |chain: &mut TransformerChain| {
chain.push(factory());
}));
self
}
#[must_use]
pub fn echo_input(mut self, echo: bool) -> Self {
self.echo_input = echo;
self
}
#[must_use]
pub fn keep_alive(mut self, interval: Duration) -> Self {
self.keep_alive = Some(interval);
self
}
#[must_use]
pub fn event_buffer_capacity(mut self, capacity: NonZeroUsize) -> Self {
self.event_buffer_capacity = Some(capacity);
self
}
fn chain(&self) -> TransformerChain {
let mut chain = TransformerChain::new();
for factory in &self.transformers {
factory(&mut chain);
}
chain
}
}
impl<A: Agent + 'static> AgentEndpoint<A> {
async fn serve(&self, headers: HeaderMap, input: Result<AgUiInput, Error>) -> Response {
let accept = headers
.get(header::ACCEPT)
.map(|value| String::from_utf8_lossy(value.as_bytes()));
let response = match SseResponse::negotiate(accept.as_deref()) {
Ok(response) => response,
Err(error) => return error.into_response(),
};
let input = match input {
Ok(AgUiInput(input)) => input,
Err(error) => return error.into_response(),
};
let mut runner = Runner::new(Arc::clone(&self.agent))
.transformers(self.chain())
.echo_input(self.echo_input);
if let Some(capacity) = self.event_buffer_capacity {
runner = runner.event_buffer_capacity(capacity);
}
let mut response = response.cancellation(runner.cancellation_token());
if let Some(interval) = self.keep_alive {
response = response.keep_alive(interval);
}
response.stream(runner.run(input))
}
}
impl<A> std::fmt::Debug for AgentEndpoint<A> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AgentEndpoint")
.field("agent", &std::any::type_name::<A>())
.field("transformers", &self.transformers.len())
.field("echo_input", &self.echo_input)
.field("keep_alive", &self.keep_alive)
.field("event_buffer_capacity", &self.event_buffer_capacity)
.finish()
}
}
pub trait RouterExt<S>: Sized {
#[must_use]
fn route_agui<A>(self, path: &str, agent: A) -> Self
where
A: Agent + 'static,
{
self.route_agui_with(path, AgentEndpoint::new(agent))
}
#[must_use]
fn route_agui_with<A>(self, path: &str, endpoint: AgentEndpoint<A>) -> Self
where
A: Agent + 'static;
}
impl<S> RouterExt<S> for Router<S>
where
S: Clone + Send + Sync + 'static,
{
fn route_agui_with<A>(self, path: &str, endpoint: AgentEndpoint<A>) -> Self
where
A: Agent + 'static,
{
let endpoint = Arc::new(endpoint);
self.route(
path,
post(move |headers: HeaderMap, input: Result<AgUiInput, Error>| {
let endpoint = Arc::clone(&endpoint);
async move { endpoint.serve(headers, input).await }
}),
)
}
}