Skip to main content

ag_ui/client/
agent.rs

1//! The low-level API: start a run, get its events.
2//!
3//! [`RemoteAgent`] adds almost nothing to [`Transport`] — a request builder, and
4//! a stream that flattens connecting into streaming. That is the point. Anything
5//! that wants the events *as they were sent* — a proxy, a recorder, a bridge to
6//! another protocol, a test — should stay at this level.
7//!
8//! For a UI, [`Thread`](crate::client::Thread) sits on top of this and does the
9//! assembling.
10//!
11//! ```no_run
12//! # #[cfg(feature = "http")]
13//! # async fn example() -> Result<(), ag_ui::client::Error> {
14//! use ag_ui::client::{HttpAgent, RunParams};
15//! use futures_util::StreamExt;
16//!
17//! let agent = HttpAgent::builder("https://example.com/agent")
18//!     .header("authorization", "Bearer …")
19//!     .build()?;
20//!
21//! let mut events = agent.run_events(
22//!     RunParams::new("thread-1", "run-1").user("msg-1", "What is the weather?"),
23//! );
24//!
25//! while let Some(event) = events.next().await {
26//!     println!("{:?}", event?.event_type());
27//! }
28//! # Ok(())
29//! # }
30//! ```
31
32use crate::{
33    Context, Message, MessageId, ResumeEntry, RunAgentInput, RunId, ThreadId, Tool, UserContent,
34};
35use futures_util::TryStreamExt;
36use serde_json::Value;
37
38use crate::client::transport::{EventStream, Transport, boxed_stream};
39
40#[cfg(feature = "http")]
41use crate::client::error::Result;
42#[cfg(feature = "http")]
43use crate::client::transport::{HttpTransport, HttpTransportBuilder};
44
45/// What to send when starting a run.
46///
47/// A builder over [`RunAgentInput`]: the two ids are required, everything else
48/// has a sensible empty default. `agent.run_events(…)` takes anything that converts
49/// into the input, so a hand-built [`RunAgentInput`] works just as well.
50///
51/// [`RunAgentInput`]: https://kimsoungryoul.github.io/ag-ui-rust/api/ag_ui/input/struct.RunAgentInput.html
52#[derive(Clone, Debug, Default, PartialEq)]
53pub struct RunParams {
54    input: RunAgentInput,
55}
56
57impl RunParams {
58    /// A run in `thread_id`, identified by `run_id`.
59    pub fn new(thread_id: impl Into<ThreadId>, run_id: impl Into<RunId>) -> Self {
60        Self {
61            input: RunAgentInput::new(thread_id, run_id),
62        }
63    }
64
65    /// Sets the conversation history, oldest first.
66    #[must_use]
67    pub fn messages(mut self, messages: impl Into<Vec<Message>>) -> Self {
68        self.input.messages = messages.into();
69        self
70    }
71
72    /// Appends one message.
73    #[must_use]
74    pub fn message(mut self, message: impl Into<Message>) -> Self {
75        self.input.messages.push(message.into());
76        self
77    }
78
79    /// Appends a user message — the common case, spelled short.
80    #[must_use]
81    pub fn user(self, id: impl Into<MessageId>, content: impl Into<UserContent>) -> Self {
82        self.message(Message::user(id, content))
83    }
84
85    /// Sets the shared state the agent starts from.
86    #[must_use]
87    pub fn state(mut self, state: impl Into<Value>) -> Self {
88        self.input.state = state.into();
89        self
90    }
91
92    /// Offers tools for this run.
93    #[must_use]
94    pub fn tools(mut self, tools: impl Into<Vec<Tool>>) -> Self {
95        self.input.tools = tools.into();
96        self
97    }
98
99    /// Sets the ambient context entries.
100    #[must_use]
101    pub fn context(mut self, context: impl Into<Vec<Context>>) -> Self {
102        self.input.context = context.into();
103        self
104    }
105
106    /// Sets the passthrough properties, which the protocol never interprets.
107    #[must_use]
108    pub fn forwarded_props(mut self, props: impl Into<Value>) -> Self {
109        self.input.forwarded_props = props.into();
110        self
111    }
112
113    /// Answers the interrupts a previous run paused on. See
114    /// [`crate::client::interrupts`].
115    #[must_use]
116    pub fn resume(mut self, entries: impl Into<Vec<ResumeEntry>>) -> Self {
117        self.input.resume = Some(entries.into());
118        self
119    }
120
121    /// Records the run that spawned this one, for nested agents.
122    #[must_use]
123    pub fn parent_run_id(mut self, run_id: impl Into<RunId>) -> Self {
124        self.input.parent_run_id = Some(run_id.into());
125        self
126    }
127
128    /// The request this describes.
129    pub fn into_input(self) -> RunAgentInput {
130        self.input
131    }
132}
133
134impl From<RunParams> for RunAgentInput {
135    fn from(params: RunParams) -> Self {
136        params.input
137    }
138}
139
140impl From<RunAgentInput> for RunParams {
141    fn from(input: RunAgentInput) -> Self {
142        Self { input }
143    }
144}
145
146/// A raw event interface over any [`Transport`]. HTTP, an in-process agent or a
147/// recorded fixture can supply events without normalization or state management.
148///
149/// # Not [`crate::server::Agent`]
150///
151/// The two crates sit on opposite ends of the same wire, and the word "agent"
152/// means the opposite thing at each end, so they do not share a name.
153/// [`crate::server::Agent`] is a *trait you implement* to be an agent;
154/// `RemoteAgent` is a *handle you hold* onto someone else's. An agent that calls
155/// another agent — the composition case — needs both in one file, and
156/// `impl Agent for X { … self.upstream: RemoteAgent<_> … }` reads correctly
157/// only because they are spelled differently.
158///
159/// [`crate::server::Agent`]: https://kimsoungryoul.github.io/ag-ui-rust/api/ag_ui/server/agent/trait.Agent.html
160#[derive(Clone, Debug, Default)]
161pub struct RemoteAgent<T> {
162    transport: T,
163}
164
165impl<T> RemoteAgent<T> {
166    /// An agent reached through `transport`.
167    pub fn new(transport: T) -> Self {
168        Self { transport }
169    }
170
171    /// The transport underneath.
172    pub fn transport(&self) -> &T {
173        &self.transport
174    }
175
176    /// Unwraps the transport.
177    pub fn into_transport(self) -> T {
178        self.transport
179    }
180}
181
182impl<T: Transport> RemoteAgent<T> {
183    /// Starts a run and streams its events, exactly as the agent sent them.
184    ///
185    /// Nothing is normalized, verified or assembled here — chunk events arrive
186    /// as chunk events. That is what a proxy wants; a UI wants
187    /// [`Thread`](crate::client::Thread).
188    ///
189    /// Connecting is folded into the stream: a transport that cannot reach the
190    /// agent yields one error item and ends.
191    pub fn run_events(&self, params: impl Into<RunAgentInput>) -> EventStream {
192        let connecting = self.transport.run(params.into());
193        boxed_stream(futures_util::stream::once(connecting).try_flatten())
194    }
195}
196
197/// An HTTP endpoint and reusable connection settings. Create independent local
198/// conversations with [`HttpAgent::thread`], or consume raw events with `run_events`.
199#[cfg(feature = "http")]
200#[derive(Clone, Debug)]
201pub struct HttpAgent {
202    agent: RemoteAgent<std::sync::Arc<HttpTransport>>,
203}
204
205#[cfg(feature = "http")]
206impl HttpAgent {
207    /// Connect to `url` using default settings. No request is made yet.
208    pub fn new(url: impl AsRef<str>) -> Result<Self> {
209        Ok(Self::from_transport(HttpTransport::new(url)?))
210    }
211    /// Use a caller-configured HTTP transport.
212    pub fn from_transport(transport: HttpTransport) -> Self {
213        Self {
214            agent: RemoteAgent::new(std::sync::Arc::new(transport)),
215        }
216    }
217    /// Configure headers, timeouts and the underlying HTTP client.
218    pub fn builder(url: impl AsRef<str>) -> HttpAgentBuilder {
219        HttpAgentBuilder {
220            transport: HttpTransport::builder(url),
221        }
222    }
223    /// An independent local conversation. This does not retrieve remote history.
224    pub fn thread(&self, id: impl Into<ThreadId>) -> crate::client::Thread<HttpTransport> {
225        crate::client::Thread::from_shared(self.agent.transport().clone(), id)
226    }
227    /// Initialize a typed conversation using a serializable state value.
228    pub fn thread_with_state<S: serde::Serialize + serde::de::DeserializeOwned>(
229        &self,
230        id: impl Into<ThreadId>,
231        state: S,
232    ) -> Result<crate::client::Thread<HttpTransport, S>> {
233        self.thread_builder(id)
234            .state(serde_json::to_value(state)?)
235            .build()
236    }
237    /// Configure initial history, state, tools, diagnostics and verification.
238    pub fn thread_builder<S>(
239        &self,
240        id: impl Into<ThreadId>,
241    ) -> crate::client::ThreadBuilder<HttpTransport, S> {
242        crate::client::ThreadBuilder::from_shared(self.agent.transport().clone(), id)
243    }
244    /// Restore a saved local JSON conversation with this endpoint's transport.
245    pub fn restore_thread(
246        &self,
247        snapshot: crate::client::ThreadSnapshot,
248    ) -> Result<crate::client::Thread<HttpTransport>> {
249        self.restore_thread_with_state(snapshot)
250    }
251    /// Restore and validate the current raw state against `S`.
252    pub fn restore_thread_with_state<S: serde::de::DeserializeOwned>(
253        &self,
254        snapshot: crate::client::ThreadSnapshot,
255    ) -> Result<crate::client::Thread<HttpTransport, S>> {
256        crate::client::Thread::restore_shared(self.agent.transport().clone(), snapshot)
257    }
258    /// Raw wire events, without normalization, validation or state application.
259    pub fn run_events(&self, params: impl Into<RunAgentInput>) -> EventStream {
260        self.agent.run_events(params)
261    }
262    /// Underlying transport settings.
263    pub fn transport(&self) -> &HttpTransport {
264        self.agent.transport()
265    }
266}
267
268/// Builds an [`HttpAgent`]: base URL, headers, timeouts.
269#[cfg(feature = "http")]
270#[derive(Clone, Debug)]
271pub struct HttpAgentBuilder {
272    transport: HttpTransportBuilder,
273}
274
275#[cfg(feature = "http")]
276impl HttpAgentBuilder {
277    /// Adds a header to every request.
278    #[must_use]
279    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
280        self.transport = self.transport.header(name, value);
281        self
282    }
283
284    /// Adds several headers.
285    #[must_use]
286    pub fn headers<K, V>(mut self, headers: impl IntoIterator<Item = (K, V)>) -> Self
287    where
288        K: Into<String>,
289        V: Into<String>,
290    {
291        self.transport = self.transport.headers(headers);
292        self
293    }
294
295    /// Bounds the whole run, streaming included.
296    #[must_use]
297    pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
298        self.transport = self.transport.timeout(timeout);
299        self
300    }
301
302    /// Bounds connection setup only, leaving the stream unbounded.
303    #[must_use]
304    pub fn connect_timeout(mut self, timeout: std::time::Duration) -> Self {
305        self.transport = self.transport.connect_timeout(timeout);
306        self
307    }
308
309    /// Uses a caller-supplied `reqwest` client.
310    #[must_use]
311    pub fn client(mut self, client: reqwest::Client) -> Self {
312        self.transport = self.transport.client(client);
313        self
314    }
315
316    /// Builds the agent.
317    ///
318    /// # Errors
319    ///
320    /// [`Error::Config`](crate::client::Error::Config) when the URL or a header is not
321    /// valid.
322    pub fn build(self) -> Result<HttpAgent> {
323        Ok(HttpAgent::from_transport(self.transport.build()?))
324    }
325}