Local models and routing
A local model runs on the same machine as your program. It needs no network and no API key, it costs nothing per call, and the text never leaves the device. The price is quality: a model small enough for a phone is much weaker than a hosted one. Troupekit lets you use both. With the local and llama features, an agent can run on a GGUF model on the device, and a route policy decides, for each model call, whether the device or the cloud answers.
Choose the on-device model
.local(choice) tells the agent which on-device model to use. You can pass a row id of the built-in local catalog as a &str, a GGUF file as a PathBuf, or a model you already loaded as an Arc<dyn LocalModel>. Loading a file needs the llama feature.
An agent with .local(..) and no .model(..) is local only. If you name a catalog model that is not in the model cache yet, build fails, unless you set .download(true) to let it fetch the file.
The on-device model samples at temperature 0.7 with a fixed seed when a request sets no temperature. Set .local_settings(LocalChatSettings::default().with_default_temperature(0.0)) for greedy replies that repeat for the same input; the same settings also carry the seed, tool mode, end-of-text ban and confidence floor.
The local catalog has one row in 0.4, smollm2-135m-instruct-q2k, a 135M-parameter model for phones with an 8192-token context:
[[model]]
id = "smollm2-135m-instruct-q2k"
url = "https://huggingface.co/bartowski/SmolLM2-135M-Instruct-GGUF/resolve/09816acd5d99df7be770d85ea30822623dab342c/SmolLM2-135M-Instruct-Q2_K.gguf"
sha256 = "741ad12b64088fedc17c33aacb22e48be1972ef36a39f03666dd68bd15614fb9"
bytes = 88202080
ram_bytes = 268435456
context = 8192
class = "phone"
licence = "apache-2.0"
embeddings = false
recommended = false
The model cache
Downloaded models live in one folder, one <id>-<sha256>.gguf file per catalog row. A file is used only when its size and SHA-256 match the catalog, and a download is checked against its SHA-256 before it gets its final name, so a half-finished or tampered download never lands in the cache. A file already in the folder is hashed once per process; later loads skip the hash while the file keeps its device, inode, size and modification time.
The folder is $TROUPEKIT_MODEL_DIR when it is set, else $HOME/.cache/troupekit/models, else %LOCALAPPDATA%\troupekit\models. A mobile app has its own storage rules, so it passes its own folder to ModelCache::new(dir).
A loaded model as the client
You can also load the model yourself and hand it to the agent as its model client. This example loads a GGUF file with llama.cpp, wraps it in LocalChat and builds an agent on it:
#![allow(unused)]
fn main() {
async fn agent(db: &Path, gguf: &Path) -> Result<BuiltAgent, Box<dyn Error>> {
let model = LlamaModel::load(gguf, LlamaSettings::default().with_context(CONTEXT))?;
let settings = LocalChatSettings::default().with_ban_eos(true);
let chat = LocalChat::new(Arc::new(model), "local/test").with_settings(settings);
let store = SqliteStore::open(db).await?;
let said = AtomicBool::new(false);
let sink = CallbackSink::new(move |line| {
let local_start =
line.contains("\"t\":\"start\"") && line.contains("\"name\":\"model.local\"");
if local_start && !said.swap(true, Ordering::SeqCst) {
println!("GENERATING");
std::io::stdout().flush().expect("stdout flushes");
}
});
let built = Agent::new("storyteller")
.instructions("Write a very long story. /no_think")
.model("local/test")
.model_client(Arc::new(chat))
.max_tokens(MAX_TOKENS)
.checkpoints(Storage::custom(Arc::new(store)))
.events(Arc::new(PrintRun(AtomicBool::new(false))))
.trace([Trace::Models])
.trace_to(Arc::new(sink))
.build()
.await?;
Ok(built)
}
}
Route policies
A route policy is the rule that picks a model for each call. Give an agent both a .model(..) and a .local(..), then add .route(policy) or .route_file(path). In the policy, target cloud means the .model(..) selector and target local means the .local(..) model; any other target id fails build. This policy has both targets and tries the cloud first:
#![allow(unused)]
fn main() {
let both = RoutePolicy::parse(
"office.toml",
"name = \"office\"\ndefault = \"cloud\"\n[[target]]\nid = \"local\"\n[[target]]\nid = \"cloud\"\n",
)
.unwrap();
}
Policy keys
| Key | Meaning | Default |
|---|---|---|
name | policy name, [a-z0-9_-] | required |
default | target tried first whenever it is eligible | none |
order | target ids in try order; targets left out follow in file order | file order |
[[target]] id | target id, unique in the policy | required |
[[target]] tiers | task tiers the target serves | none |
[[target]] context_tokens | context window; a request that cannot fit skips the target | no limit |
[network] mode | auto, online or offline | auto |
[network] offline_after_failures | network errors in a row before the probe reports offline, 1 to 1 000 | 1 |
[network] retry_online_after_ms | wait before an offline probe tries online, 1 to 86 400 000 | 30 000 |
[budget] cloud_usd_per_day | daily cap on remote spend; at the cap, remote targets are skipped | no cap |
[device] min_battery_percent | below it, on-device targets are skipped, 0 to 100 | no limit |
[device] max_thermal | nominal, fair, serious or critical; hotter, on-device targets are skipped | no limit |
[fallback] on_error | whether an error moves the request to the next target | true |
A policy holds at most 16 targets and 64 KiB of text. Fallback never switches target after the first streamed delta, because by then part of the answer has already reached the caller.
Whether a target runs on the device is never read from TOML. Your code declares it when it binds a model to the target id, because only the code knows whether a model touches the network.
Private agents
Some data must never leave the device. .private(true) keeps an agent's model requests on the device, even on fallback: the route never plans a cloud target. build also refuses a private agent that would send text to a cloud model another way: one with no on-device model, a cloud knowledge embedder, a judge eval that names a cloud model, or a network tool.
Warning
buildrefusesweb_fetch,web_search, declarative HTTP tools and hosted tools on a private agent. A tool of your own is trusted: a#[tool]fn or atool(..)value is never refused, even when it sends a request. To havebuildrefuse one, implementToolyourself and overrideuses_networkto returntrue, or give a private agent none of your network tools.
Tiers, network and device state
A tier is a label for a kind of task, such as small or large. .tier(name) sends an agent's requests only to targets that list that tier, and a tier that no target serves fails build.
The network and device rules need to know the state of the machine. Your app knows it best, so it can keep a NetworkState handle and pass it with .network(state). Without one, a passive probe infers the network state from network errors. In the same way, .device(state) reads battery and thermal state from a DeviceState handle; without it both are unknown and the device rules are skipped.
Note
Adapters for on-device models are in 0.4, in the bindings:
AppleFoundationModelin the SwiftTroupekitApplelibrary andOnDeviceModelin the Kotlintroupekit-androidlibrary, which loads a LiteRT-LM model file that your app supplies. A Rust program cannot use them.