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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
use crate::error::KitError;
use crate::laws::Laws;
use serde_json::Value;
use crate::trace::{path_of, root_span, Traced};
use std::fmt;
use std::future::Future;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use troupekit_agent::{
    AgentError, AgentIo, AgentRun, EventSink, Limits, Persona, RunState, SimpleIo, StepOutcome,
};
use troupekit_core::event::{Event, Usage};
use troupekit_core::ids::RunId;
use troupekit_core::inmem::InMemCheckpoints;
use troupekit_core::message::{Message, Role};
use troupekit_core::store::CheckpointStore;
use troupekit_trace::Trace;

mod start;
mod stream;

pub use start::{Progress, MAX_STEPS_PER_WINDOW};
pub(crate) use stream::{detached, Cancel, Queue, StreamIo};
pub use stream::{RunStream, StreamSettings};

const BASE_RETRY_MS: u64 = 500;
const MAX_RETRY_MS: u64 = 30_000;

pub(crate) struct Discard;

impl EventSink for Discard {
    fn emit(&self, _event: Event) {}
}

/// What an agent runs on: one user text, or a prepared conversation.
/// Built from `&str`, `String`, one `Message` or a `Vec<Message>`.
/// An empty conversation fails when the run starts.
#[derive(Debug, Clone, PartialEq)]
pub struct Input(Vec<Message>);

impl From<&str> for Input {
    fn from(text: &str) -> Self {
        Input(vec![Message::text(Role::User, text)])
    }
}

impl From<String> for Input {
    fn from(text: String) -> Self {
        Input(vec![Message::text(Role::User, text)])
    }
}

impl From<Message> for Input {
    fn from(message: Message) -> Self {
        Input(vec![message])
    }
}

impl From<Vec<Message>> for Input {
    fn from(messages: Vec<Message>) -> Self {
        Input(messages)
    }
}

/// The result of one finished run: the answer and how it was reached.
/// `text` is the answer as text; `output` is the raw final value.
/// Read it through the getters.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct RunOutcome {
    text: String,
    output: Value,
    usage: Usage,
    model_calls: u32,
    run_id: RunId,
    messages: Vec<Message>,
    trace_path: Option<PathBuf>,
}

impl RunOutcome {
    /// Returns the answer as text: a string output as is, any other
    /// output as JSON text.
    /// The same text `run` returns.
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Returns the final output value of the run.
    /// A string for plain agents, a JSON value for typed output.
    /// Never null for a finished run.
    pub fn output(&self) -> &Value {
        &self.output
    }

    /// Returns the tokens and cost the run used, summed over calls.
    /// Cost is in millionths of a US dollar.
    /// Includes eval and repair calls.
    pub fn usage(&self) -> Usage {
        self.usage
    }

    /// Returns how many model calls the run made.
    /// Retried calls count once per attempt that reached the model.
    /// At least one for a finished run.
    pub fn model_calls(&self) -> u32 {
        self.model_calls
    }

    /// Returns the id of the run, for `resume` and logs.
    /// Unique per run.
    /// Stable across checkpoints.
    pub fn run_id(&self) -> RunId {
        self.run_id
    }

    /// Returns the whole conversation, input first.
    /// Includes tool calls and tool results.
    /// The last message is the answer.
    pub fn messages(&self) -> &[Message] {
        &self.messages
    }

    /// Returns the trace file this run was written to.
    /// `None` when tracing is off or goes to a custom sink.
    /// Every run of one built agent shares the file.
    pub fn trace_path(&self) -> Option<&Path> {
        self.trace_path.as_deref()
    }
}

/// An agent that passed every `build` check, ready to run many times.
/// Cheap to clone and safe to share across tasks; each run gets its own
/// state, and in-memory checkpoints are dropped after the run.
#[derive(Clone)]
pub struct BuiltAgent {
    inner: Arc<Inner>,
}

struct Inner {
    persona: Persona,
    io: SimpleIo,
    limits: Limits,
    store: Option<Arc<dyn CheckpointStore>>,
    retries: u32,
    laws: Laws,
    trace: Option<Traced>,
    #[cfg(feature = "knowledge")]
    preamble: Option<troupekit_context::tools::KnowledgeKit>,
}

