Skip to main content

ag_ui/axum/
router.rs

1//! Mounting an agent on a router.
2//!
3//! ```
4//! use ag_ui::axum::RouterExt;
5//! use axum::Router;
6//! use axum::routing::get;
7//! # use ag_ui::RunOutcome;
8//! # use ag_ui::server::{Agent, Result, RunContext};
9//! # struct CartAgent;
10//! # impl Agent for CartAgent {
11//! #     type State = ();
12//! #     async fn run(&self, _ctx: &mut RunContext<()>) -> Result<RunOutcome> { Ok(RunOutcome::Success) }
13//! # }
14//!
15//! let app: Router = Router::new()
16//!     .route("/health", get(|| async { "ok" }))
17//!     .route_agui("/agent", CartAgent);
18//! # let _ = app;
19//! ```
20
21use std::num::NonZeroUsize;
22use std::sync::Arc;
23use std::time::Duration;
24
25use crate::RunAgentInput;
26use crate::server::{Agent, Runner, StreamTransformer, TransformerChain};
27use axum::Router;
28use axum::extract::Request;
29use axum::http::header;
30use axum::response::{IntoResponse, Response};
31use axum::routing::post;
32
33use crate::axum::extract::AgUiInput;
34use crate::axum::respond::SseResponse;
35
36/// Builds one transformer, once per run.
37type TransformerFactory = Arc<dyn Fn(&mut TransformerChain) + Send + Sync>;
38
39/// Receives one request's decoding warnings.
40type InputWarnings = Arc<dyn Fn(&RunAgentInput, &[String]) + Send + Sync>;
41
42/// An agent plus the per-run settings it is served with.
43///
44/// [`route_agui`](RouterExt::route_agui) mounts an agent with the defaults;
45/// build one of these and use [`route_agui_with`](RouterExt::route_agui_with)
46/// when you want to change them.
47///
48/// ```
49/// use ag_ui::axum::{AgentEndpoint, RouterExt};
50/// use ag_ui::server::FilterToolCalls;
51/// use axum::Router;
52/// use std::time::Duration;
53/// # use ag_ui::RunOutcome;
54/// # use ag_ui::server::{Agent, Result, RunContext};
55/// # struct CartAgent;
56/// # impl Agent for CartAgent {
57/// #     type State = ();
58/// #     async fn run(&self, _ctx: &mut RunContext<()>) -> Result<RunOutcome> { Ok(RunOutcome::Success) }
59/// # }
60///
61/// let endpoint = AgentEndpoint::new(CartAgent)
62///     .transformer(|| FilterToolCalls::deny(["internal_debug"]))
63///     .keep_alive(Duration::from_secs(10));
64///
65/// let app: Router = Router::new().route_agui_with("/agent", endpoint);
66/// # let _ = app;
67/// ```
68pub struct AgentEndpoint<A> {
69    agent: Arc<A>,
70    transformers: Vec<TransformerFactory>,
71    echo_input: bool,
72    keep_alive: Option<Duration>,
73    event_buffer_capacity: Option<NonZeroUsize>,
74    allow_missing_content_type: bool,
75    input_warnings: Option<InputWarnings>,
76}
77
78impl<A> AgentEndpoint<A> {
79    /// Wraps an agent with the default settings.
80    pub fn new(agent: A) -> Self {
81        Self {
82            agent: Arc::new(agent),
83            transformers: Vec::new(),
84            echo_input: false,
85            keep_alive: Some(Duration::from_secs(15)),
86            event_buffer_capacity: None,
87            allow_missing_content_type: false,
88            input_warnings: None,
89        }
90    }
91
92    /// Hands each request's decoding warnings to `hook`, with the input they
93    /// came from, before the run starts.
94    ///
95    /// A warning says what decoding removed or read as omitted: an
96    /// unrecognised field or enum member, a deprecated optional `null`. It
97    /// quotes at most 64 characters of the body, with control characters
98    /// escaped. The hook is called only for a request that has any. Without
99    /// one the warnings are discarded; the endpoint never prints them.
100    ///
101    /// ```
102    /// use ag_ui::axum::AgentEndpoint;
103    /// # use ag_ui::RunOutcome;
104    /// # use ag_ui::server::{Agent, Result, RunContext};
105    /// # struct CartAgent;
106    /// # impl Agent for CartAgent {
107    /// #     type State = ();
108    /// #     async fn run(&self, _ctx: &mut RunContext<()>) -> Result<RunOutcome> { Ok(RunOutcome::Success) }
109    /// # }
110    ///
111    /// let endpoint = AgentEndpoint::new(CartAgent).on_input_warnings(|input, warnings| {
112    ///     for warning in warnings {
113    ///         // Route it wherever the application logs.
114    ///         let _ = (&input.run_id, warning);
115    ///     }
116    /// });
117    /// # let _ = endpoint;
118    /// ```
119    #[must_use]
120    pub fn on_input_warnings<F>(mut self, hook: F) -> Self
121    where
122        F: Fn(&RunAgentInput, &[String]) + Send + Sync + 'static,
123    {
124        self.input_warnings = Some(Arc::new(hook));
125        self
126    }
127
128    /// Appends a transformer to every run's chain.
129    ///
130    /// # Why a closure and not a transformer
131    ///
132    /// A [`StreamTransformer`] takes `&mut self` because a useful one is a
133    /// state machine — [`FilterToolCalls`](crate::server::transform::FilterToolCalls)
134    /// remembers which call ids it dropped. One instance shared across
135    /// concurrent runs would leak one run's state into another, so the endpoint
136    /// stores the recipe and builds a fresh chain per request.
137    #[must_use]
138    pub fn transformer<F, T>(mut self, factory: F) -> Self
139    where
140        F: Fn() -> T + Send + Sync + 'static,
141        T: StreamTransformer + 'static,
142    {
143        self.transformers
144            .push(Arc::new(move |chain: &mut TransformerChain| {
145                chain.push(factory());
146            }));
147        self
148    }
149
150    /// Echoes the request body back on `RUN_STARTED`.
151    ///
152    /// See [`Runner::echo_input`](crate::server::run::Runner::echo_input). Off by default — it is the largest payload
153    /// in the protocol.
154    #[must_use]
155    pub fn echo_input(mut self, echo: bool) -> Self {
156        self.echo_input = echo;
157        self
158    }
159
160    /// Sends an SSE comment whenever a run produces nothing for `interval`.
161    ///
162    /// Defaults to 15 seconds. Comments keep idle connections active without
163    /// creating AG-UI events. Set an interval below your proxy's idle timeout.
164    /// See [`SseResponse::keep_alive`] and [`Self::without_keep_alive`].
165    #[must_use]
166    pub fn keep_alive(mut self, interval: Duration) -> Self {
167        self.keep_alive = Some(interval);
168        self
169    }
170
171    /// Disables the default SSE keep-alive comments.
172    ///
173    /// Use this when the hosting infrastructure already sends heartbeats or
174    /// an endpoint needs to stay completely silent between protocol events.
175    /// Calling [`Self::keep_alive`] afterwards enables comments again.
176    #[must_use]
177    pub fn without_keep_alive(mut self) -> Self {
178        self.keep_alive = None;
179        self
180    }
181
182    /// Limits each run's queued events. See
183    /// [`Runner::event_buffer_capacity`](crate::server::run::Runner::event_buffer_capacity).
184    /// Overflow produces an `EVENT_BUFFER_FULL` terminal error; callers using
185    /// durable execution can reconnect from their application's saved state.
186    #[must_use]
187    pub fn event_buffer_capacity(mut self, capacity: NonZeroUsize) -> Self {
188        self.event_buffer_capacity = Some(capacity);
189        self
190    }
191
192    /// Reads a request that carries no `Content-Type` as JSON, instead of
193    /// refusing it with `415`.
194    ///
195    /// For clients that send no header and cannot be changed to. Off by
196    /// default, and turning it on gives up what requiring a JSON media type
197    /// buys — see [`AgUiInput`](crate::axum::AgUiInput#the-content-type-is-required).
198    /// A header that names something other than JSON is refused either way.
199    #[must_use]
200    pub fn allow_missing_content_type(mut self) -> Self {
201        self.allow_missing_content_type = true;
202        self
203    }
204
205    /// A fresh chain for one run.
206    fn chain(&self) -> TransformerChain {
207        let mut chain = TransformerChain::new();
208        for factory in &self.transformers {
209            factory(&mut chain);
210        }
211        chain
212    }
213}
214
215impl<A: Agent + 'static> AgentEndpoint<A> {
216    /// Serves one request: negotiate, decode, run, stream.
217    ///
218    /// Negotiation is reported first. A request that fails both checks has
219    /// nothing in common with this endpoint at all, and saying so is more use
220    /// to the caller than a note about a body that was never going to be
221    /// answered.
222    async fn serve(&self, request: Request) -> Response {
223        let accept = request
224            .headers()
225            .get(header::ACCEPT)
226            .map(|value| String::from_utf8_lossy(value.as_bytes()));
227
228        let response = match SseResponse::negotiate(accept.as_deref()) {
229            Ok(response) => response,
230            Err(error) => return error.into_response(),
231        };
232        // The router's state is not this endpoint's business: the body is
233        // read the way `AgUiInput` reads it, under any state.
234        let input = match AgUiInput::read(request, &(), self.allow_missing_content_type).await {
235            Ok((AgUiInput(input), warnings)) => {
236                match &self.input_warnings {
237                    Some(hook) if !warnings.is_empty() => hook(&input, &warnings),
238                    _ => {}
239                }
240                input
241            }
242            Err(error) => return error.into_response(),
243        };
244
245        let mut runner = Runner::new(Arc::clone(&self.agent))
246            .transformers(self.chain())
247            .echo_input(self.echo_input);
248        if let Some(capacity) = self.event_buffer_capacity {
249            runner = runner.event_buffer_capacity(capacity);
250        }
251
252        // The token has to come off the runner before `run` consumes it.
253        let mut response = response.cancellation(runner.cancellation_token());
254        if let Some(interval) = self.keep_alive {
255            response = response.keep_alive(interval);
256        }
257        response.stream(runner.run(input))
258    }
259}
260
261impl<A> std::fmt::Debug for AgentEndpoint<A> {
262    /// Describes the settings, not the agent: an agent holds an LLM client and
263    /// a database handle, and neither is `Debug`.
264    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
265        f.debug_struct("AgentEndpoint")
266            .field("agent", &std::any::type_name::<A>())
267            .field("transformers", &self.transformers.len())
268            .field("echo_input", &self.echo_input)
269            .field("keep_alive", &self.keep_alive)
270            .field("event_buffer_capacity", &self.event_buffer_capacity)
271            .field(
272                "allow_missing_content_type",
273                &self.allow_missing_content_type,
274            )
275            .field("input_warnings", &self.input_warnings.is_some())
276            .finish()
277    }
278}
279
280/// Mounts AG-UI agents on an [`axum::Router`].
281///
282/// # What it does to the router
283///
284/// `route_agui(path, agent)` is `route(path, post(handler))` and nothing else:
285/// the endpoint composes with the router's other routes, with `nest`, `merge`
286/// and `fallback`, and with any layer applied before or after it. A `GET` on
287/// the path still gets axum's own `405`.
288///
289/// # The state parameter
290///
291/// The handler reads only the request, so it is a `Handler<_, S>` for **every**
292/// router state `S`. Mounting an agent therefore places no constraint on `S`
293/// beyond axum's own `Clone + Send + Sync + 'static`, and works the same in a
294/// `Router<()>` and in a `Router<AppState>` — including before
295/// [`with_state`](axum::Router::with_state) is called.
296///
297/// An agent that needs values from the router state should capture them when it
298/// is constructed (`CartAgent::new(state.catalog.clone())`). Extracting `State`
299/// inside the AG-UI handler would tie this crate's one-line mount to a single
300/// application's state type, which is the opposite of what it is for.
301pub trait RouterExt<S>: Sized {
302    /// Mounts `agent` as a `POST` endpoint at `path`.
303    ///
304    /// The endpoint answers with `text/event-stream`, cancels the run when the
305    /// client disconnects, sends an SSE comment after 15 seconds of silence,
306    /// and refuses a request it cannot answer with a `4xx`.
307    #[must_use]
308    fn route_agui<A>(self, path: &str, agent: A) -> Self
309    where
310        A: Agent + 'static,
311    {
312        self.route_agui_with(path, AgentEndpoint::new(agent))
313    }
314
315    /// Mounts a configured [`AgentEndpoint`] as a `POST` endpoint at `path`.
316    #[must_use]
317    fn route_agui_with<A>(self, path: &str, endpoint: AgentEndpoint<A>) -> Self
318    where
319        A: Agent + 'static;
320}
321
322impl<S> RouterExt<S> for Router<S>
323where
324    S: Clone + Send + Sync + 'static,
325{
326    fn route_agui_with<A>(self, path: &str, endpoint: AgentEndpoint<A>) -> Self
327    where
328        A: Agent + 'static,
329    {
330        // One `Arc` for the endpoint, cloned per request; the agent itself is
331        // never cloned. `Arc<A>: Agent` is what lets the runner take it by
332        // value.
333        let endpoint = Arc::new(endpoint);
334        self.route(
335            path,
336            post(move |request: Request| {
337                let endpoint = Arc::clone(&endpoint);
338                async move { endpoint.serve(request).await }
339            }),
340        )
341    }
342}