troupekit-kit 0.3.1

Ergonomic Troupekit API: one builder or one macro per agent, tool and graph, on top of the Troupekit engine.
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
use crate::common::{echo_model, AddArgs};
use serde_json::json;
use std::sync::Arc;
use troupekit::{tool, Agent, Graph, KitError, Storage};
use troupekit_core::event::Usage;
use troupekit_core::message::{ContentPart, Message, Role};
use troupekit_graph::testing::{text_reply, FnModel};
use troupekit_providers::{CompletionResponse, Model, StopReason};

/// Uppercases the draft.
#[tool]
fn upper_draft(draft: String) -> String {
    draft.to_uppercase()
}

/// Trims the input.
#[tool]
fn clean_text(input: String) -> String {
    input.trim().to_string()
}

/// Counts characters of the cleaned text.
#[tool]
fn count_chars(clean: String) -> usize {
    clean.chars().count()
}

/// Shouts the text.
#[tool]
fn shout(text: String) -> String {
    text.to_uppercase()
}

/// Adds one.
#[tool]
fn increment(input: i64) -> i64 {
    input + 1
}

/// Takes optional text.
#[tool]
fn maybe_text(input: Option<String>) -> String {
    input.unwrap_or_default()
}

/// Takes any JSON value.
#[tool]
fn any_value(input: serde_json::Value) -> String {
    input.to_string()
}

fn drafter() -> Agent {
    Agent::new("drafter")
        .instructions("Draft.")
        .model("fake/m")
        .model_client(echo_model())
}

fn shouting_model() -> Arc<dyn Model> {
    Arc::new(FnModel::new("fake/m", |req| {
        let result = req
            .messages
            .iter()
            .flat_map(|m| &m.parts)
            .find_map(|p| match p {
                ContentPart::ToolResult { content, .. } => Some(content.clone()),
                _ => None,
            });
        match result {
            Some(out) => text_reply(&format!("got {out}"), 3),
            None => Ok(CompletionResponse {
                message: Message::new(
                    Role::Assistant,
                    vec![ContentPart::ToolCall {
                        id: "c1".into(),
                        name: "shout".into(),
                        arguments: json!({"text": "hi"}),
                    }],
                )
                .unwrap(),
                usage: Usage {
                    input_tokens: 3,
                    output_tokens: 1,
                    cost_usd_micros: 0,
                },
                stop: StopReason::ToolUse,
            }),
        }
    }))
}

async fn config_error(graph: Graph) -> String {
    match graph.build().await {
        Err(e @ KitError::Config { .. }) => e.to_string(),
        Err(other) => panic!("expected Config, got {other}"),
        Ok(_) => panic!("expected Config, got a built graph"),
    }
}

#[tokio::test]
async fn agent_then_fn_pipeline_runs_offline() {
    let output = Graph::new("pipeline")
        .agent("draft", drafter())
        .step("upper", upper_draft)
        .run("hi")
        .await
        .unwrap();
    let text = output.as_str().unwrap();
    assert!(text.starts_with("HELLO! YOU SAID:"), "{text}");
}

#[tokio::test]
async fn no_edges_means_chain_in_order() {
    let report = Graph::new("lab3")
        .step("clean", clean_text)
        .step("count", count_chars)
        .run_with("  abc ")
        .await
        .unwrap();
    assert_eq!(report.output(), &json!("3"));
    assert_eq!(report.state()["clean"], json!("abc"));
    assert_eq!(report.state()["input"], json!("  abc "));
}

#[tokio::test]
async fn edges_set_the_chain_order() {
    let output = Graph::new("lab3")
        .step("count", count_chars)
        .step("clean", clean_text)
        .edge("clean", "count")
        .run("  ab ")
        .await
        .unwrap();
    assert_eq!(output, json!("2"));
}

#[tokio::test]
async fn branching_edges_are_refused() {
    let text = config_error(
        Graph::new("g")
            .step("clean", clean_text)
            .step("count", count_chars)
            .step("other", count_chars)
            .edge("clean", "count")
            .edge("clean", "other"),
    )
    .await;
    assert_eq!(
        text,
        "agent `graph:g`: node `clean` has two outgoing edges; fan-out needs workflow TOML"
    );
}

#[tokio::test]
async fn fn_args_must_match_feeding_nodes() {
    let text = config_error(
        Graph::new("pipeline")
            .agent("draft", drafter())
            .step("loud", shout),
    )
    .await;
    assert_eq!(
        text,
        "agent `graph:pipeline`: step `loud` takes (text) but is fed by (draft); name its arguments after the nodes that feed it"
    );
}