impl BuiltAgent {
    pub(crate) fn new(
        persona: Persona,
        io: SimpleIo,
        limits: Limits,
        store: Option<Arc<dyn CheckpointStore>>,
        retries: u32,
        laws: Laws,
    ) -> Self {
        BuiltAgent {
            inner: Arc::new(Inner {
                persona,
                io,
                limits,
                store,
                retries,
                laws,
                trace: None,
                #[cfg(feature = "knowledge")]
                preamble: None,
            }),
        }
    }

    pub(crate) fn with_trace(mut self, trace: Option<Traced>) -> Self {
        let inner = Arc::get_mut(&mut self.inner).expect("a fresh BuiltAgent is not shared");
        inner.trace = trace;
        self
    }

    /// Returns the trace file this agent writes, one root span per run.
    /// `None` when tracing is off or goes to a custom sink.
    /// The file is created at `build`.
    pub fn trace_path(&self) -> Option<&Path> {
        path_of(&self.inner.trace)
    }

    async fn traced<T>(
        &self,
        run_id: Option<RunId>,
        work: impl Future<Output = Result<T, KitError>>,
        id_of: impl Fn(&T) -> RunId,
    ) -> Result<T, KitError> {
        let owner = self.inner.persona.name.as_str();
        let traced = self.inner.trace.as_ref();
        root_span(traced, Trace::Agents, "agent.run", owner, run_id, work, id_of).await
    }

    #[cfg(feature = "knowledge")]
    pub(crate) fn with_preamble(
        mut self,
        preamble: Option<troupekit_context::tools::KnowledgeKit>,
    ) -> Self {
        let inner = Arc::get_mut(&mut self.inner).expect("a fresh BuiltAgent is not shared");
        inner.preamble = preamble;
        self
    }

    #[cfg(feature = "knowledge")]
    async fn messages(&self, input: Input) -> Result<Vec<Message>, KitError> {
        match &self.inner.preamble {
            Some(kit) => crate::memory::prepend(kit, input.0).await,
            None => Ok(input.0),
        }
    }

    #[cfg(not(feature = "knowledge"))]
    async fn messages(&self, input: Input) -> Result<Vec<Message>, KitError> {
        Ok(input.0)
    }

    /// Runs the agent once on `input` and returns the answer as text.
    /// Retries transient provider failures; fails with `Failed`,
    /// `Paused` or `Retries` when the run ends without an answer.
    pub async fn run(&self, input: impl Into<Input>) -> Result<String, KitError> {
        Ok(self.run_with(input).await?.text)
    }

    /// Runs the agent once on `input` and returns the full outcome.
    /// Same failures as `run`.
    /// The run id in the outcome works with `resume`.
    pub async fn run_with(&self, input: impl Into<Input>) -> Result<RunOutcome, KitError> {
        let input = input.into();
        self.traced(None, self.run_untraced(input), RunOutcome::run_id)
            .await
    }

    async fn run_untraced(&self, input: Input) -> Result<RunOutcome, KitError> {
        let inner = &self.inner;
        let messages = self.messages(input).await?;
        let run =
            AgentRun::new(&inner.persona, messages, inner.limits.clone(), &inner.io).await?;
        let store: Arc<dyn CheckpointStore> = match &inner.store {
            Some(store) => store.clone(),
            None => Arc::new(InMemCheckpoints::default()),
        };
        let agent = self.clone();
        detached(run.run_id(), move |stop| async move {
            let mut run = run;
            agent.finish(&agent.inner.io, &mut run, store.as_ref(), &stop).await
        })
        .await
    }

    /// Continues run `run_id` from its latest checkpoint, after a crash
    /// or restart, and returns the answer. A finished run returns its
    /// answer again. Needs `Storage::sqlite(..)` or `Storage::custom(..)`.
    /// Refuses another agent's run; limits become the stricter of the
    /// run's and this agent's, and the retry budget counts across resumes.
    pub async fn resume(&self, run_id: RunId) -> Result<String, KitError> {
        self.traced(Some(run_id), self.resume_untraced(run_id), |_| run_id)
            .await
    }

