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
use crate::common::*;
use async_trait::async_trait;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use troupekit::{Agent, KitError, Progress, Storage};
use troupekit_core::error::{CoreError, ProviderError, ProviderErrorKind};
use troupekit_core::ids::RunId;
use troupekit_core::inmem::InMemCheckpoints;
use troupekit_core::store::{Checkpoint, CheckpointStore};
use troupekit_graph::testing::{text_reply, FnModel};

const LONG: Duration = Duration::from_secs(60);

#[derive(Default)]
struct Recording {
    inner: InMemCheckpoints,
    steps: Mutex<Vec<u64>>,
}

#[async_trait]
impl CheckpointStore for Recording {
    async fn save(&self, cp: Checkpoint) -> Result<(), CoreError> {
        let step = cp.step;
        self.inner.save(cp).await?;
        self.steps.lock().unwrap().push(step);
        Ok(())
    }

    async fn latest(&self, run_id: RunId) -> Result<Option<Checkpoint>, CoreError> {
        self.inner.latest(run_id).await
    }
}

fn counting_model() -> Arc<FnModel> {
    Arc::new(FnModel::new("fake/m", |_req| text_reply("counted", 10)))
}

#[tokio::test]
async fn start_returns_id_before_any_model_call() {
    let model = counting_model();
    let store = Arc::new(InMemCheckpoints::default());
    let built = Agent::new("counter")
        .instructions("Answer.")
        .model("fake/m")
        .model_client(model.clone())
        .checkpoints(Storage::custom(store.clone()))
        .build()
        .await
        .unwrap();
    let run_id = built.start("hello").await.unwrap();
    assert_eq!(model.calls(), 0);
    assert_eq!(store.latest(run_id).await.unwrap().unwrap().step, 0);
    assert_eq!(built.resume(run_id).await.unwrap(), "counted");
    assert_eq!(model.calls(), 1);
}

#[tokio::test]
async fn start_needs_durable_storage() {
    let built = greeter().build().await.unwrap();
    let err = built.start("hello").await.unwrap_err();
    assert!(matches!(err, KitError::Config { .. }), "{err:?}");
    assert_eq!(
        err.to_string(),
        "agent `greeter`: start needs Storage::sqlite(..) or Storage::custom(..) checkpoints"
    );
    let err = greeter().start("hello").await.unwrap_err();
    assert!(matches!(err, KitError::Config { .. }), "{err:?}");
}

#[cfg(feature = "sqlite")]
#[tokio::test]
async fn started_run_resumes_in_new_process_shape() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("runs.db");
    let expected = greeter().run("I am Ada").await.unwrap();
    let (first, run_id) = greeter()
        .checkpoints(Storage::sqlite(&path))
        .start("I am Ada")
        .await
        .unwrap();
    drop(first);
    let second = greeter()
        .checkpoints(Storage::sqlite(&path))
        .build()
        .await
        .unwrap();
    assert_eq!(second.resume(run_id).await.unwrap(), expected);
}

#[tokio::test]
async fn resume_for_zero_budget_is_pending() {
    let model = counting_model();
    let store = Arc::new(Recording::default());
    let built = Agent::new("counter")
        .instructions("Answer.")
        .model("fake/m")
        .model_client(model.clone())
        .checkpoints(Storage::custom(store.clone()))
        .build()
        .await
        .unwrap();
    let run_id = built.start("hello").await.unwrap();
    let progress = built.resume_for(run_id, Duration::ZERO).await.unwrap();
    assert_eq!(progress, Progress::Pending { run_id });
    assert_eq!(*store.steps.lock().unwrap(), vec![0]);
    assert_eq!(model.calls(), 0);
}

#[tokio::test]
async fn resume_for_large_budget_is_done() {
    let built = greeter()
        .checkpoints(Storage::custom(Arc::new(InMemCheckpoints::default())))
        .build()
        .await
        .unwrap();
    let run_id = built.start("I am Ada").await.unwrap();
    let progress = built.resume_for(run_id, LONG).await.unwrap();
    assert_eq!(progress, Progress::Done("Hello! You said: I am Ada".into()));
    let again = built.resume_for(run_id, Duration::ZERO).await.unwrap();
    assert_eq!(again, Progress::Done("Hello! You said: I am Ada".into()));
}

#[tokio::test]
async fn resume_for_saves_after_every_step() {
    let store = Arc::new(Recording::default());
    let built = Agent::new("calc")
        .instructions("Use the add tool.")
        .model("fake/m")
        .model_client(calc_model())
        .tool(add_tool())
        .checkpoints(Storage::custom(store.clone()))
        .build()
        .await
        .unwrap();
    let run_id = built.start("What is 2 + 40?").await.unwrap();
    let progress = built.resume_for(run_id, LONG).await.unwrap();
    assert_eq!(progress, Progress::Done("The sum is 42".into()));
    let steps = store.steps.lock().unwrap().clone();
    assert!(steps.len() >= 3, "{steps:?}");
    let expected: Vec<u64> = (0..steps.len() as u64).collect();
    assert_eq!(steps, expected);
}

