troupekit-local 0.4.0

On-device models for the Troupekit LLM agent framework: the LocalModel trait, model catalog and llama.cpp.
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
use crate::error::LocalError;
use crate::model::{ChatMessage, ChatRole, Flow, GenParams, GenStop, Generation, LocalModel};
use crate::reply::{after_think, answer_of, opens_think, parse_reply, unclosed_think};
use crate::tools::{request_grammar, turn_prompt, ToolMode};
use async_trait::async_trait;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use troupekit_core::error::{ProviderError, ProviderErrorKind};
use troupekit_core::event::Usage;
use troupekit_core::message::{ContentPart, Message, Role};
use troupekit_providers::request::{CompletionRequest, CompletionResponse, Delta, StopReason};
use troupekit_providers::Model;

const TOOL_RESPONSE_CLOSE: &str = "</tool_response>";

/// Settings of a `LocalChat`: tool mode, the temperature used when a
/// request has none, the sampling seed, whether end of text is banned
/// and an optional minimum confidence. Defaults are plan rows S18 to S22.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub struct LocalChatSettings {
    tool_mode: ToolMode,
    default_temperature: f64,
    seed: u32,
    ban_eos: bool,
    min_confidence: Option<f64>,
}

impl Default for LocalChatSettings {
    fn default() -> Self {
        Self {
            tool_mode: ToolMode::Auto,
            default_temperature: 0.7,
            seed: 0x5452_4B54,
            ban_eos: false,
            min_confidence: None,
        }
    }
}

impl LocalChatSettings {
    /// Sets whether the model may answer in text when tools are offered.
    /// `Required` asks for exactly one tool call.
    /// Default `Auto`.
    pub fn with_tool_mode(mut self, tool_mode: ToolMode) -> Self {
        self.tool_mode = tool_mode;
        self
    }

    /// Sets the temperature used when a request has none (0 to 2).
    /// Values outside the range are clamped.
    /// Default 0.7.
    pub fn with_default_temperature(mut self, temperature: f64) -> Self {
        self.default_temperature = if temperature.is_finite() {
            temperature.clamp(0.0, 2.0)
        } else {
            0.7
        };
        self
    }

    /// Sets the sampling seed, so runs repeat for the same input.
    /// Input: any u32.
    /// Default `0x5452_4B54`.
    pub fn with_seed(mut self, seed: u32) -> Self {
        self.seed = seed;
        self
    }

    /// Bans end of text, so generation runs to `max_tokens`.
    /// Only for fixed-length runs such as benchmarks and kill tests.
    /// Default false.
    pub fn with_ban_eos(mut self, ban_eos: bool) -> Self {
        self.ban_eos = ban_eos;
        self
    }

    /// Sets the minimum confidence (geometric mean token probability,
    /// 0 to 1) below which a call fails with a `Server` error a router
    /// may fall back on. While set, a streamed reply is held and sent only
    /// after it passes. Default `None` (off: one softmax per token).
    pub fn with_min_confidence(mut self, min_confidence: Option<f64>) -> Self {
        self.min_confidence = min_confidence
            .filter(|c| c.is_finite())
            .map(|c| c.clamp(0.0, 1.0));
        self
    }

    /// Returns the tool mode.
    /// Input: none.
    /// Default `Auto`.
    pub fn tool_mode(&self) -> ToolMode {
        self.tool_mode
    }

    /// Returns the temperature used when a request has none.
    /// Input: none.
    /// Default 0.7.
    pub fn default_temperature(&self) -> f64 {
        self.default_temperature
    }

    /// Returns the sampling seed.
    /// Input: none.
    /// Default `0x5452_4B54`.
    pub fn seed(&self) -> u32 {
        self.seed
    }

    /// Returns whether end of text is banned.
    /// Input: none.
    /// Default false.
    pub fn ban_eos(&self) -> bool {
        self.ban_eos
    }

    /// Returns the minimum confidence, or `None` when off.
    /// Input: none.
    /// Default `None`.
    pub fn min_confidence(&self) -> Option<f64> {
        self.min_confidence
    }
}

/// A local model behind the `Model` interface, so the same agent runs
/// on device. Renders requests through the model's chat template,
/// generates on a blocking thread and cancels when the future is dropped.
pub struct LocalChat {
    model: Arc<dyn LocalModel>,
    id: String,
    settings: LocalChatSettings,
}

impl std::fmt::Debug for LocalChat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LocalChat")
            .field("id", &self.id)
            .field("settings", &self.settings)
            .finish()
    }
}

