troupekit-kit 0.4.0

Ergonomic API for the Troupekit LLM agent framework: one builder or one macro per agent, tool and graph.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
use super::{BuiltAgent, Input, RunOutcome};
use crate::error::KitError;
use async_trait::async_trait;
use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use tokio::sync::Notify;
use tokio::task::JoinHandle;
use troupekit_agent::{
    AgentError, AgentIo, AgentRun, EvalRegistry, EventSink, ModelHandle, UsageLedger,
};
use troupekit_core::clock::Clock;
use troupekit_core::event::{Event, EventBody};
use troupekit_core::ids::RunId;
use troupekit_core::inmem::InMemCheckpoints;
use troupekit_core::store::CheckpointStore;
use troupekit_tools::ToolRegistry;

/// Buffer settings of one streamed run. `capacity` (default 4096, from
/// `MIN_CAPACITY` to `MAX_CAPACITY`) bounds queued events: when full a new
/// text delta is dropped and counted; lifecycle events are always kept.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StreamSettings {
    pub capacity: usize,
}

impl StreamSettings {
    /// Smallest `capacity` `stream_with` accepts.
    /// Below it a burst of lifecycle events would crowd out every delta.
    /// Fixed at 16.
    pub const MIN_CAPACITY: usize = 16;

    /// Largest `capacity` `stream_with` accepts.
    /// Bounds the memory one unread stream can hold.
    /// Fixed at 1 048 576 events.
    pub const MAX_CAPACITY: usize = 1_048_576;

    pub(crate) fn check(&self, agent: &str) -> Result<(), KitError> {
        let range = StreamSettings::MIN_CAPACITY..=StreamSettings::MAX_CAPACITY;
        if range.contains(&self.capacity) {
            return Ok(());
        }
        Err(KitError::config(
            agent,
            format!(
                "stream capacity must be {} to {}, got {}",
                range.start(),
                range.end(),
                self.capacity
            ),
        ))
    }
}

impl Default for StreamSettings {
    /// Returns the default buffer of 4096 events.
    /// Enough for a long answer read at UI speed.
    /// Change `capacity` before passing it to `stream_with`.
    fn default() -> Self {
        StreamSettings { capacity: 4096 }
    }
}

/// A stop request shared by a stream and its run task. The run checks it
/// between steps, never inside one, so a model call in flight finishes and
/// is billed before the run stops. Setting it twice is a no-op.
#[derive(Clone, Default)]
pub(crate) struct Cancel(Arc<CancelState>);

#[derive(Default)]
struct CancelState {
    set: AtomicBool,
    changed: Notify,
}

impl Cancel {
    /// Asks the run to stop at its next step boundary and wakes a retry
    /// wait. Input: none. Output: none. Never blocks.
    pub(crate) fn set(&self) {
        self.0.set.store(true, Ordering::SeqCst);
        self.0.changed.notify_waiters();
    }

    /// Whether a stop was asked for. Input: none.
    /// Output: true once `set` was called.
    pub(crate) fn is_set(&self) -> bool {
        self.0.set.load(Ordering::SeqCst)
    }

    async fn wait(&self) {
        loop {
            let changed = self.0.changed.notified();
            tokio::pin!(changed);
            changed.as_mut().enable();
            if self.is_set() {
                return;
            }
            changed.await;
        }
    }

    /// Sleeps for `duration` unless a stop is asked for first.
    /// Input: the wait. Output: true when a stop cut the wait short.
    pub(crate) async fn sleep(&self, duration: Duration) -> bool {
        tokio::time::timeout(duration, self.wait()).await.is_ok()
    }
}

/// Runs `work` on its own task and waits for it. Dropping the returned
/// future sets `work`'s stop flag instead of dropping `work`, so a model
/// call in flight finishes and is billed before the run ends Cancelled.
/// Input: the run id and the work given its flag. Output: its result.
pub(crate) async fn detached<T, F>(
    run_id: RunId,
    work: impl FnOnce(Cancel) -> F,
) -> Result<T, KitError>
where
    F: std::future::Future<Output = Result<T, KitError>> + Send + 'static,
    T: Send + 'static,
{
    let cancel = Cancel::default();
    let work = work(cancel.clone());
    let task = match troupekit_trace::current() {
        Some(scope) => tokio::spawn(scope.in_scope(work)),
        None => tokio::spawn(work),
    };
    let _cancel = CancelOnDrop(&cancel);
    match task.await {
        Ok(result) => result,
        Err(err) if err.is_panic() => std::panic::resume_unwind(err.into_panic()),
        Err(_) => Err(KitError::Cancelled { run_id }),
    }
}

