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
use crate::common::*;
use std::path::PathBuf;
use std::sync::Arc;
use troupekit::{Agent, Graph, KitError};
use troupekit_local::{
    ChatMessage, Flow, GenParams, GenStop, Generation, LocalError, LocalInfo, LocalMetrics,
    LocalModel,
};
use troupekit_providers::route::RoutePolicy;

struct Scripted {
    info: LocalInfo,
    reply: String,
    saw_sampling: std::sync::Mutex<Vec<(f32, u32)>>,
}

impl LocalModel for Scripted {
    fn info(&self) -> &LocalInfo {
        &self.info
    }

    fn tokenize(&self, text: &str, _special: bool) -> Result<Vec<u32>, LocalError> {
        Ok(text.bytes().map(u32::from).collect())
    }

    fn detokenize(&self, tokens: &[u32]) -> Result<String, LocalError> {
        Ok(tokens.iter().map(|t| char::from(*t as u8)).collect())
    }

    fn render_chat(&self, msgs: &[ChatMessage], add: bool) -> Result<String, LocalError> {
        let mut out: String = msgs.iter().map(|m| m.content().to_string()).collect();
        if add {
            out.push_str("<assistant>");
        }
        Ok(out)
    }

    fn generate(
        &self,
        _prompt: &[u32],
        params: &GenParams,
        on_token: &mut dyn FnMut(&str) -> Flow,
    ) -> Result<Generation, LocalError> {
        self.saw_sampling
            .lock()
            .expect("lock")
            .push((params.temperature(), params.seed()));
        on_token(&self.reply);
        Ok(Generation::new(
            self.reply.clone(),
            1,
            GenStop::EndOfText,
            None,
            LocalMetrics::default(),
        ))
    }

    fn score(&self, _tokens: &[u32]) -> Result<f64, LocalError> {
        Ok(0.0)
    }

    fn embed(&self, texts: &[String]) -> Result<Vec<Vec<f32>>, LocalError> {
        let dims = self.info.embedding_dims();
        if dims == 0 {
            return Err(LocalError::Unsupported("embeddings"));
        }
        Ok(texts
            .iter()
            .map(|_| {
                let mut v = vec![0.0; dims];
                v[0] = 1.0;
                v
            })
            .collect())
    }

    fn reset(&self) {}
}

fn on_device(reply: &str, dims: usize) -> Arc<dyn LocalModel> {
    scripted_device(reply, dims)
}

fn scripted_device(reply: &str, dims: usize) -> Arc<Scripted> {
    Arc::new(Scripted {
        info: LocalInfo::new(4_096, 256, dims, true),
        reply: reply.to_string(),
        saw_sampling: std::sync::Mutex::new(Vec::new()),
    })
}

fn cloud_agent(name: &str) -> Agent {
    Agent::new(name)
        .instructions("Answer.")
        .model("openai/gpt-6-luna")
        .api_key(secret("sk-local-test"))
}

async fn config_error(agent: Agent) -> String {
    match agent.build().await {
        Err(err @ KitError::Config { .. }) => err.to_string(),
        Err(other) => panic!("expected a Config error, got {other}"),
        Ok(_) => panic!("expected build to fail"),
    }
}

#[tokio::test]
async fn private_agent_never_calls_cloud_transport() {
    let transport = scripted();
    let text = cloud_agent("private")
        .transport(transport.clone())
        .local(on_device("from the device", 0))
        .private(true)
        .run("hi")
        .await
        .unwrap();
    assert_eq!(text, "from the device");
    assert!(transport.sent().is_empty(), "no request left the device");

    let both = RoutePolicy::parse(
        "office.toml",
        "name = \"office\"\ndefault = \"cloud\"\n[[target]]\nid = \"local\"\n[[target]]\nid = \"cloud\"\n",
    )
    .unwrap();
    let routed = scripted();
    let text = cloud_agent("private")
        .transport(routed.clone())
        .local(on_device("from the device", 0))
        .route(both)
        .private(true)
        .run("hi")
        .await
        .unwrap();
    assert_eq!(text, "from the device");
    assert!(
        routed.sent().is_empty(),
        "the private view skips target cloud"
    );

    let open = scripted();
    let text = cloud_agent("open")
        .transport(open.clone())
        .local(on_device("from the device", 0))
        .run("hi")
        .await
        .unwrap();
    assert_eq!(text, "Hi there");
    assert_eq!(open.sent().len(), 1, "a non-private agent uses .model(..)");
}

#[tokio::test]
async fn private_local_agent_needs_no_cloud_key() {
    let built = Agent::new("keyless")
        .instructions("Answer.")
        .model("openai/gpt-6-luna")
        .api_key_env("TROUPEKIT_TEST_KEY_THAT_IS_NEVER_SET")
        .local(on_device("from the device", 0))
        .private(true)
        .build()
        .await
        .unwrap();
    assert_eq!(built.run("hi").await.unwrap(), "from the device");
    let local_only = Agent::new("solo")
        .instructions("Answer.")
        .local(on_device("solo answer", 0));
    assert_eq!(local_only.run("hi").await.unwrap(), "solo answer");
}