#[tokio::test]
async fn step_arguments_must_accept_text() {
    let text = config_error(Graph::new("g").step("inc", increment)).await;
    assert_eq!(
        text,
        "agent `graph:g`: step `inc` argument `input` must accept a string; every graph node is fed text"
    );
    assert_eq!(
        Graph::new("g")
            .step("m", maybe_text)
            .run("x")
            .await
            .unwrap(),
        json!("x")
    );
    assert!(Graph::new("g").step("a", any_value).build().await.is_ok());
}

#[tokio::test]
async fn node_with_two_inputs_is_refused() {
    let text = config_error(
        Graph::new("g")
            .step("clean", clean_text)
            .step("other", clean_text)
            .step("count", count_chars)
            .edge("clean", "count")
            .edge("other", "count"),
    )
    .await;
    assert_eq!(
        text,
        "agent `graph:g`: node `count` has two incoming edges; joins need workflow TOML"
    );
}

#[tokio::test]
async fn agent_and_step_sharing_a_tool_see_plain_output() {
    let agent = Agent::new("caller")
        .instructions("Call shout.")
        .model("fake/m")
        .model_client(shouting_model())
        .tool(shout);
    let output = Graph::new("shared")
        .agent("text", agent)
        .step("loud", shout)
        .run("go")
        .await
        .unwrap();
    assert_eq!(output, json!("GOT HI"));
}

#[tokio::test]
async fn same_selector_nodes_keep_their_own_model_clients() {
    let caller = || {
        Agent::new("caller")
            .instructions("Call shout.")
            .model("fake/m")
            .model_client(shouting_model())
            .tool(shout)
    };
    let output = Graph::new("g")
        .agent("draft", drafter())
        .agent("text", caller())
        .run("hi")
        .await
        .unwrap();
    assert_eq!(output, json!("got HI"));
    let output = Graph::new("g")
        .agent("text", caller())
        .agent("draft", drafter())
        .run("hi")
        .await
        .unwrap();
    assert!(
        output.as_str().unwrap().starts_with("Hello! You said:"),
        "{output}"
    );
}

#[tokio::test]
async fn one_agent_name_with_two_model_clients_is_refused() {
    let other = drafter().model_client(shouting_model());
    for (first, second) in [(drafter(), other.clone()), (other, drafter())] {
        let text = config_error(Graph::new("g").agent("draft", first).agent("again", second)).await;
        assert_eq!(
            text,
            "agent `graph:g`: two different agents are named `drafter`"
        );
    }
}

#[tokio::test]
async fn one_agent_name_with_two_prices_is_refused() {
    let model = echo_model();
    let priced = |price| {
        Agent::new("drafter")
            .instructions("Draft.")
            .model("fake/m")
            .model_client(model.clone())
            .price(price)
    };
    let paid = troupekit_providers::Price {
        input_usd_micros_per_mtok: 1_000_000,
        ..troupekit_providers::Price::FREE
    };
    let text = config_error(
        Graph::new("g")
            .agent("draft", priced(troupekit_providers::Price::FREE))
            .agent("again", priced(paid)),
    )
    .await;
    assert_eq!(
        text,
        "agent `graph:g`: two different agents are named `drafter`"
    );
    let built = Graph::new("g")
        .agent("draft", priced(paid))
        .agent("again", priced(paid))
        .build()
        .await;
    assert!(built.is_ok());
}

#[tokio::test]
async fn agent_limits_and_laws_belong_to_the_graph() {
    let limited = drafter().limits(troupekit_agent::Limits {
        run: Some(10),
        ..Default::default()
    });
    let text = config_error(Graph::new("g").agent("draft", limited)).await;
    assert_eq!(
        text,
        "agent `graph:g`: agent node `draft` sets its own limits; set them on the graph"
    );
    let lawful = drafter().law("def main = 1");
    let text = config_error(Graph::new("g").agent("draft", lawful)).await;
    assert_eq!(
        text,
        "agent `graph:g`: agent node `draft` sets its own laws; set them on the graph"
    );
}

