Skip to main content

troupekit_local/
chat.rs

1use crate::error::LocalError;
2use crate::model::{ChatMessage, ChatRole, Flow, GenParams, GenStop, Generation, LocalModel};
3use crate::reply::{after_think, answer_of, opens_think, parse_reply, unclosed_think};
4use crate::tools::{request_grammar, turn_prompt, ToolMode};
5use async_trait::async_trait;
6use std::sync::atomic::{AtomicBool, Ordering};
7use std::sync::Arc;
8use troupekit_core::error::{ProviderError, ProviderErrorKind};
9use troupekit_core::event::Usage;
10use troupekit_core::message::{ContentPart, Message, Role};
11use troupekit_providers::request::{CompletionRequest, CompletionResponse, Delta, StopReason};
12use troupekit_providers::Model;
13
14const TOOL_RESPONSE_CLOSE: &str = "</tool_response>";
15
16/// Settings of a `LocalChat`: tool mode, the temperature used when a
17/// request has none, the sampling seed, whether end of text is banned
18/// and an optional minimum confidence. Defaults are plan rows S18 to S22.
19#[non_exhaustive]
20#[derive(Debug, Clone, PartialEq)]
21pub struct LocalChatSettings {
22    tool_mode: ToolMode,
23    default_temperature: f64,
24    seed: u32,
25    ban_eos: bool,
26    min_confidence: Option<f64>,
27}
28
29impl Default for LocalChatSettings {
30    fn default() -> Self {
31        Self {
32            tool_mode: ToolMode::Auto,
33            default_temperature: 0.7,
34            seed: 0x5452_4B54,
35            ban_eos: false,
36            min_confidence: None,
37        }
38    }
39}
40
41impl LocalChatSettings {
42    /// Sets whether the model may answer in text when tools are offered.
43    /// `Required` asks for exactly one tool call.
44    /// Default `Auto`.
45    pub fn with_tool_mode(mut self, tool_mode: ToolMode) -> Self {
46        self.tool_mode = tool_mode;
47        self
48    }
49
50    /// Sets the temperature used when a request has none (0 to 2).
51    /// Values outside the range are clamped.
52    /// Default 0.7.
53    pub fn with_default_temperature(mut self, temperature: f64) -> Self {
54        self.default_temperature = if temperature.is_finite() {
55            temperature.clamp(0.0, 2.0)
56        } else {
57            0.7
58        };
59        self
60    }
61
62    /// Sets the sampling seed, so runs repeat for the same input.
63    /// Input: any u32.
64    /// Default `0x5452_4B54`.
65    pub fn with_seed(mut self, seed: u32) -> Self {
66        self.seed = seed;
67        self
68    }
69
70    /// Bans end of text, so generation runs to `max_tokens`.
71    /// Only for fixed-length runs such as benchmarks and kill tests.
72    /// Default false.
73    pub fn with_ban_eos(mut self, ban_eos: bool) -> Self {
74        self.ban_eos = ban_eos;
75        self
76    }
77
78    /// Sets the minimum confidence (geometric mean token probability,
79    /// 0 to 1) below which a call fails with a `Server` error a router
80    /// may fall back on. While set, a streamed reply is held and sent only
81    /// after it passes. Default `None` (off: one softmax per token).
82    pub fn with_min_confidence(mut self, min_confidence: Option<f64>) -> Self {
83        self.min_confidence = min_confidence
84            .filter(|c| c.is_finite())
85            .map(|c| c.clamp(0.0, 1.0));
86        self
87    }
88
89    /// Returns the tool mode.
90    /// Input: none.
91    /// Default `Auto`.
92    pub fn tool_mode(&self) -> ToolMode {
93        self.tool_mode
94    }
95
96    /// Returns the temperature used when a request has none.
97    /// Input: none.
98    /// Default 0.7.
99    pub fn default_temperature(&self) -> f64 {
100        self.default_temperature
101    }
102
103    /// Returns the sampling seed.
104    /// Input: none.
105    /// Default `0x5452_4B54`.
106    pub fn seed(&self) -> u32 {
107        self.seed
108    }
109
110    /// Returns whether end of text is banned.
111    /// Input: none.
112    /// Default false.
113    pub fn ban_eos(&self) -> bool {
114        self.ban_eos
115    }
116
117    /// Returns the minimum confidence, or `None` when off.
118    /// Input: none.
119    /// Default `None`.
120    pub fn min_confidence(&self) -> Option<f64> {
121        self.min_confidence
122    }
123}
124
125/// A local model behind the `Model` interface, so the same agent runs
126/// on device. Renders requests through the model's chat template,
127/// generates on a blocking thread and cancels when the future is dropped.
128pub struct LocalChat {
129    model: Arc<dyn LocalModel>,
130    id: String,
131    settings: LocalChatSettings,
132}
133
134impl std::fmt::Debug for LocalChat {
135    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136        f.debug_struct("LocalChat")
137            .field("id", &self.id)
138            .field("settings", &self.settings)
139            .finish()
140    }
141}
142
143struct CancelOnDrop(Arc<AtomicBool>);
144
145impl Drop for CancelOnDrop {
146    fn drop(&mut self) {
147        self.0.store(true, Ordering::SeqCst);
148    }
149}
150
151impl LocalChat {
152    /// Wraps a loaded local model with default settings.
153    /// Input: the model and the id `Model::id` returns.
154    /// Output: the chat model.
155    pub fn new(model: Arc<dyn LocalModel>, id: impl Into<String>) -> Self {
156        Self {
157            model,
158            id: id.into(),
159            settings: LocalChatSettings::default(),
160        }
161    }
162
163    /// Replaces the settings.
164    /// Input: the settings.
165    /// Output: the chat model.
166    pub fn with_settings(mut self, settings: LocalChatSettings) -> Self {
167        self.settings = settings;
168        self
169    }
170
171    /// Returns the settings.
172    /// Input: none.
173    /// Output: the settings.
174    pub fn settings(&self) -> &LocalChatSettings {
175        &self.settings
176    }
177
178    fn render(&self, req: &CompletionRequest) -> Result<Vec<ChatMessage>, ProviderError> {
179        let mut system = req.system_text().unwrap_or_default();
180        let tools = turn_prompt(
181            &req.tools,
182            self.settings.tool_mode,
183            req.output_schema.as_ref(),
184        );
185        if !tools.is_empty() {
186            if !system.is_empty() {
187                system.push_str("\n\n");
188            }
189            system.push_str(&tools);
190        }
191        let mut out = Vec::new();
192        if !system.is_empty() {
193            out.push(ChatMessage::new(ChatRole::System, system));
194        }
195        for message in &req.messages {
196            let role = match message.role {
197                Role::System => continue,
198                Role::User => ChatRole::User,
199                Role::Assistant => ChatRole::Assistant,
200                Role::Tool => ChatRole::User,
201            };
202            let mut lines = Vec::new();
203            for part in &message.parts {
204                match part {
205                    ContentPart::Text { text } => lines.push(text.clone()),
206                    ContentPart::ToolCall {
207                        name, arguments, ..
208                    } => lines.push(
209                        serde_json::json!({ "tool": name, "arguments": arguments }).to_string(),
210                    ),
211                    ContentPart::ToolResult {
212                        content, is_error, ..
213                    } => lines.push(tool_response(content, *is_error)),
214                    ContentPart::Image { .. } => {
215                        return Err(ProviderError::new(
216                            ProviderErrorKind::BadRequest,
217                            "local models do not take images",
218                        ))
219                    }
220                    ContentPart::Hosted { .. } => {}
221                }
222            }
223            if !lines.is_empty() {
224                out.push(ChatMessage::new(role, lines.join("\n")));
225            }
226        }
227        Ok(out)
228    }
229
230    async fn run(
231        &self,
232        req: &CompletionRequest,
233        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
234    ) -> Result<CompletionResponse, ProviderError> {
235        req.validate()?;
236        let req = req.sendable(false)?;
237        let grammar = request_grammar(
238            &req.tools,
239            self.settings.tool_mode,
240            req.output_schema.as_ref(),
241        )
242        .map_err(server)?;
243        let messages = self.render(&req)?;
244        for message in &messages {
245            self.refuse_control_tokens(message.content())?;
246        }
247        let rendered = self.model.render_chat(&messages, true).map_err(server)?;
248        let prompt = self.model.tokenize(&rendered, true).map_err(server)?;
249        let limit = self.model.info().context_length();
250        if prompt.len() >= limit {
251            return Err(server(LocalError::ContextFull {
252                needed: prompt.len() + 1,
253                limit,
254            }));
255        }
256        let max_tokens = (req.max_tokens as usize).min(limit - prompt.len());
257        assert!(max_tokens > 0 && prompt.len() + max_tokens <= limit);
258        let cancel = Arc::new(AtomicBool::new(false));
259        let _guard = CancelOnDrop(cancel.clone());
260        let temperature = req.temperature.unwrap_or(self.settings.default_temperature);
261        let params = GenParams::default()
262            .with_max_tokens(max_tokens)
263            .with_temperature(temperature as f32)
264            .with_seed(self.settings.seed)
265            .with_ban_eos(self.settings.ban_eos)
266            .with_grammar(grammar)
267            .with_confidence(self.settings.min_confidence.is_some())
268            .with_cancel(Some(cancel));
269        let prompt_tokens = prompt.len();
270        let require_call = self.settings.tool_mode == ToolMode::Required && !req.tools.is_empty();
271        let hold_all = require_call || self.settings.min_confidence.is_some();
272        let mut gate = TextGate::new(!req.tools.is_empty(), hold_all);
273        let generation = self.generate(prompt, params, &mut gate, on_delta).await?;
274        self.check_confidence(&generation)?;
275        check_answered(&generation, max_tokens, !req.tools.is_empty())?;
276        let call_id = next_call_id(&req.messages);
277        let parts: Vec<ContentPart> = parse_reply(generation.text(), &req.tools)
278            .map_err(server)?
279            .into_iter()
280            .map(|p| match p {
281                ContentPart::ToolCall {
282                    name, arguments, ..
283                } => ContentPart::ToolCall {
284                    id: call_id.clone(),
285                    name,
286                    arguments,
287                },
288                other => other,
289            })
290            .collect();
291        let call = parts.iter().find_map(|p| match p {
292            ContentPart::ToolCall {
293                id,
294                name,
295                arguments,
296            } => Some((id.clone(), name.clone(), arguments.to_string())),
297            _ => None,
298        });
299        if require_call && call.is_none() {
300            return Err(ProviderError::new(
301                ProviderErrorKind::Server,
302                "local model answered in text, but tool_mode Required needs a tool call",
303            ));
304        }
305        match &call {
306            Some((id, name, json)) => {
307                on_delta(&Delta::ToolCallStarted {
308                    index: 0,
309                    id: id.clone(),
310                    name: name.clone(),
311                });
312                on_delta(&Delta::ToolCallArgs {
313                    index: 0,
314                    json: json.clone(),
315                });
316            }
317            None => {
318                if let Some(text) = gate.flush() {
319                    on_delta(&Delta::TextDelta { text });
320                }
321            }
322        }
323        let stop = match (call.is_some(), generation.stop()) {
324            (true, _) => StopReason::ToolUse,
325            (false, GenStop::MaxTokens) => StopReason::MaxTokens,
326            (false, GenStop::Cancelled) => StopReason::Other("cancelled".into()),
327            (false, _) => StopReason::EndTurn,
328        };
329        let usage = Usage {
330            input_tokens: prompt_tokens as u64,
331            output_tokens: generation.tokens() as u64,
332            cost_usd_micros: 0,
333        };
334        on_delta(&Delta::Usage {
335            input_tokens: Some(usage.input_tokens),
336            output_tokens: Some(usage.output_tokens),
337        });
338        on_delta(&Delta::Stop {
339            reason: stop.clone(),
340        });
341        let message = Message::new(Role::Assistant, parts)
342            .map_err(|e| ProviderError::new(ProviderErrorKind::Server, e.to_string()))?;
343        Ok(CompletionResponse {
344            message,
345            usage,
346            stop,
347        })
348    }
349
350    fn refuse_control_tokens(&self, content: &str) -> Result<(), ProviderError> {
351        let plain = self.model.tokenize(content, false).map_err(server)?;
352        let special = self.model.tokenize(content, true).map_err(server)?;
353        if plain != special {
354            return Err(ProviderError::new(
355                ProviderErrorKind::BadRequest,
356                "message text holds chat template control tokens",
357            ));
358        }
359        Ok(())
360    }
361
362    fn check_confidence(&self, generation: &Generation) -> Result<(), ProviderError> {
363        let (Some(min), Some(lp)) = (self.settings.min_confidence, generation.mean_logprob())
364        else {
365            return Ok(());
366        };
367        let confidence = lp.exp();
368        assert!((0.0..=1.0).contains(&confidence));
369        if confidence < min {
370            return Err(ProviderError::new(
371                ProviderErrorKind::Server,
372                format!("local confidence {confidence:.3} below {min}"),
373            ));
374        }
375        Ok(())
376    }
377
378    async fn generate(
379        &self,
380        prompt: Vec<u32>,
381        params: GenParams,
382        gate: &mut TextGate,
383        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
384    ) -> Result<Generation, ProviderError> {
385        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<String>();
386        let model = self.model.clone();
387        let ctx = troupekit_trace::current();
388        let handle = tokio::task::spawn_blocking(move || {
389            let mut on_token = |piece: &str| {
390                if tx.send(piece.to_string()).is_err() {
391                    Flow::Stop
392                } else {
393                    Flow::Continue
394                }
395            };
396            match ctx {
397                Some(ctx) => ctx.enter(|| model.generate(&prompt, &params, &mut on_token)),
398                None => model.generate(&prompt, &params, &mut on_token),
399            }
400        });
401        while let Some(piece) = rx.recv().await {
402            if let Some(text) = gate.push(&piece) {
403                on_delta(&Delta::TextDelta { text });
404            }
405        }
406        handle
407            .await
408            .map_err(|e| {
409                ProviderError::new(
410                    ProviderErrorKind::Server,
411                    format!("local generation stopped: {e}"),
412                )
413            })?
414            .map_err(server)
415    }
416}
417
418/// Names the next local tool call. Input: the request history. Output:
419/// `local-N` with N one above the highest `local-N` call id kept in the
420/// history (1 when there is none), so a history that dropped earlier
421/// calls still gets an id no kept call uses.
422fn next_call_id(messages: &[Message]) -> String {
423    let highest = messages
424        .iter()
425        .flat_map(|m| &m.parts)
426        .filter_map(|p| match p {
427            ContentPart::ToolCall { id, .. } => id.strip_prefix("local-")?.parse::<u64>().ok(),
428            _ => None,
429        })
430        .max()
431        .unwrap_or(0);
432    format!("local-{}", highest.saturating_add(1))
433}
434
435/// Renders one tool result the way Qwen-style chat templates expect it in
436/// a user turn: `<tool_response>\n...\n</tool_response>`, which the
437/// template reads as a tool turn and not as a new question. A failed
438/// call's content starts with `error: `; a closing tag inside the content
439/// is escaped so a tool cannot end the block early. Output: the block.
440fn tool_response(content: &str, is_error: bool) -> String {
441    let body = content.replace(TOOL_RESPONSE_CLOSE, "<\\/tool_response>");
442    assert!(!body.contains(TOOL_RESPONSE_CLOSE));
443    let prefix = if is_error { "error: " } else { "" };
444    format!("<tool_response>\n{prefix}{body}\n{TOOL_RESPONSE_CLOSE}")
445}
446
447/// Refuses a local reply that holds no answer: one that ends inside its
448/// `<think>` block, or one the output cap cut before any answer text or
449/// inside a tool call. A seeded local run would repeat the same cut, so
450/// the error is a `Decode`, which no retry repeats. Input: the
451/// generation, the cap and whether the turn offered tools.
452fn check_answered(
453    generation: &Generation,
454    max_tokens: usize,
455    tools: bool,
456) -> Result<(), ProviderError> {
457    let text = generation.text();
458    let used = generation.tokens();
459    let refuse = |what: &str| {
460        Err(ProviderError::new(
461            ProviderErrorKind::Decode,
462            format!(
463                "local reply {what} after {used} of {max_tokens} output tokens, so it holds no answer; raise max_tokens"
464            ),
465        ))
466    };
467    if unclosed_think(text) {
468        return refuse("ended inside its <think> block");
469    }
470    if generation.stop() != GenStop::MaxTokens {
471        return Ok(());
472    }
473    let answer = answer_of(text).trim_start();
474    if answer.is_empty() {
475        return refuse("was cut by the output cap before any answer text");
476    }
477    if tools
478        && answer.starts_with('{')
479        && serde_json::from_str::<serde_json::Value>(answer.trim_end()).is_err()
480    {
481        return refuse("was cut by the output cap inside a tool call");
482    }
483    Ok(())
484}
485
486fn server(e: LocalError) -> ProviderError {
487    ProviderError::new(ProviderErrorKind::Server, e.to_string())
488}
489
490struct TextGate {
491    buffer: String,
492    state: GateState,
493    tools: bool,
494}
495
496#[derive(PartialEq)]
497enum GateState {
498    Deciding,
499    Text,
500    Held,
501}
502
503impl TextGate {
504    fn new(tools: bool, hold_all: bool) -> Self {
505        Self {
506            buffer: String::new(),
507            tools,
508            state: match hold_all {
509                true => GateState::Held,
510                false => GateState::Deciding,
511            },
512        }
513    }
514
515    fn push(&mut self, piece: &str) -> Option<String> {
516        match self.state {
517            GateState::Text => (!piece.is_empty()).then(|| piece.to_string()),
518            GateState::Held => {
519                self.buffer.push_str(piece);
520                None
521            }
522            GateState::Deciding => {
523                self.buffer.push_str(piece);
524                let head = self.buffer.trim_start();
525                let answer = after_think(head);
526                if answer.is_none() && opens_think(head) {
527                    return None;
528                }
529                match answer.unwrap_or(head).chars().next() {
530                    None => None,
531                    Some('{') if self.tools => {
532                        self.state = GateState::Held;
533                        None
534                    }
535                    Some(_) => {
536                        let out = answer.map(str::to_string);
537                        self.state = GateState::Text;
538                        let buffered = std::mem::take(&mut self.buffer);
539                        Some(out.unwrap_or(buffered))
540                    }
541                }
542            }
543        }
544    }
545
546    fn flush(&mut self) -> Option<String> {
547        let held = self.state != GateState::Text;
548        self.state = GateState::Text;
549        let text = std::mem::take(&mut self.buffer);
550        let text = answer_of(&text).to_string();
551        (held && !text.is_empty()).then_some(text)
552    }
553}
554
555#[async_trait]
556impl Model for LocalChat {
557    fn id(&self) -> &str {
558        &self.id
559    }
560
561    async fn complete(&self, req: &CompletionRequest) -> Result<CompletionResponse, ProviderError> {
562        self.run(req, &mut |_| {}).await
563    }
564
565    async fn stream(
566        &self,
567        req: &CompletionRequest,
568        on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
569    ) -> Result<CompletionResponse, ProviderError> {
570        self.run(req, on_delta).await
571    }
572}