struct CancelOnDrop(Arc<AtomicBool>);

impl Drop for CancelOnDrop {
    fn drop(&mut self) {
        self.0.store(true, Ordering::SeqCst);
    }
}

impl LocalChat {
    /// Wraps a loaded local model with default settings.
    /// Input: the model and the id `Model::id` returns.
    /// Output: the chat model.
    pub fn new(model: Arc<dyn LocalModel>, id: impl Into<String>) -> Self {
        Self {
            model,
            id: id.into(),
            settings: LocalChatSettings::default(),
        }
    }

    /// Replaces the settings.
    /// Input: the settings.
    /// Output: the chat model.
    pub fn with_settings(mut self, settings: LocalChatSettings) -> Self {
        self.settings = settings;
        self
    }

    /// Returns the settings.
    /// Input: none.
    /// Output: the settings.
    pub fn settings(&self) -> &LocalChatSettings {
        &self.settings
    }

    fn render(&self, req: &CompletionRequest) -> Result<Vec<ChatMessage>, ProviderError> {
        let mut system = req.system_text().unwrap_or_default();
        let tools = turn_prompt(
            &req.tools,
            self.settings.tool_mode,
            req.output_schema.as_ref(),
        );
        if !tools.is_empty() {
            if !system.is_empty() {
                system.push_str("\n\n");
            }
            system.push_str(&tools);
        }
        let mut out = Vec::new();
        if !system.is_empty() {
            out.push(ChatMessage::new(ChatRole::System, system));
        }
        for message in &req.messages {
            let role = match message.role {
                Role::System => continue,
                Role::User => ChatRole::User,
                Role::Assistant => ChatRole::Assistant,
                Role::Tool => ChatRole::User,
            };
            let mut lines = Vec::new();
            for part in &message.parts {
                match part {
                    ContentPart::Text { text } => lines.push(text.clone()),
                    ContentPart::ToolCall {
                        name, arguments, ..
                    } => lines.push(
                        serde_json::json!({ "tool": name, "arguments": arguments }).to_string(),
                    ),
                    ContentPart::ToolResult {
                        content, is_error, ..
                    } => lines.push(tool_response(content, *is_error)),
                    ContentPart::Image { .. } => {
                        return Err(ProviderError::new(
                            ProviderErrorKind::BadRequest,
                            "local models do not take images",
                        ))
                    }
                    ContentPart::Hosted { .. } => {}
                }
            }
            if !lines.is_empty() {
                out.push(ChatMessage::new(role, lines.join("\n")));
            }
        }
        Ok(out)
    }