#[tokio::test]
async fn graph_ledger_carries_period_spend_and_agent_ledgers_are_refused() {
    use troupekit_core::store::UsageLedger;
    let ledger = Arc::new(troupekit_agent::InMemoryLedger::default());
    ledger
        .record(
            "user-1",
            Usage {
                input_tokens: 0,
                output_tokens: 0,
                cost_usd_micros: 1_000,
            },
        )
        .await
        .unwrap();
    let capped = troupekit_agent::Limits {
        user: Some(troupekit_agent::PeriodLimit {
            key: "user-1".into(),
            max_usd_micros: 10,
        }),
        ..Default::default()
    };
    let result = Graph::new("g")
        .agent("draft", drafter())
        .limits(capped)
        .ledger(ledger.clone())
        .run("hi")
        .await;
    assert!(
        matches!(
            result,
            Err(KitError::Paused { .. } | KitError::Failed { .. })
        ),
        "{result:?}"
    );
    let text = config_error(Graph::new("g").agent("draft", drafter().ledger(ledger))).await;
    assert_eq!(
        text,
        "agent `graph:g`: agent node `draft` sets its own ledger; set it on the graph"
    );
}

#[tokio::test]
async fn finished_run_resumes_to_its_output() {
    let store = Arc::new(troupekit_core::inmem::InMemCheckpoints::default());
    let built = Graph::new("lab3")
        .step("clean", clean_text)
        .checkpoints(Storage::custom(store))
        .build()
        .await
        .unwrap();
    let report = built.run_with(" ab ").await.unwrap();
    assert_eq!(built.resume(report.run_id()).await.unwrap(), json!("ab"));
    assert_eq!(built.resume(report.run_id()).await.unwrap(), json!("ab"));
}

#[tokio::test]
async fn resume_with_a_changed_graph_is_refused() {
    let store = Arc::new(troupekit_core::inmem::InMemCheckpoints::default());
    let first = Graph::new("lab3")
        .step("clean", clean_text)
        .step("count", count_chars)
        .checkpoints(Storage::custom(store.clone()))
        .build()
        .await
        .unwrap();
    let report = first.run_with(" ab ").await.unwrap();
    let renamed = Graph::new("lab3")
        .step("clean", clean_text)
        .step("total", count_chars)
        .checkpoints(Storage::custom(store))
        .build()
        .await
        .unwrap();
    let err = renamed.resume(report.run_id()).await.unwrap_err();
    assert_eq!(
        err.to_string(),
        format!(
            "agent `graph:lab3`: run {} was started by a different workflow; resume it with the graph that started it",
            report.run_id()
        )
    );
}

#[tokio::test]
async fn embedded_agents_take_graph_retries_and_share_one_eval_callback() {
    let built = Graph::new("g")
        .agent("draft", drafter().retries(33))
        .build()
        .await;
    assert!(built.is_ok());
    let check: troupekit_agent::EvalFn = Arc::new(|_, _| Ok(()));
    let base = drafter().eval("always_ok()");
    let checked = base.clone().eval_fn("always_ok", check);
    let built = Graph::new("g")
        .agent("draft", checked.clone())
        .agent("again", checked.clone())
        .build()
        .await;
    assert!(built.is_ok());
    let other: troupekit_agent::EvalFn = Arc::new(|_, _| Ok(()));
    let text = config_error(
        Graph::new("g")
            .agent("draft", checked)
            .agent("again", base.eval_fn("always_ok", other)),
    )
    .await;
    assert_eq!(
        text,
        "agent `graph:g`: eval `always_ok` has two different callbacks; pass one shared EvalFn"
    );
}

#[tokio::test]
async fn cycle_is_refused() {
    let text = config_error(
        Graph::new("g")
            .step("clean", clean_text)
            .step("count", count_chars)
            .edge("clean", "count")
            .edge("count", "clean"),
    )
    .await;
    assert_eq!(text, "agent `graph:g`: edges form a cycle");
}

#[tokio::test]
async fn unknown_or_unchained_nodes_are_refused() {
    let text = config_error(
        Graph::new("g")
            .step("clean", clean_text)
            .edge("clean", "nowhere"),
    )
    .await;
    assert_eq!(text, "agent `graph:g`: edge names unknown node `nowhere`");
    let text = config_error(
        Graph::new("g")
            .step("clean", clean_text)
            .step("count", count_chars)
            .step("lone", clean_text)
            .edge("clean", "count"),
    )
    .await;
    assert_eq!(text, "agent `graph:g`: node `lone` is not on the chain");
}

#[tokio::test]
async fn duplicate_node_id_is_refused() {
    let text = config_error(
        Graph::new("g")
            .step("clean", clean_text)
            .step("clean", clean_text),
    )
    .await;
    assert_eq!(text, "agent `graph:g`: duplicate node id `clean`");
    for reserved in ["input", "end"] {
        let text = config_error(Graph::new("g").step(reserved, clean_text)).await;
        assert_eq!(
            text,
            format!("agent `graph:g`: node id `{reserved}` is reserved")
        );
    }
    let text = config_error(Graph::new("g")).await;
    assert_eq!(text, "agent `graph:g`: needs at least one node");
}