#[test]
fn defaults_are_the_safe_values() {
    assert_eq!(troupekit::MAX_STEPS_PER_WINDOW, 10_000);
    assert_eq!(troupekit::MAX_PERSONA_BYTES, 1024 * 1024);
}

fn rate_limited(retry_after_ms: u64) -> Arc<FnModel> {
    Arc::new(FnModel::new("fake/m", move |_req| {
        Err(
            ProviderError::new(ProviderErrorKind::RateLimited, "slow down")
                .with_retry_after(retry_after_ms),
        )
    }))
}

#[tokio::test]
async fn resume_for_keeps_the_retry_wait_across_windows() {
    let model = rate_limited(20_000);
    let built = Agent::new("limited")
        .instructions("Answer.")
        .model("fake/m")
        .model_client(model.clone())
        .retries(5)
        .checkpoints(Storage::custom(Arc::new(InMemCheckpoints::default())))
        .build()
        .await
        .unwrap();
    let run_id = built.start("hello").await.unwrap();
    for _ in 0..3 {
        let progress = built
            .resume_for(run_id, Duration::from_millis(50))
            .await
            .unwrap();
        assert_eq!(progress, Progress::Pending { run_id });
    }
    assert_eq!(model.calls(), 1, "a saved retry wait is not skipped");
}

#[tokio::test]
async fn retry_cap_holds_across_resume_for_windows() {
    let model = rate_limited(150);
    let built = Agent::new("limited")
        .instructions("Answer.")
        .model("fake/m")
        .model_client(model.clone())
        .retries(2)
        .checkpoints(Storage::custom(Arc::new(InMemCheckpoints::default())))
        .build()
        .await
        .unwrap();
    let run_id = built.start("hello").await.unwrap();
    let window = Duration::from_millis(100);
    for _ in 0..2 {
        let progress = built.resume_for(run_id, window).await.unwrap();
        assert_eq!(progress, Progress::Pending { run_id });
        tokio::time::sleep(Duration::from_millis(200)).await;
    }
    let err = built.resume_for(run_id, window).await.unwrap_err();
    assert!(
        matches!(err, KitError::Retries { attempts: 2, .. }),
        "{err:?}"
    );
    assert_eq!(model.calls(), 3);
}

#[tokio::test]
async fn resume_keeps_retries_counted_by_resume_for() {
    let model = rate_limited(300);
    let built = Agent::new("limited")
        .instructions("Answer.")
        .model("fake/m")
        .model_client(model.clone())
        .retries(1)
        .checkpoints(Storage::custom(Arc::new(InMemCheckpoints::default())))
        .build()
        .await
        .unwrap();
    let run_id = built.start("hello").await.unwrap();
    let progress = built
        .resume_for(run_id, Duration::from_millis(100))
        .await
        .unwrap();
    assert_eq!(progress, Progress::Pending { run_id });
    let waited = std::time::Instant::now();
    let err = built.resume(run_id).await.unwrap_err();
    assert!(
        waited.elapsed() >= Duration::from_millis(150),
        "resume waits out the saved retry wait"
    );
    assert!(
        matches!(err, KitError::Retries { attempts: 1, .. }),
        "{err:?}"
    );
    assert_eq!(model.calls(), 2);
}

#[tokio::test]
async fn exhausted_checkpoint_is_refused_before_another_step() {
    let failures = Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let seen = failures.clone();
    let model = Arc::new(FnModel::new("fake/m", move |_req| {
        if seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2 {
            return Err(
                ProviderError::new(ProviderErrorKind::RateLimited, "slow down").with_retry_after(1),
            );
        }
        text_reply("late", 10)
    }));
    let built = Agent::new("limited")
        .instructions("Answer.")
        .model("fake/m")
        .model_client(model.clone())
        .retries(1)
        .checkpoints(Storage::custom(Arc::new(InMemCheckpoints::default())))
        .build()
        .await
        .unwrap();
    let run_id = built.start("hello").await.unwrap();
    let err = built.resume_for(run_id, LONG).await.unwrap_err();
    assert!(
        matches!(err, KitError::Retries { attempts: 1, .. }),
        "{err:?}"
    );
    assert_eq!(model.calls(), 2);
    let err = built.resume_for(run_id, LONG).await.unwrap_err();
    assert!(
        matches!(err, KitError::Retries { attempts: 1, .. }),
        "{err:?}"
    );
    let err = built.resume(run_id).await.unwrap_err();
    assert!(
        matches!(err, KitError::Retries { attempts: 1, .. }),
        "{err:?}"
    );
    assert_eq!(model.calls(), 2);
}

#[derive(Default)]
struct FailingSaves {
    seen: Mutex<Vec<RunId>>,
}

#[async_trait]
impl CheckpointStore for FailingSaves {
    async fn save(&self, cp: Checkpoint) -> Result<(), CoreError> {
        self.seen.lock().unwrap().push(cp.run_id);
        Err(CoreError::InvalidMessage("disk full".into()))
    }

    async fn latest(&self, _run_id: RunId) -> Result<Option<Checkpoint>, CoreError> {
        Ok(None)
    }
}