    async fn run(
        &self,
        req: &CompletionRequest,
        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
    ) -> Result<CompletionResponse, ProviderError> {
        req.validate()?;
        let req = req.sendable(false)?;
        let grammar = request_grammar(
            &req.tools,
            self.settings.tool_mode,
            req.output_schema.as_ref(),
        )
        .map_err(server)?;
        let messages = self.render(&req)?;
        for message in &messages {
            self.refuse_control_tokens(message.content())?;
        }
        let rendered = self.model.render_chat(&messages, true).map_err(server)?;
        let prompt = self.model.tokenize(&rendered, true).map_err(server)?;
        let limit = self.model.info().context_length();
        if prompt.len() >= limit {
            return Err(server(LocalError::ContextFull {
                needed: prompt.len() + 1,
                limit,
            }));
        }
        let max_tokens = (req.max_tokens as usize).min(limit - prompt.len());
        assert!(max_tokens > 0 && prompt.len() + max_tokens <= limit);
        let cancel = Arc::new(AtomicBool::new(false));
        let _guard = CancelOnDrop(cancel.clone());
        let temperature = req.temperature.unwrap_or(self.settings.default_temperature);
        let params = GenParams::default()
            .with_max_tokens(max_tokens)
            .with_temperature(temperature as f32)
            .with_seed(self.settings.seed)
            .with_ban_eos(self.settings.ban_eos)
            .with_grammar(grammar)
            .with_confidence(self.settings.min_confidence.is_some())
            .with_cancel(Some(cancel));
        let prompt_tokens = prompt.len();
        let require_call = self.settings.tool_mode == ToolMode::Required && !req.tools.is_empty();
        let hold_all = require_call || self.settings.min_confidence.is_some();
        let mut gate = TextGate::new(!req.tools.is_empty(), hold_all);
        let generation = self.generate(prompt, params, &mut gate, on_delta).await?;
        self.check_confidence(&generation)?;
        check_answered(&generation, max_tokens, !req.tools.is_empty())?;
        let call_id = next_call_id(&req.messages);
        let parts: Vec<ContentPart> = parse_reply(generation.text(), &req.tools)
            .map_err(server)?
            .into_iter()
            .map(|p| match p {
                ContentPart::ToolCall {
                    name, arguments, ..
                } => ContentPart::ToolCall {
                    id: call_id.clone(),
                    name,
                    arguments,
                },
                other => other,
            })
            .collect();
        let call = parts.iter().find_map(|p| match p {
            ContentPart::ToolCall {
                id,
                name,
                arguments,
            } => Some((id.clone(), name.clone(), arguments.to_string())),
            _ => None,
        });
        if require_call && call.is_none() {
            return Err(ProviderError::new(
                ProviderErrorKind::Server,
                "local model answered in text, but tool_mode Required needs a tool call",
            ));
        }
        match &call {
            Some((id, name, json)) => {
                on_delta(&Delta::ToolCallStarted {
                    index: 0,
                    id: id.clone(),
                    name: name.clone(),
                });
                on_delta(&Delta::ToolCallArgs {
                    index: 0,
                    json: json.clone(),
                });
            }
            None => {
                if let Some(text) = gate.flush() {
                    on_delta(&Delta::TextDelta { text });
                }
            }
        }
        let stop = match (call.is_some(), generation.stop()) {
            (true, _) => StopReason::ToolUse,
            (false, GenStop::MaxTokens) => StopReason::MaxTokens,
            (false, GenStop::Cancelled) => StopReason::Other("cancelled".into()),
            (false, _) => StopReason::EndTurn,
        };
        let usage = Usage {
            input_tokens: prompt_tokens as u64,
            output_tokens: generation.tokens() as u64,
            cost_usd_micros: 0,
        };
        on_delta(&Delta::Usage {
            input_tokens: Some(usage.input_tokens),
            output_tokens: Some(usage.output_tokens),
        });
        on_delta(&Delta::Stop {
            reason: stop.clone(),
        });
        let message = Message::new(Role::Assistant, parts)
            .map_err(|e| ProviderError::new(ProviderErrorKind::Server, e.to_string()))?;
        Ok(CompletionResponse {
            message,
            usage,
            stop,
        })
    }

    fn refuse_control_tokens(&self, content: &str) -> Result<(), ProviderError> {
        let plain = self.model.tokenize(content, false).map_err(server)?;
        let special = self.model.tokenize(content, true).map_err(server)?;
        if plain != special {
            return Err(ProviderError::new(
                ProviderErrorKind::BadRequest,
                "message text holds chat template control tokens",
            ));
        }
        Ok(())
    }

    fn check_confidence(&self, generation: &Generation) -> Result<(), ProviderError> {
        let (Some(min), Some(lp)) = (self.settings.min_confidence, generation.mean_logprob())
        else {
            return Ok(());
        };
        let confidence = lp.exp();
        assert!((0.0..=1.0).contains(&confidence));
        if confidence < min {
            return Err(ProviderError::new(
                ProviderErrorKind::Server,
                format!("local confidence {confidence:.3} below {min}"),
            ));
        }
        Ok(())
    }

    async fn generate(
        &self,
        prompt: Vec<u32>,
        params: GenParams,
        gate: &mut TextGate,
        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
    ) -> Result<Generation, ProviderError> {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<String>();
        let model = self.model.clone();
        let ctx = troupekit_trace::current();
        let handle = tokio::task::spawn_blocking(move || {
            let mut on_token = |piece: &str| {
                if tx.send(piece.to_string()).is_err() {
                    Flow::Stop
                } else {
                    Flow::Continue
                }
            };
            match ctx {
                Some(ctx) => ctx.enter(|| model.generate(&prompt, &params, &mut on_token)),
                None => model.generate(&prompt, &params, &mut on_token),
            }
        });
        while let Some(piece) = rx.recv().await {
            if let Some(text) = gate.push(&piece) {
                on_delta(&Delta::TextDelta { text });
            }
        }
        handle
            .await
            .map_err(|e| {
                ProviderError::new(
                    ProviderErrorKind::Server,
                    format!("local generation stopped: {e}"),
                )
            })?
            .map_err(server)
    }
}