#[tokio::test]
async fn same_tool_twice_is_shared_different_tool_same_name_is_refused() {
    let model = shouting_model();
    let caller = |name: &str| {
        Agent::new(name)
            .instructions("Call shout.")
            .model("fake/m")
            .model_client(model.clone())
            .tool(shout)
    };
    let output = Graph::new("twice")
        .agent("text", caller("first"))
        .agent("again", caller("second"))
        .run("go")
        .await
        .unwrap();
    assert_eq!(output, json!("got HI"));
    let impostor = tool("shout", "Not the same tool.", |a: AddArgs| async move {
        a.a + a.b
    });
    let other = Agent::new("other")
        .instructions("x")
        .model("fake/m")
        .model_client(model.clone())
        .tool(impostor);
    let text = config_error(
        Graph::new("twice")
            .agent("text", caller("first"))
            .agent("again", other),
    )
    .await;
    assert_eq!(
        text,
        "agent `graph:twice`: tool `shout` is registered twice with different specs"
    );
}

#[tokio::test]
async fn equal_spec_tools_with_different_state_are_refused() {
    let model = shouting_model();
    let tenant = |name: &str, offset: i64| {
        let search = tool("search", "Search.", move |a: AddArgs| async move {
            a.a + a.b + offset
        });
        Agent::new(name)
            .instructions("Search.")
            .model("fake/m")
            .model_client(model.clone())
            .tool(search)
    };
    let text = config_error(
        Graph::new("g")
            .agent("text", tenant("first", 1))
            .agent("again", tenant("second", 2)),
    )
    .await;
    assert_eq!(
        text,
        "agent `graph:g`: tool `search` has two different implementations; pass one shared tool to both agents"
    );
    let shared: Arc<dyn troupekit::Tool> =
        Arc::new(tool("search", "Search.", |a: AddArgs| async move { a.a }));
    let caller = |name: &str| {
        Agent::new(name)
            .instructions("Search.")
            .model("fake/m")
            .model_client(model.clone())
            .tool_arc(shared.clone())
    };
    let built = Graph::new("g")
        .agent("text", caller("first"))
        .agent("again", caller("second"))
        .build()
        .await;
    assert!(built.is_ok());
}

#[cfg(feature = "sqlite")]
#[tokio::test]
async fn sqlite_checkpoints_allow_graph_resume() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("graph.db");
    let built = Graph::new("lab3")
        .step("clean", clean_text)
        .step("count", count_chars)
        .checkpoints(Storage::sqlite(&path))
        .build()
        .await
        .unwrap();
    let report = built.run_with(" abcd ").await.unwrap();
    assert_eq!(built.resume(report.run_id()).await.unwrap(), json!("4"));
}

#[tokio::test]
async fn graph_laws_are_stored_and_validated() {
    let built = Graph::new("g")
        .step("clean", clean_text)
        .law("def main = 1")
        .auto_laws(false)
        .build()
        .await
        .unwrap();
    assert_eq!(built.laws().inline(), ["def main = 1".to_string()]);
    assert!(!built.laws().auto());
    let text = config_error(
        Graph::new("g")
            .step("clean", clean_text)
            .laws("missing.bend"),
    )
    .await;
    assert!(
        text.starts_with("agent `graph:g`: law file `missing.bend`"),
        "{text}"
    );
}

#[tokio::test]
async fn defaults_are_the_safe_values() {
    let built = Graph::new("g")
        .step("clean", clean_text)
        .checkpoints(Storage::memory())
        .build()
        .await
        .unwrap();
    assert_eq!(built.workflow().max_retries, 3);
    assert_eq!(built.workflow().max_steps, 200);
    assert!(built.laws().auto());
    let resumed = built.resume(troupekit_core::ids::RunId::new()).await;
    assert!(matches!(resumed, Err(KitError::Config { .. })));
    let text = config_error(Graph::new("g").step("clean", clean_text).retries(51)).await;
    assert_eq!(text, "agent `graph:g`: retries must be at most 50, got 51");
}

#[tokio::test]
async fn workflow_built_by_serializer_not_splicing() {
    let hostile = "a\"\n[[nodes]]\nid = \"x";
    let err = Graph::new("g")
        .step(hostile, clean_text)
        .build()
        .await
        .unwrap_err();
    assert!(matches!(err, KitError::Workflow(_)), "{err}");
    let err = Graph::new("Bad Name")
        .step("clean", clean_text)
        .build()
        .await
        .unwrap_err();
    assert!(matches!(err, KitError::Workflow(_)), "{err}");
}