use std::num::NonZeroUsize;
use std::sync::Arc;
use std::time::Duration;
use crate::RunAgentInput;
use crate::server::{Agent, Runner, StreamTransformer, TransformerChain};
use axum::Router;
use axum::extract::Request;
use axum::http::header;
use axum::response::{IntoResponse, Response};
use axum::routing::post;
use crate::axum::extract::AgUiInput;
use crate::axum::respond::SseResponse;
type TransformerFactory = Arc<dyn Fn(&mut TransformerChain) + Send + Sync>;
type InputWarnings = Arc<dyn Fn(&RunAgentInput, &[String]) + Send + Sync>;
pub struct AgentEndpoint<A> {
agent: Arc<A>,
transformers: Vec<TransformerFactory>,
echo_input: bool,
keep_alive: Option<Duration>,
event_buffer_capacity: Option<NonZeroUsize>,
allow_missing_content_type: bool,
input_warnings: Option<InputWarnings>,
}
impl<A> AgentEndpoint<A> {
pub fn new(agent: A) -> Self {
Self {
agent: Arc::new(agent),
transformers: Vec::new(),
echo_input: false,
keep_alive: Some(Duration::from_secs(15)),
event_buffer_capacity: None,
allow_missing_content_type: false,
input_warnings: None,
}
}
#[must_use]
pub fn on_input_warnings<F>(mut self, hook: F) -> Self
where
F: Fn(&RunAgentInput, &[String]) + Send + Sync + 'static,
{
self.input_warnings = Some(Arc::new(hook));
self
}
#[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 without_keep_alive(mut self) -> Self {
self.keep_alive = None;
self
}
#[must_use]
pub fn event_buffer_capacity(mut self, capacity: NonZeroUsize) -> Self {
self.event_buffer_capacity = Some(capacity);
self
}
#[must_use]
pub fn allow_missing_content_type(mut self) -> Self {
self.allow_missing_content_type = true;
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, request: Request) -> Response {
let accept = request
.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 AgUiInput::read(request, &(), self.allow_missing_content_type).await {
Ok((AgUiInput(input), warnings)) => {
match &self.input_warnings {
Some(hook) if !warnings.is_empty() => hook(&input, &warnings),
_ => {}
}
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)
.field(
"allow_missing_content_type",
&self.allow_missing_content_type,
)
.field("input_warnings", &self.input_warnings.is_some())
.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 |request: Request| {
let endpoint = Arc::clone(&endpoint);
async move { endpoint.serve(request).await }
}),
)
}
}