/// Names the next local tool call. Input: the request history. Output:
/// `local-N` with N one above the highest `local-N` call id kept in the
/// history (1 when there is none), so a history that dropped earlier
/// calls still gets an id no kept call uses.
fn next_call_id(messages: &[Message]) -> String {
    let highest = messages
        .iter()
        .flat_map(|m| &m.parts)
        .filter_map(|p| match p {
            ContentPart::ToolCall { id, .. } => id.strip_prefix("local-")?.parse::<u64>().ok(),
            _ => None,
        })
        .max()
        .unwrap_or(0);
    format!("local-{}", highest.saturating_add(1))
}

/// Renders one tool result the way Qwen-style chat templates expect it in
/// a user turn: `<tool_response>\n...\n</tool_response>`, which the
/// template reads as a tool turn and not as a new question. A failed
/// call's content starts with `error: `; a closing tag inside the content
/// is escaped so a tool cannot end the block early. Output: the block.
fn tool_response(content: &str, is_error: bool) -> String {
    let body = content.replace(TOOL_RESPONSE_CLOSE, "<\\/tool_response>");
    assert!(!body.contains(TOOL_RESPONSE_CLOSE));
    let prefix = if is_error { "error: " } else { "" };
    format!("<tool_response>\n{prefix}{body}\n{TOOL_RESPONSE_CLOSE}")
}

/// Refuses a local reply that holds no answer: one that ends inside its
/// `<think>` block, or one the output cap cut before any answer text or
/// inside a tool call. A seeded local run would repeat the same cut, so
/// the error is a `Decode`, which no retry repeats. Input: the
/// generation, the cap and whether the turn offered tools.
fn check_answered(
    generation: &Generation,
    max_tokens: usize,
    tools: bool,
) -> Result<(), ProviderError> {
    let text = generation.text();
    let used = generation.tokens();
    let refuse = |what: &str| {
        Err(ProviderError::new(
            ProviderErrorKind::Decode,
            format!(
                "local reply {what} after {used} of {max_tokens} output tokens, so it holds no answer; raise max_tokens"
            ),
        ))
    };
    if unclosed_think(text) {
        return refuse("ended inside its <think> block");
    }
    if generation.stop() != GenStop::MaxTokens {
        return Ok(());
    }
    let answer = answer_of(text).trim_start();
    if answer.is_empty() {
        return refuse("was cut by the output cap before any answer text");
    }
    if tools
        && answer.starts_with('{')
        && serde_json::from_str::<serde_json::Value>(answer.trim_end()).is_err()
    {
        return refuse("was cut by the output cap inside a tool call");
    }
    Ok(())
}

fn server(e: LocalError) -> ProviderError {
    ProviderError::new(ProviderErrorKind::Server, e.to_string())
}

struct TextGate {
    buffer: String,
    state: GateState,
    tools: bool,
}

#[derive(PartialEq)]
enum GateState {
    Deciding,
    Text,
    Held,
}

impl TextGate {
    fn new(tools: bool, hold_all: bool) -> Self {
        Self {
            buffer: String::new(),
            tools,
            state: match hold_all {
                true => GateState::Held,
                false => GateState::Deciding,
            },
        }
    }

    fn push(&mut self, piece: &str) -> Option<String> {
        match self.state {
            GateState::Text => (!piece.is_empty()).then(|| piece.to_string()),
            GateState::Held => {
                self.buffer.push_str(piece);
                None
            }
            GateState::Deciding => {
                self.buffer.push_str(piece);
                let head = self.buffer.trim_start();
                let answer = after_think(head);
                if answer.is_none() && opens_think(head) {
                    return None;
                }
                match answer.unwrap_or(head).chars().next() {
                    None => None,
                    Some('{') if self.tools => {
                        self.state = GateState::Held;
                        None
                    }
                    Some(_) => {
                        let out = answer.map(str::to_string);
                        self.state = GateState::Text;
                        let buffered = std::mem::take(&mut self.buffer);
                        Some(out.unwrap_or(buffered))
                    }
                }
            }
        }
    }

    fn flush(&mut self) -> Option<String> {
        let held = self.state != GateState::Text;
        self.state = GateState::Text;
        let text = std::mem::take(&mut self.buffer);
        let text = answer_of(&text).to_string();
        (held && !text.is_empty()).then_some(text)
    }
}

#[async_trait]
impl Model for LocalChat {
    fn id(&self) -> &str {
        &self.id
    }

    async fn complete(&self, req: &CompletionRequest) -> Result<CompletionResponse, ProviderError> {
        self.run(req, &mut |_| {}).await
    }

    async fn stream(
        &self,
        req: &CompletionRequest,
        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
    ) -> Result<CompletionResponse, ProviderError> {
        self.run(req, on_delta).await
    }
}