#[tokio::test]
async fn save_failure_during_run_keeps_the_run_id() {
    let store = Arc::new(FailingSaves::default());
    let built = Agent::new("saver")
        .instructions("Answer.")
        .model("fake/m")
        .model_client(counting_model())
        .checkpoints(Storage::custom(store.clone()))
        .build()
        .await
        .unwrap();
    let err = built.run("hello").await.unwrap_err();
    assert_in_run(err, &store);
    let err = built.run_with("hello").await.unwrap_err();
    assert_in_run(err, &store);
}

fn assert_in_run(err: KitError, store: &FailingSaves) {
    let seen = *store.seen.lock().unwrap().last().unwrap();
    match err {
        KitError::InRun { run_id, source } => {
            assert_eq!(run_id, seen);
            assert!(!matches!(*source, KitError::InRun { .. }), "{source:?}");
        }
        other => panic!("expected InRun, got {other:?}"),
    }
}

fn user_capped() -> (
    Arc<troupekit_agent::InMemoryLedger>,
    troupekit_agent::Limits,
) {
    let ledger = Arc::new(troupekit_agent::InMemoryLedger::default());
    let limits = troupekit_agent::Limits {
        user: Some(troupekit_agent::PeriodLimit {
            key: "user-1".into(),
            max_usd_micros: 10,
        }),
        ..Default::default()
    };
    (ledger, limits)
}

async fn spend_past_the_cap(ledger: &troupekit_agent::InMemoryLedger) {
    use troupekit_core::store::UsageLedger;
    let spent = troupekit_core::event::Usage {
        input_tokens: 0,
        output_tokens: 0,
        cost_usd_micros: 1_000,
    };
    ledger.record("user-1", spent).await.unwrap();
}

#[tokio::test]
async fn resume_for_refuses_a_run_of_another_agent() {
    let store = Arc::new(InMemCheckpoints::default());
    let model = counting_model();
    let first = Agent::new("counter")
        .instructions("Answer.")
        .model("fake/m")
        .model_client(model.clone())
        .checkpoints(Storage::custom(store.clone()))
        .build()
        .await
        .unwrap();
    let run_id = first.start("hello").await.unwrap();
    let other = Agent::new("other")
        .instructions("Answer.")
        .model("fake/m")
        .model_client(model.clone())
        .checkpoints(Storage::custom(store.clone()))
        .build()
        .await
        .unwrap();
    let err = other.resume_for(run_id, LONG).await.unwrap_err();
    assert!(matches!(err, KitError::Config { .. }), "{err:?}");
    assert!(
        err.to_string().contains("was started by agent `counter`"),
        "{err}"
    );
    assert_eq!(model.calls(), 0, "a refused run makes no model call");
}

#[tokio::test]
async fn resume_for_applies_the_stricter_current_limits() {
    let store = Arc::new(InMemCheckpoints::default());
    let model = counting_model();
    let loose = Agent::new("counter")
        .instructions("Answer.")
        .model("fake/m")
        .model_client(model.clone())
        .checkpoints(Storage::custom(store.clone()))
        .build()
        .await
        .unwrap();
    let run_id = loose.start("hello").await.unwrap();
    let (ledger, limits) = user_capped();
    spend_past_the_cap(&ledger).await;
    let strict = Agent::new("counter")
        .instructions("Answer.")
        .model("fake/m")
        .model_client(model.clone())
        .limits(limits)
        .ledger(ledger)
        .checkpoints(Storage::custom(store.clone()))
        .build()
        .await
        .unwrap();
    let resumed = strict.resume_for(run_id, LONG).await;
    assert!(
        matches!(resumed, Err(KitError::Paused { .. })),
        "{resumed:?}"
    );
    assert_eq!(
        model.calls(),
        0,
        "a user past the current cap gets no model call"
    );
}

#[tokio::test]
async fn graph_resume_for_applies_the_stricter_current_limits() {
    let store = Arc::new(InMemCheckpoints::default());
    let model = counting_model();
    let node = || {
        Agent::new("drafter")
            .instructions("Draft.")
            .model("fake/m")
            .model_client(model.clone())
    };
    let loose = troupekit::Graph::new("g")
        .agent("draft", node())
        .checkpoints(Storage::custom(store.clone()))
        .build()
        .await
        .unwrap();
    let run_id = loose.start("hi").await.unwrap();
    let (ledger, limits) = user_capped();
    spend_past_the_cap(&ledger).await;
    let strict = troupekit::Graph::new("g")
        .agent("draft", node())
        .limits(limits)
        .ledger(ledger)
        .checkpoints(Storage::custom(store.clone()))
        .build()
        .await
        .unwrap();
    let resumed = strict.resume_for(run_id, LONG).await;
    assert!(
        matches!(resumed, Err(KitError::Paused { .. })),
        "{resumed:?}"
    );
    assert_eq!(
        model.calls(),
        0,
        "a user past the current cap gets no model call"
    );
}

#[test]
fn successful_run_needs_no_timer() {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .build()
        .unwrap();
    let answer = runtime.block_on(async {
        let built = greeter().build().await.unwrap();
        built.run("I am Ada").await.unwrap()
    });
    assert_eq!(answer, "Hello! You said: I am Ada");
}