#[cfg(feature = "knowledge")]
#[tokio::test]
async fn local_only_agent_defaults_to_local_embedder() {
    use troupekit::Knowledge;
    let dir = tempfile::tempdir().unwrap();
    let docs = dir.path().join("docs");
    std::fs::create_dir(&docs).unwrap();
    std::fs::write(docs.join("a.md"), "The office opens at nine.").unwrap();
    let knowledge = || Knowledge::dir(&docs).store(dir.path().join("k.db"));
    let solo = |dims: usize| {
        Agent::new("solo")
            .instructions("Answer.")
            .local(on_device("ok", dims))
            .knowledge(knowledge())
    };
    solo(8).build().await.unwrap();
    solo(8).private(true).build().await.unwrap();
    let text = config_error(solo(0)).await;
    assert!(
        text.contains("Knowledge::dir(..).local_embedder("),
        "{text}"
    );

    let marked = cloud_agent("mixed")
        .local(on_device("ok", 0))
        .private(true)
        .knowledge(knowledge().local_embedder(on_device("emb", 8)));
    marked.build().await.unwrap();
    let cloud_default = cloud_agent("mixed")
        .local(on_device("ok", 8))
        .private(true)
        .knowledge(knowledge());
    let text = config_error(cloud_default).await;
    assert!(text.contains("on_device_embedder"), "{text}");
}

#[tokio::test]
async fn local_selector_needs_file_or_download() {
    let dir = tempfile::tempdir().unwrap();
    std::env::set_var("TROUPEKIT_MODEL_DIR", dir.path());
    let agent = Agent::new("solo")
        .instructions("Answer.")
        .model("local/smollm2-135m-instruct-q2k");
    let text = config_error(agent).await;
    assert!(text.contains(".download(true)"), "{text}");
    assert!(text.contains("ModelCache::fetch"), "{text}");
    let unknown = Agent::new("solo")
        .instructions("Answer.")
        .local("no-such-model");
    let text = config_error(unknown).await;
    assert!(text.contains("LocalCatalog::builtin()"), "{text}");
    let twice = Agent::new("solo")
        .instructions("Answer.")
        .model("local/smollm2-135m-instruct-q2k")
        .local(on_device("x", 0));
    let text = config_error(twice).await;
    assert!(text.contains("once"), "{text}");
}

fn toml_persona(model: &str) -> Agent {
    Agent::from_toml(format!(
        "name = \"toml\"\ninstructions = \"Answer.\"\nmodel = \"{model}\"\n"
    ))
}

#[tokio::test]
async fn toml_local_model_is_the_on_device_model() {
    let twice = toml_persona("local/smollm2-135m-instruct-q2k").local(on_device("x", 0));
    let text = config_error(twice).await;
    assert!(text.contains("once"), "{text}");
}

#[cfg(feature = "knowledge")]
#[tokio::test]
async fn toml_local_model_loads_from_the_cache() {
    let dir = tempfile::tempdir().unwrap();
    std::env::set_var("TROUPEKIT_MODEL_DIR", dir.path());
    let text = config_error(toml_persona("local/smollm2-135m-instruct-q2k")).await;
    assert!(text.contains(".download(true)"), "{text}");
}

#[tokio::test]
async fn toml_cloud_model_with_local_keeps_the_cloud() {
    let open = scripted();
    let text = toml_persona("openai/gpt-6-luna")
        .api_key(secret("sk-local-test"))
        .transport(open.clone())
        .local(on_device("from the device", 0))
        .run("hi")
        .await
        .unwrap();
    assert_eq!(text, "Hi there");
    assert_eq!(open.sent().len(), 1, "a TOML cloud model is not dropped");

    let private = scripted();
    let text = toml_persona("openai/gpt-6-luna")
        .api_key(secret("sk-local-test"))
        .transport(private.clone())
        .local(on_device("from the device", 0))
        .private(true)
        .run("hi")
        .await
        .unwrap();
    assert_eq!(text, "from the device");
    assert!(private.sent().is_empty(), "private stays on the device");
}

#[cfg(not(feature = "llama"))]
#[tokio::test]
async fn local_without_llama_feature_names_it() {
    let agent = Agent::new("solo")
        .instructions("Answer.")
        .local(PathBuf::from("model.gguf"));
    let text = config_error(agent).await;
    assert!(text.contains("`llama`"), "{text}");
    assert!(text.contains("model.gguf"), "{text}");
}

#[tokio::test]
async fn empty_name_with_local_file_is_a_config_error() {
    let agent = Agent::new("")
        .instructions("Answer.")
        .local(PathBuf::from("missing.gguf"));
    let text = config_error(agent).await;
    assert!(text.contains("name must be"), "{text}");
}