    async fn resume_untraced(&self, run_id: RunId) -> Result<String, KitError> {
        let name = self.inner.persona.name.as_str();
        let Some(store) = &self.inner.store else {
            return Err(KitError::config(
                name,
                "resume needs Storage::sqlite(..) or Storage::custom(..) checkpoints",
            ));
        };
        let Some(checkpoint) = store.latest(run_id).await? else {
            return Err(KitError::config(
                name,
                format!("no checkpoint for run {run_id}"),
            ));
        };
        let mut run = AgentRun::from_checkpoint(&checkpoint)?;
        if run.persona() != name {
            return Err(KitError::config(
                name,
                format!(
                    "run {run_id} was started by agent `{}`; resume it with that agent",
                    run.persona()
                ),
            ));
        }
        let current = self.inner.limits.clone().with_budget(&self.inner.persona.budget);
        run.tighten(&current);
        let agent = self.clone();
        let store = store.clone();
        let outcome = detached(run_id, move |stop| async move {
            let mut run = run;
            agent.finish(&agent.inner.io, &mut run, store.as_ref(), &stop).await
        })
        .await?;
        Ok(outcome.text)
    }

    /// Returns the validated persona this agent runs.
    /// Built from the builder settings by `Persona::parse`.
    /// Read only.
    pub fn persona(&self) -> &Persona {
        &self.inner.persona
    }

    /// Returns the laws checked at `build`.
    /// 0.2 stores them; runs do not prove them yet.
    /// Read only.
    pub fn laws(&self) -> &Laws {
        &self.inner.laws
    }

    /// Refuses a restored run whose saved retry count is past this agent's
    /// cap, before any step: an earlier call already ended it with
    /// `Retries`. A count equal to the cap may still take its last retry.
    fn refuse_exhausted(&self, run: &AgentRun) -> Result<(), KitError> {
        let retries = run.retries();
        if retries <= self.inner.retries {
            return Ok(());
        }
        assert!(retries > 0);
        Err(KitError::Retries {
            run_id: run.run_id(),
            attempts: retries - 1,
            last_error: "retries were used up by an earlier call".into(),
        })
    }

    async fn finish(
        &self,
        io: &dyn AgentIo,
        run: &mut AgentRun,
        store: &dyn CheckpointStore,
        cancel: &Cancel,
    ) -> Result<RunOutcome, KitError> {
        match run.state().clone() {
            RunState::Done { output } => return Ok(self.outcome(run, output)),
            RunState::Failed { error } => {
                return Err(KitError::failed(run.run_id(), error, run.host_failed()))
            }
            RunState::Paused { reason, .. } => {
                return Err(KitError::Paused {
                    run_id: run.run_id(),
                    reason,
                })
            }
            _ => {}
        }
        self.refuse_exhausted(run)?;
        let saved_wait = retry_left(run, io.clock().now_ms());
        if !saved_wait.is_zero() {
            tokio::time::sleep(saved_wait).await;
        }
        run.set_retry_at_ms(None);
        loop {
            let step = drive_until(run, io, store, cancel)
                .await
                .map_err(|e| KitError::in_run(run.run_id(), e.into()))?;
            let Some(step) = step else {
                return Err(KitError::Cancelled {
                    run_id: run.run_id(),
                });
            };
            match step {
                StepOutcome::Done(output) => return Ok(self.outcome(run, output)),
                StepOutcome::Retry {
                    error,
                    retry_after_ms,
                } => {
                    assert!(run.retries() > 0);
                    let attempts = run.retries() - 1;
                    if attempts >= self.inner.retries {
                        return Err(KitError::Retries {
                            run_id: run.run_id(),
                            attempts,
                            last_error: error,
                        });
                    }
                    if cancel.sleep(retry_delay(attempts, retry_after_ms)).await {
                        return Err(KitError::Cancelled {
                            run_id: run.run_id(),
                        });
                    }
                }
                StepOutcome::Paused(reason) => {
                    return Err(KitError::Paused {
                        run_id: run.run_id(),
                        reason,
                    })
                }
                StepOutcome::Failed(reason) => {
                    return Err(KitError::failed(run.run_id(), reason, run.host_failed()))
                }
                StepOutcome::Continue => {
                    unreachable!("drive_until returns only a final, paused or retry outcome")
                }
            }
            assert!(run.retries() <= self.inner.retries);
        }
    }

