Skip to main content

troupekit_kit/built/
stream.rs

1use super::{BuiltAgent, Input, RunOutcome};
2use crate::error::KitError;
3use async_trait::async_trait;
4use std::collections::VecDeque;
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::sync::{Arc, Mutex, PoisonError};
7use std::time::Duration;
8use tokio::sync::Notify;
9use tokio::task::JoinHandle;
10use troupekit_agent::{
11    AgentError, AgentIo, AgentRun, EvalRegistry, EventSink, ModelHandle, UsageLedger,
12};
13use troupekit_core::clock::Clock;
14use troupekit_core::event::{Event, EventBody};
15use troupekit_core::ids::RunId;
16use troupekit_core::inmem::InMemCheckpoints;
17use troupekit_core::store::CheckpointStore;
18use troupekit_tools::ToolRegistry;
19
20/// Buffer settings of one streamed run. `capacity` (default 4096, from
21/// `MIN_CAPACITY` to `MAX_CAPACITY`) bounds queued events: when full a new
22/// text delta is dropped and counted; lifecycle events are always kept.
23#[non_exhaustive]
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub struct StreamSettings {
26    pub capacity: usize,
27}
28
29impl StreamSettings {
30    /// Smallest `capacity` `stream_with` accepts.
31    /// Below it a burst of lifecycle events would crowd out every delta.
32    /// Fixed at 16.
33    pub const MIN_CAPACITY: usize = 16;
34
35    /// Largest `capacity` `stream_with` accepts.
36    /// Bounds the memory one unread stream can hold.
37    /// Fixed at 1 048 576 events.
38    pub const MAX_CAPACITY: usize = 1_048_576;
39
40    pub(crate) fn check(&self, agent: &str) -> Result<(), KitError> {
41        let range = StreamSettings::MIN_CAPACITY..=StreamSettings::MAX_CAPACITY;
42        if range.contains(&self.capacity) {
43            return Ok(());
44        }
45        Err(KitError::config(
46            agent,
47            format!(
48                "stream capacity must be {} to {}, got {}",
49                range.start(),
50                range.end(),
51                self.capacity
52            ),
53        ))
54    }
55}
56
57impl Default for StreamSettings {
58    /// Returns the default buffer of 4096 events.
59    /// Enough for a long answer read at UI speed.
60    /// Change `capacity` before passing it to `stream_with`.
61    fn default() -> Self {
62        StreamSettings { capacity: 4096 }
63    }
64}
65
66/// A stop request shared by a stream and its run task. The run checks it
67/// between steps, never inside one, so a model call in flight finishes and
68/// is billed before the run stops. Setting it twice is a no-op.
69#[derive(Clone, Default)]
70pub(crate) struct Cancel(Arc<CancelState>);
71
72#[derive(Default)]
73struct CancelState {
74    set: AtomicBool,
75    changed: Notify,
76}
77
78impl Cancel {
79    /// Asks the run to stop at its next step boundary and wakes a retry
80    /// wait. Input: none. Output: none. Never blocks.
81    pub(crate) fn set(&self) {
82        self.0.set.store(true, Ordering::SeqCst);
83        self.0.changed.notify_waiters();
84    }
85
86    /// Whether a stop was asked for. Input: none.
87    /// Output: true once `set` was called.
88    pub(crate) fn is_set(&self) -> bool {
89        self.0.set.load(Ordering::SeqCst)
90    }
91
92    async fn wait(&self) {
93        loop {
94            let changed = self.0.changed.notified();
95            tokio::pin!(changed);
96            changed.as_mut().enable();
97            if self.is_set() {
98                return;
99            }
100            changed.await;
101        }
102    }
103
104    /// Sleeps for `duration` unless a stop is asked for first.
105    /// Input: the wait. Output: true when a stop cut the wait short.
106    pub(crate) async fn sleep(&self, duration: Duration) -> bool {
107        tokio::time::timeout(duration, self.wait()).await.is_ok()
108    }
109}
110
111/// Runs `work` on its own task and waits for it. Dropping the returned
112/// future sets `work`'s stop flag instead of dropping `work`, so a model
113/// call in flight finishes and is billed before the run ends Cancelled.
114/// Input: the run id and the work given its flag. Output: its result.
115pub(crate) async fn detached<T, F>(
116    run_id: RunId,
117    work: impl FnOnce(Cancel) -> F,
118) -> Result<T, KitError>
119where
120    F: std::future::Future<Output = Result<T, KitError>> + Send + 'static,
121    T: Send + 'static,
122{
123    let cancel = Cancel::default();
124    let work = work(cancel.clone());
125    let task = match troupekit_trace::current() {
126        Some(scope) => tokio::spawn(scope.in_scope(work)),
127        None => tokio::spawn(work),
128    };
129    let _cancel = CancelOnDrop(&cancel);
130    match task.await {
131        Ok(result) => result,
132        Err(err) if err.is_panic() => std::panic::resume_unwind(err.into_panic()),
133        Err(_) => Err(KitError::Cancelled { run_id }),
134    }
135}
136
137/// A run in progress that yields its events in `seq` order. Every method
138/// takes `&self`, so one task may read events while another cancels or
139/// waits in `finish`. Dropping the last owner cancels the run.
140pub struct RunStream<T = RunOutcome> {
141    run_id: RunId,
142    queue: Arc<Queue>,
143    cancel: Cancel,
144    task: tokio::sync::Mutex<Option<JoinHandle<Result<T, KitError>>>>,
145}
146
147impl<T> RunStream<T> {
148    pub(crate) fn spawn<F>(
149        run_id: RunId,
150        queue: Arc<Queue>,
151        cancel: Cancel,
152        task: F,
153    ) -> RunStream<T>
154    where
155        F: std::future::Future<Output = Result<T, KitError>> + Send + 'static,
156        T: Send + 'static,
157    {
158        let closer = Closer(queue.clone());
159        let task = tokio::spawn(async move {
160            let _closer = closer;
161            task.await
162        });
163        RunStream {
164            run_id,
165            queue,
166            cancel,
167            task: tokio::sync::Mutex::new(Some(task)),
168        }
169    }
170
171    /// Waits for the next event of the run.
172    /// Output: the event, or `None` once the run is over and every
173    /// queued event has been read. Safe to call from several tasks.
174    pub async fn next(&self) -> Option<Event> {
175        self.queue.pop().await
176    }
177
178    /// Returns the run id, known before the first event.
179    /// Store it to resume the run after a cancel or a restart.
180    /// Output: the id.
181    pub fn run_id(&self) -> RunId {
182        self.run_id
183    }
184
185    /// Returns how many text deltas were dropped because the buffer was
186    /// full. The answer in `finish` is complete either way.
187    /// Output: the count.
188    pub fn dropped_deltas(&self) -> u64 {
189        self.queue.dropped()
190    }
191
192    /// Stops the run after the step in flight, also while another task
193    /// waits in `next` or `finish`. A model call already sent finishes and
194    /// is billed and saved first, so `resume` never sends it again.
195    /// Calling it twice, or after the end, is a no-op.
196    pub fn cancel(&self) {
197        self.cancel.set();
198    }
199
200    /// Waits for the run to end and returns its result, once. Dropping
201    /// this future before the run ends cancels the run, like `cancel`.
202    /// Output: the outcome, the run's error, `Cancelled` after a cancel,
203    /// or `Config` on a second call. A panic in the run resumes here.
204    pub async fn finish(&self) -> Result<T, KitError> {
205        let mut slot = self.task.lock().await;
206        let Some(task) = slot.as_mut() else {
207            return Err(KitError::config(
208                &self.run_id.to_string(),
209                "finish was already called for this stream",
210            ));
211        };
212        let _cancel = CancelOnDrop(&self.cancel);
213        let joined = task.await;
214        *slot = None;
215        match joined {
216            Ok(result) => result,
217            Err(err) if err.is_panic() => std::panic::resume_unwind(err.into_panic()),
218            Err(_) => Err(KitError::Cancelled {
219                run_id: self.run_id,
220            }),
221        }
222    }
223}
224
225/// Cancels the run when dropped. Held by `finish` while it joins, so a
226/// `finish` future dropped mid-join (a timeout) stops the run after the
227/// step in flight; once the join is done the cancel is a no-op.
228struct CancelOnDrop<'a>(&'a Cancel);
229
230impl Drop for CancelOnDrop<'_> {
231    /// Asks the run to stop at its next step boundary. Output: none.
232    /// Safe on a run that has already ended.
233    /// Never blocks.
234    fn drop(&mut self) {
235        self.0.set();
236    }
237}
238
239impl<T> Drop for RunStream<T> {
240    /// Cancels the run when the stream is dropped, so an unread stream
241    /// stops calling the model after the step in flight, which is billed;
242    /// `finish` guards its own future the same way. A no-op once it ended.
243    fn drop(&mut self) {
244        self.cancel.set();
245    }
246}
247
248impl<T> std::fmt::Debug for RunStream<T> {
249    /// Writes the run id and the dropped delta count.
250    /// The queued events are not shown.
251    /// Output: the debug text.
252    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
253        f.debug_struct("RunStream")
254            .field("run_id", &self.run_id)
255            .field("dropped_deltas", &self.dropped_deltas())
256            .finish_non_exhaustive()
257    }
258}
259
260impl BuiltAgent {
261    /// Starts a run on `input` and returns its event stream once the run
262    /// id is known, with the default buffer. Fails at the call on a bad
263    /// input or setup, as `start` does. Needs no durable storage.
264    pub async fn stream(&self, input: impl Into<Input>) -> Result<RunStream, KitError> {
265        self.stream_with(input, StreamSettings::default()).await
266    }
267
268    /// Starts a streamed run on `input` with `settings`. Events also reach
269    /// the agent's own `.events(..)` sink. Fails with `Config` when the
270    /// capacity is out of range, else as `stream`.
271    pub async fn stream_with(
272        &self,
273        input: impl Into<Input>,
274        settings: StreamSettings,
275    ) -> Result<RunStream, KitError> {
276        let inner = &self.inner;
277        settings.check(&inner.persona.name)?;
278        let messages = self.messages(input.into()).await?;
279        let queue = Arc::new(Queue::new(settings.capacity));
280        let io = StreamIo {
281            base: self.clone(),
282            queue: queue.clone(),
283        };
284        let mut run = AgentRun::new(&inner.persona, messages, inner.limits.clone(), &io).await?;
285        let run_id = run.run_id();
286        let store: Arc<dyn CheckpointStore> = match &inner.store {
287            Some(store) => store.clone(),
288            None => Arc::new(InMemCheckpoints::default()),
289        };
290        store.save(run.checkpoint()).await?;
291        let agent = self.clone();
292        let cancel = Cancel::default();
293        let stop = cancel.clone();
294        let task = async move { agent.finish(&io, &mut run, store.as_ref(), &stop).await };
295        assert_eq!(queue.dropped(), 0);
296        Ok(RunStream::spawn(run_id, queue, cancel, task))
297    }
298}
299
300pub(crate) struct Queue {
301    state: Mutex<QueueState>,
302    ready: Notify,
303    capacity: usize,
304}
305
306struct QueueState {
307    events: VecDeque<Event>,
308    dropped: u64,
309    closed: bool,
310}
311
312impl Queue {
313    pub(crate) fn new(capacity: usize) -> Queue {
314        assert!(capacity >= StreamSettings::MIN_CAPACITY);
315        assert!(capacity <= StreamSettings::MAX_CAPACITY);
316        Queue {
317            state: Mutex::new(QueueState {
318                events: VecDeque::new(),
319                dropped: 0,
320                closed: false,
321            }),
322            ready: Notify::new(),
323            capacity,
324        }
325    }
326
327    fn push(&self, event: Event) {
328        let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
329        if state.closed {
330            return;
331        }
332        let delta = matches!(event.body, EventBody::TextDelta { .. });
333        if delta && state.events.len() >= self.capacity {
334            state.dropped += 1;
335            return;
336        }
337        state.events.push_back(event);
338        drop(state);
339        self.ready.notify_one();
340    }
341
342    fn close(&self) {
343        let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
344        state.closed = true;
345        drop(state);
346        self.ready.notify_waiters();
347        self.ready.notify_one();
348    }
349
350    async fn pop(&self) -> Option<Event> {
351        loop {
352            let notified = self.ready.notified();
353            tokio::pin!(notified);
354            notified.as_mut().enable();
355            {
356                let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
357                if let Some(event) = state.events.pop_front() {
358                    return Some(event);
359                }
360                if state.closed {
361                    return None;
362                }
363            }
364            notified.await;
365        }
366    }
367
368    pub(crate) fn dropped(&self) -> u64 {
369        self.state
370            .lock()
371            .unwrap_or_else(PoisonError::into_inner)
372            .dropped
373    }
374}
375
376struct Closer(Arc<Queue>);
377
378impl Drop for Closer {
379    /// Closes the queue when the run task ends for any reason: an answer,
380    /// an error with no final event such as `Retries`, a panic or a
381    /// cancel. `next` then returns `None` after the queued events.
382    fn drop(&mut self) {
383        self.0.close();
384    }
385}
386
387impl EventSink for Queue {
388    fn emit(&self, event: Event) {
389        self.push(event);
390    }
391}
392
393pub(crate) trait BaseIo: Send + Sync + 'static {
394    fn io(&self) -> &dyn AgentIo;
395}
396
397impl BaseIo for BuiltAgent {
398    fn io(&self) -> &dyn AgentIo {
399        &self.inner.io
400    }
401}
402
403impl BaseIo for Arc<dyn AgentIo> {
404    fn io(&self) -> &dyn AgentIo {
405        self.as_ref()
406    }
407}
408
409/// The io of one streamed run: everything from `base`, except that each
410/// event goes to the stream's queue and then to `base`'s own sink, so a
411/// user sink set with `.events(..)` still sees every event.
412pub(crate) struct StreamIo<B> {
413    pub(crate) base: B,
414    pub(crate) queue: Arc<Queue>,
415}
416
417impl<B: BaseIo> EventSink for StreamIo<B> {
418    fn emit(&self, event: Event) {
419        self.queue.push(event.clone());
420        self.base.io().events().emit(event);
421    }
422}
423
424#[async_trait]
425impl<B: BaseIo> AgentIo for StreamIo<B> {
426    async fn model(&self, selector: &str) -> Result<ModelHandle, AgentError> {
427        self.base.io().model(selector).await
428    }
429
430    fn tools(&self) -> &ToolRegistry {
431        self.base.io().tools()
432    }
433
434    fn evals(&self) -> &EvalRegistry {
435        self.base.io().evals()
436    }
437
438    fn ledger(&self) -> &dyn UsageLedger {
439        self.base.io().ledger()
440    }
441
442    fn events(&self) -> &dyn EventSink {
443        self
444    }
445
446    fn clock(&self) -> &dyn Clock {
447        self.base.io().clock()
448    }
449}