/// A run in progress that yields its events in `seq` order. Every method
/// takes `&self`, so one task may read events while another cancels or
/// waits in `finish`. Dropping the last owner cancels the run.
pub struct RunStream<T = RunOutcome> {
    run_id: RunId,
    queue: Arc<Queue>,
    cancel: Cancel,
    task: tokio::sync::Mutex<Option<JoinHandle<Result<T, KitError>>>>,
}

impl<T> RunStream<T> {
    pub(crate) fn spawn<F>(
        run_id: RunId,
        queue: Arc<Queue>,
        cancel: Cancel,
        task: F,
    ) -> RunStream<T>
    where
        F: std::future::Future<Output = Result<T, KitError>> + Send + 'static,
        T: Send + 'static,
    {
        let closer = Closer(queue.clone());
        let task = tokio::spawn(async move {
            let _closer = closer;
            task.await
        });
        RunStream {
            run_id,
            queue,
            cancel,
            task: tokio::sync::Mutex::new(Some(task)),
        }
    }

    /// Waits for the next event of the run.
    /// Output: the event, or `None` once the run is over and every
    /// queued event has been read. Safe to call from several tasks.
    pub async fn next(&self) -> Option<Event> {
        self.queue.pop().await
    }

    /// Returns the run id, known before the first event.
    /// Store it to resume the run after a cancel or a restart.
    /// Output: the id.
    pub fn run_id(&self) -> RunId {
        self.run_id
    }

    /// Returns how many text deltas were dropped because the buffer was
    /// full. The answer in `finish` is complete either way.
    /// Output: the count.
    pub fn dropped_deltas(&self) -> u64 {
        self.queue.dropped()
    }

    /// Stops the run after the step in flight, also while another task
    /// waits in `next` or `finish`. A model call already sent finishes and
    /// is billed and saved first, so `resume` never sends it again.
    /// Calling it twice, or after the end, is a no-op.
    pub fn cancel(&self) {
        self.cancel.set();
    }

    /// Waits for the run to end and returns its result, once. Dropping
    /// this future before the run ends cancels the run, like `cancel`.
    /// Output: the outcome, the run's error, `Cancelled` after a cancel,
    /// or `Config` on a second call. A panic in the run resumes here.
    pub async fn finish(&self) -> Result<T, KitError> {
        let mut slot = self.task.lock().await;
        let Some(task) = slot.as_mut() else {
            return Err(KitError::config(
                &self.run_id.to_string(),
                "finish was already called for this stream",
            ));
        };
        let _cancel = CancelOnDrop(&self.cancel);
        let joined = task.await;
        *slot = None;
        match joined {
            Ok(result) => result,
            Err(err) if err.is_panic() => std::panic::resume_unwind(err.into_panic()),
            Err(_) => Err(KitError::Cancelled {
                run_id: self.run_id,
            }),
        }
    }
}

/// Cancels the run when dropped. Held by `finish` while it joins, so a
/// `finish` future dropped mid-join (a timeout) stops the run after the
/// step in flight; once the join is done the cancel is a no-op.
struct CancelOnDrop<'a>(&'a Cancel);

impl Drop for CancelOnDrop<'_> {
    /// Asks the run to stop at its next step boundary. Output: none.
    /// Safe on a run that has already ended.
    /// Never blocks.
    fn drop(&mut self) {
        self.0.set();
    }
}

impl<T> Drop for RunStream<T> {
    /// Cancels the run when the stream is dropped, so an unread stream
    /// stops calling the model after the step in flight, which is billed;
    /// `finish` guards its own future the same way. A no-op once it ended.
    fn drop(&mut self) {
        self.cancel.set();
    }
}

impl<T> std::fmt::Debug for RunStream<T> {
    /// Writes the run id and the dropped delta count.
    /// The queued events are not shown.
    /// Output: the debug text.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RunStream")
            .field("run_id", &self.run_id)
            .field("dropped_deltas", &self.dropped_deltas())
            .finish_non_exhaustive()
    }
}

impl BuiltAgent {
    /// Starts a run on `input` and returns its event stream once the run
    /// id is known, with the default buffer. Fails at the call on a bad
    /// input or setup, as `start` does. Needs no durable storage.
    pub async fn stream(&self, input: impl Into<Input>) -> Result<RunStream, KitError> {
        self.stream_with(input, StreamSettings::default()).await
    }