#[tokio::test]
async fn route_file_binds_local_and_cloud() {
    let dir = tempfile::tempdir().unwrap();
    let path = |name: &str, default: &str| {
        let file = dir.path().join(name);
        std::fs::write(
            &file,
            format!(
                "name = \"office\"\ndefault = \"{default}\"\n\
                 [[target]]\nid = \"local\"\n[[target]]\nid = \"cloud\"\n"
            ),
        )
        .unwrap();
        file
    };
    let agent = |file: PathBuf| {
        Agent::new("routed")
            .instructions("Echo the user.")
            .model("fake/m")
            .model_client(echo_model())
            .local(on_device("from the device", 0))
            .route_file(file)
    };
    let local_first = agent(path("local.toml", "local")).run("hi").await.unwrap();
    assert_eq!(local_first, "from the device");
    let cloud_first = agent(path("cloud.toml", "cloud")).run("hi").await.unwrap();
    assert_eq!(cloud_first, "Hello! You said: hi");

    let solo = Agent::new("solo")
        .instructions("Answer.")
        .local(on_device("x", 0))
        .route_file(path("solo.toml", "local"));
    let text = config_error(solo).await;
    assert!(text.contains("cloud model"), "{text}");
}

#[tokio::test]
async fn routed_run_bills_the_target_that_served() {
    let policy = RoutePolicy::parse(
        "office.toml",
        "name = \"office\"\ndefault = \"local\"\n[[target]]\nid = \"local\"\n[[target]]\nid = \"cloud\"\n",
    )
    .unwrap();
    let paid = troupekit_providers::Price {
        input_usd_micros_per_mtok: 100_000_000,
        output_usd_micros_per_mtok: 100_000_000,
        ..troupekit_providers::Price::FREE
    };
    let out = Agent::new("routed")
        .instructions("Echo the user.")
        .model("fake/m")
        .model_client(echo_model())
        .price(paid)
        .local(on_device("from the device", 0))
        .route(policy)
        .run_with("hi")
        .await
        .unwrap();
    assert_eq!(out.text(), "from the device");
    assert!(
        out.usage().input_tokens > 0,
        "the device reply reports tokens"
    );
    assert_eq!(
        out.usage().cost_usd_micros,
        0,
        "the device served it for free"
    );
}

#[tokio::test]
async fn graph_private_runs_local_nodes() {
    let node = Agent::new("first")
        .instructions("Answer.")
        .model("fake/m")
        .model_client(echo_model())
        .local(on_device("from the device", 0));
    let text = Graph::new("pipe")
        .agent("first", node)
        .private(true)
        .run("hi")
        .await
        .unwrap();
    assert_eq!(text, "from the device");
}

#[tokio::test]
async fn graph_nodes_share_one_local_agent() {
    let agent = Agent::new("helper")
        .instructions("Answer.")
        .local(on_device("from the device", 0));
    let text = Graph::new("pipe")
        .agent("first", agent.clone())
        .agent("second", agent)
        .edge("first", "second")
        .run("hi")
        .await
        .unwrap();
    assert_eq!(text, "from the device");
}

#[tokio::test]
async fn private_route_needs_no_cloud_key() {
    let both = RoutePolicy::parse(
        "office.toml",
        "name = \"office\"\ndefault = \"cloud\"\n[[target]]\nid = \"local\"\n[[target]]\nid = \"cloud\"\n",
    )
    .unwrap();
    let keyless = || {
        Agent::new("keyless")
            .instructions("Answer.")
            .model("openai/gpt-6-luna")
            .api_key_env("TROUPEKIT_TEST_KEY_THAT_IS_NEVER_SET")
            .route(both.clone())
    };
    let text = keyless()
        .local(on_device("from the device", 0))
        .private(true)
        .run("hi")
        .await
        .unwrap();
    assert_eq!(text, "from the device");
    let text = config_error(keyless().private(true)).await;
    assert!(text.contains(".local("), "{text}");
    let err = keyless()
        .local(on_device("from the device", 0))
        .build()
        .await
        .unwrap_err();
    assert!(matches!(err, KitError::MissingKey { .. }), "{err}");
}

#[tokio::test]
async fn local_settings_reach_the_on_device_sampler() {
    let device = scripted_device("from the device", 0);
    let greedy = troupekit_local::LocalChatSettings::default()
        .with_default_temperature(0.0)
        .with_seed(42);
    let text = Agent::new("solo")
        .instructions("Answer.")
        .local(device.clone() as Arc<dyn LocalModel>)
        .local_settings(greedy)
        .run("hi")
        .await
        .unwrap();
    assert_eq!(text, "from the device");
    let saw = device.saw_sampling.lock().expect("lock").clone();
    assert!(!saw.is_empty(), "the device model was called");
    assert!(saw.iter().all(|s| *s == (0.0, 42)), "{saw:?}");
}