troupekit-local 0.4.0

On-device models for the Troupekit LLM agent framework: the LocalModel trait, model catalog and llama.cpp.
Documentation
use crate::error::LocalError;
use serde::de::{Deserialize, Deserializer, MapAccess, Visitor};
use serde_json::{Map, Value};
use std::collections::BTreeSet;
use std::fmt;
use troupekit_core::message::ContentPart;
use troupekit_core::tool::ToolSpec;

/// The largest local reply `parse_reply` reads, in bytes (1 MiB).
/// Longer replies are refused before any JSON parsing.
/// Bounds memory on a runaway generation.
pub const REPLY_MAX_BYTES: usize = 1024 * 1024;

const THINK_OPEN: &str = "<think>";
const THINK_CLOSE: &str = "</think>";

/// Turns a local model's reply into message parts. One leading
/// `<think>...</think>` block is dropped first; with tools, a reply
/// that is exactly `{"tool":"<name>","arguments":{..}}` becomes one
/// `ToolCall` with id `local-1`; anything else is one `Text` part.
/// Errors: over 1 MiB, a reply that ends inside its `<think>` block,
/// an unknown tool, or a malformed call object.
pub fn parse_reply(text: &str, tools: &[ToolSpec]) -> Result<Vec<ContentPart>, LocalError> {
    if text.len() > REPLY_MAX_BYTES {
        return Err(LocalError::Decode(format!(
            "local reply is {} bytes, limit {REPLY_MAX_BYTES}",
            text.len()
        )));
    }
    if unclosed_think(text) {
        return Err(LocalError::Decode(
            "local reply ends inside its <think> block, so it holds no answer".into(),
        ));
    }
    let text = answer_of(text);
    let text_part = || {
        vec![ContentPart::Text {
            text: text.to_string(),
        }]
    };
    if tools.is_empty() || !text.trim_start().starts_with('{') {
        return Ok(text_part());
    }
    let Ok(Members(members)) = serde_json::from_str::<Members>(text.trim()) else {
        return Ok(text_part());
    };
    let mut seen = BTreeSet::new();
    let unique = members.iter().all(|(key, _)| seen.insert(key.as_str()));
    let map: Map<String, Value> = members.into_iter().collect();
    let Some(tool) = map.get("tool") else {
        return Ok(text_part());
    };
    if !unique {
        return Err(LocalError::Decode(
            "local tool call repeats a member".into(),
        ));
    }
    let Value::String(name) = tool else {
        return Err(LocalError::Decode(
            "local tool call has a non-string tool name".into(),
        ));
    };
    if !tools.iter().any(|t| &t.name == name) {
        return Err(LocalError::Decode(format!(
            "local reply calls unknown tool {name:?}"
        )));
    }
    if map.len() != 2 {
        return Err(LocalError::Decode(
            "local tool call must hold only tool and arguments".into(),
        ));
    }
    let Some(arguments @ Value::Object(_)) = map.get("arguments") else {
        return Err(LocalError::Decode(format!(
            "local call to {name:?} has no arguments object"
        )));
    };
    Ok(vec![ContentPart::ToolCall {
        id: "local-1".to_string(),
        name: name.clone(),
        arguments: arguments.clone(),
    }])
}

/// The answer in a local reply: what follows one leading closed
/// `<think>...</think>` block, start-trimmed and possibly empty, else
/// the whole reply. Input: the reply. Output: a slice of it.
pub(crate) fn answer_of(text: &str) -> &str {
    after_think(text).unwrap_or(text)
}

/// Tells whether a finished reply opens a `<think>` block it never
/// closes, as when the output cap cuts the reasoning short. Input: the
/// whole reply. Output: true when the reply holds no answer at all.
pub(crate) fn unclosed_think(text: &str) -> bool {
    text.trim_start().starts_with(THINK_OPEN) && after_think(text).is_none()
}

/// Splits one leading `<think>...</think>` block, the reasoning a
/// thinking model such as Qwen3 writes first, off a reply. Input: the
/// reply. Output: what follows the block, start-trimmed, or `None` when
/// the reply does not open with a closed block.
pub(crate) fn after_think(text: &str) -> Option<&str> {
    let body = text.trim_start().strip_prefix(THINK_OPEN)?;
    let end = body.find(THINK_CLOSE)?;
    Some(body[end + THINK_CLOSE.len()..].trim_start())
}

/// Tells whether `head`, a start-trimmed reply so far, may still become
/// or already opens an unclosed `<think>` block. Input: the reply so far.
/// Output: true while a stream must wait to see the answer.
pub(crate) fn opens_think(head: &str) -> bool {
    THINK_OPEN.starts_with(head) || (head.starts_with(THINK_OPEN) && after_think(head).is_none())
}

/// The top-level members of one JSON object, in source order with
/// repeated keys kept. Input: JSON text. Output: the pairs, or an error
/// when the text is not an object. `Value` merges repeated keys, which
/// would hide a malformed call.
struct Members(Vec<(String, Value)>);

impl<'de> Deserialize<'de> for Members {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct MembersVisitor;
        impl<'de> Visitor<'de> for MembersVisitor {
            type Value = Members;
            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("a JSON object")
            }
            fn visit_map<A: MapAccess<'de>>(self, mut access: A) -> Result<Members, A::Error> {
                let mut members = Vec::new();
                while let Some(pair) = access.next_entry::<String, Value>()? {
                    members.push(pair);
                }
                Ok(Members(members))
            }
        }
        deserializer.deserialize_map(MembersVisitor)
    }
}