    fn outcome(&self, run: &AgentRun, output: Value) -> RunOutcome {
        let mut outcome = outcome(run, output);
        outcome.trace_path = self.trace_path().map(Path::to_path_buf);
        outcome
    }
}

impl fmt::Debug for BuiltAgent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let inner = &self.inner;
        f.debug_struct("BuiltAgent")
            .field("name", &inner.persona.name)
            .field("model", &inner.persona.model)
            .field("tools", &inner.persona.tools)
            .field("retries", &inner.retries)
            .field("durable", &inner.store.is_some())
            .field("laws", &inner.laws)
            .finish_non_exhaustive()
    }
}

fn outcome(run: &AgentRun, output: Value) -> RunOutcome {
    let text = match &output {
        Value::String(text) => text.clone(),
        other => other.to_string(),
    };
    RunOutcome {
        text,
        output,
        usage: run.usage(),
        model_calls: run.model_calls(),
        run_id: run.run_id(),
        messages: run.messages().to_vec(),
        trace_path: None,
    }
}

/// Steps `run`, saving after every step, until a step ends in something
/// other than `Continue`, as `drive` does, but checks `cancel` around each
/// step, so a step in flight always finishes, is billed and saved, then
/// stops. Output: the outcome, `None` once a stop was asked for, or the
/// store error.
async fn drive_until(
    run: &mut AgentRun,
    io: &dyn AgentIo,
    store: &dyn CheckpointStore,
    cancel: &Cancel,
) -> Result<Option<StepOutcome>, AgentError> {
    if store.latest(run.run_id()).await?.is_none() {
        store.save(run.checkpoint()).await?;
    }
    loop {
        if cancel.is_set() {
            return Ok(None);
        }
        let outcome = run.step(io).await;
        store.save(run.checkpoint()).await?;
        if cancel.is_set() {
            return Ok(None);
        }
        if outcome != StepOutcome::Continue {
            return Ok(Some(outcome));
        }
    }
}

fn retry_delay(attempt: u32, retry_after_ms: Option<u64>) -> Duration {
    let backoff = BASE_RETRY_MS.saturating_mul(1u64 << attempt.min(16));
    Duration::from_millis(retry_after_ms.unwrap_or(backoff).min(MAX_RETRY_MS))
}

/// Records on `run` the wait after `step`, at `now_ms` on the io clock:
/// the backoff of a `Retry`, cleared for any other outcome, so the next
/// checkpoint carries it. Output: the wait of a `Retry`, else `None`.
fn note_retry(run: &mut AgentRun, step: &StepOutcome, now_ms: i64) -> Option<Duration> {
    let StepOutcome::Retry { retry_after_ms, .. } = step else {
        run.set_retry_at_ms(None);
        return None;
    };
    assert!(run.retries() > 0, "a retry step is counted");
    let wait = retry_delay(run.retries() - 1, *retry_after_ms);
    let wait_ms = i64::try_from(wait.as_millis()).expect("a retry wait is capped");
    run.set_retry_at_ms(Some(now_ms.saturating_add(wait_ms)));
    Some(wait)
}

/// Returns how much of the retry wait saved on `run` is left at `now_ms`,
/// capped at the longest retry wait so a skewed clock cannot stall a run.
/// Output: zero when no wait is saved or it has passed.
fn retry_left(run: &AgentRun, now_ms: i64) -> Duration {
    let left = run
        .retry_at_ms()
        .map_or(0, |at_ms| at_ms.saturating_sub(now_ms))
        .clamp(0, i64::try_from(MAX_RETRY_MS).expect("the cap fits"));
    let left = Duration::from_millis(u64::try_from(left).expect("left is clamped to 0 or more"));
    assert!(left <= Duration::from_millis(MAX_RETRY_MS));
    left
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn retry_delay_backs_off_and_caps() {
        assert_eq!(retry_delay(0, None), Duration::from_millis(500));
        assert_eq!(retry_delay(2, None), Duration::from_millis(2000));
        assert_eq!(retry_delay(20, None), Duration::from_millis(30_000));
        assert_eq!(retry_delay(0, Some(7)), Duration::from_millis(7));
        assert_eq!(retry_delay(0, Some(90_000)), Duration::from_millis(30_000));
    }
}