    /// Starts a streamed run on `input` with `settings`. Events also reach
    /// the agent's own `.events(..)` sink. Fails with `Config` when the
    /// capacity is out of range, else as `stream`.
    pub async fn stream_with(
        &self,
        input: impl Into<Input>,
        settings: StreamSettings,
    ) -> Result<RunStream, KitError> {
        let inner = &self.inner;
        settings.check(&inner.persona.name)?;
        let messages = self.messages(input.into()).await?;
        let queue = Arc::new(Queue::new(settings.capacity));
        let io = StreamIo {
            base: self.clone(),
            queue: queue.clone(),
        };
        let mut run = AgentRun::new(&inner.persona, messages, inner.limits.clone(), &io).await?;
        let run_id = run.run_id();
        let store: Arc<dyn CheckpointStore> = match &inner.store {
            Some(store) => store.clone(),
            None => Arc::new(InMemCheckpoints::default()),
        };
        store.save(run.checkpoint()).await?;
        let agent = self.clone();
        let cancel = Cancel::default();
        let stop = cancel.clone();
        let task = async move { agent.finish(&io, &mut run, store.as_ref(), &stop).await };
        assert_eq!(queue.dropped(), 0);
        Ok(RunStream::spawn(run_id, queue, cancel, task))
    }
}

pub(crate) struct Queue {
    state: Mutex<QueueState>,
    ready: Notify,
    capacity: usize,
}

struct QueueState {
    events: VecDeque<Event>,
    dropped: u64,
    closed: bool,
}

impl Queue {
    pub(crate) fn new(capacity: usize) -> Queue {
        assert!(capacity >= StreamSettings::MIN_CAPACITY);
        assert!(capacity <= StreamSettings::MAX_CAPACITY);
        Queue {
            state: Mutex::new(QueueState {
                events: VecDeque::new(),
                dropped: 0,
                closed: false,
            }),
            ready: Notify::new(),
            capacity,
        }
    }

    fn push(&self, event: Event) {
        let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
        if state.closed {
            return;
        }
        let delta = matches!(event.body, EventBody::TextDelta { .. });
        if delta && state.events.len() >= self.capacity {
            state.dropped += 1;
            return;
        }
        state.events.push_back(event);
        drop(state);
        self.ready.notify_one();
    }

    fn close(&self) {
        let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
        state.closed = true;
        drop(state);
        self.ready.notify_waiters();
        self.ready.notify_one();
    }

    async fn pop(&self) -> Option<Event> {
        loop {
            let notified = self.ready.notified();
            tokio::pin!(notified);
            notified.as_mut().enable();
            {
                let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
                if let Some(event) = state.events.pop_front() {
                    return Some(event);
                }
                if state.closed {
                    return None;
                }
            }
            notified.await;
        }
    }

    pub(crate) fn dropped(&self) -> u64 {
        self.state
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .dropped
    }
}

struct Closer(Arc<Queue>);

impl Drop for Closer {
    /// Closes the queue when the run task ends for any reason: an answer,
    /// an error with no final event such as `Retries`, a panic or a
    /// cancel. `next` then returns `None` after the queued events.
    fn drop(&mut self) {
        self.0.close();
    }
}

impl EventSink for Queue {
    fn emit(&self, event: Event) {
        self.push(event);
    }
}

pub(crate) trait BaseIo: Send + Sync + 'static {
    fn io(&self) -> &dyn AgentIo;
}

impl BaseIo for BuiltAgent {
    fn io(&self) -> &dyn AgentIo {
        &self.inner.io
    }
}

impl BaseIo for Arc<dyn AgentIo> {
    fn io(&self) -> &dyn AgentIo {
        self.as_ref()
    }
}

/// The io of one streamed run: everything from `base`, except that each
/// event goes to the stream's queue and then to `base`'s own sink, so a
/// user sink set with `.events(..)` still sees every event.
pub(crate) struct StreamIo<B> {
    pub(crate) base: B,
    pub(crate) queue: Arc<Queue>,
}

impl<B: BaseIo> EventSink for StreamIo<B> {
    fn emit(&self, event: Event) {
        self.queue.push(event.clone());
        self.base.io().events().emit(event);
    }
}

#[async_trait]
impl<B: BaseIo> AgentIo for StreamIo<B> {
    async fn model(&self, selector: &str) -> Result<ModelHandle, AgentError> {
        self.base.io().model(selector).await
    }

    fn tools(&self) -> &ToolRegistry {
        self.base.io().tools()
    }

    fn evals(&self) -> &EvalRegistry {
        self.base.io().evals()
    }

    fn ledger(&self) -> &dyn UsageLedger {
        self.base.io().ledger()
    }

    fn events(&self) -> &dyn EventSink {
        self
    }

    fn clock(&self) -> &dyn Clock {
        self.base.io().clock()
    }
}