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::gbnf::{literal, schema_to_gbnf, GbnfBuilder, MAX_LENGTH};
use crate::{Grammar, LocalError};
use serde_json::Value;
use troupekit_core::tool::ToolSpec;

const MAX_TOOLS: usize = 64;
const TEXT_RULE: &str = r"[^{< \t\r\n\x00] [^\x00]*";
const THINK_RULE: &str = r#""<think>" ([^<\x00] | "<" [^/\x00])* "</think>" [ \t\r\n]*"#;
const ARGUMENT_ONLY: [&str; 4] = [
    "minLength",
    "minProperties",
    "maxProperties",
    "propertyNames",
];

/// Whether a local model may answer in text when tools are offered.
/// `Auto` allows text or one tool call; `Required` allows only a call.
/// Default `Auto`.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ToolMode {
    #[default]
    Auto,
    Required,
}

/// Builds the system prompt block that lists the tools and the reply
/// format `parse_reply` reads. Tool names and schemas are written as
/// JSON, so a name cannot break out of its quotes. Empty for no tools.
pub fn tool_prompt(tools: &[ToolSpec], mode: ToolMode) -> String {
    turn_prompt(tools, mode, None)
}

/// Builds the tool prompt for a `LocalChat` turn. With an output schema
/// in `Auto`, the no-tool reply is JSON of that schema instead of plain
/// text, matching `request_grammar`. Empty for no tools.
pub(crate) fn turn_prompt(tools: &[ToolSpec], mode: ToolMode, output: Option<&Value>) -> String {
    if tools.is_empty() {
        return String::new();
    }
    let mut out = String::from("You can call these tools:\n");
    for tool in tools {
        let name = serde_json::Value::String(tool.name.clone()).to_string();
        let description = serde_json::Value::String(tool.description.clone()).to_string();
        out.push_str(&format!(
            "- name: {name}\n  description: {description}\n  arguments schema: {}\n",
            tool.schema
        ));
    }
    out.push_str("To call a tool, reply with only this JSON object and nothing else:\n");
    out.push_str("{\"tool\":\"<name>\",\"arguments\":{...}}\n");
    out.push_str("A tool's result comes back inside <tool_response></tool_response>. Use it; call a tool again only when you still need something the results do not hold.\n");
    match mode {
        ToolMode::Auto => match output {
            None => out.push_str("If no tool is needed, reply in plain text.\n"),
            Some(schema) => out.push_str(&format!(
                "If no tool is needed, reply with only JSON that matches this schema: {schema}\n"
            )),
        },
        ToolMode::Required => out.push_str("You must call exactly one tool.\n"),
    }
    out
}

/// Builds the grammar for a turn with tools: one root branch per tool,
/// `{"tool":"<name>","arguments":<schema>}`, plus a plain-text branch in
/// `ToolMode::Auto` that cannot open with `{` or `<`. Each branch may
/// follow one `<think>...</think>` block, as a thinking model writes.
/// Errors: no tools, more than 64, a root schema not `type: "object"`.
pub fn tool_grammar(tools: &[ToolSpec], mode: ToolMode) -> Result<Grammar, LocalError> {
    turn_grammar(tools, mode, None)
}

/// Builds the grammar for `output_schema`: generation must produce one
/// JSON value of the schema. Input: the schema. Output: the grammar, or
/// `LocalError::Grammar` for a schema the converter refuses.
pub fn output_grammar(schema: &Value) -> Result<Grammar, LocalError> {
    schema_to_gbnf(schema)
}

/// Builds the grammar a `LocalChat` turn uses: tool branches and, in
/// `Auto`, the output schema (when given) or plain text as the last
/// branch. Output: `None` when there is neither a tool nor a schema.
pub(crate) fn request_grammar(
    tools: &[ToolSpec],
    mode: ToolMode,
    output: Option<&Value>,
) -> Result<Option<Grammar>, LocalError> {
    match (tools.is_empty(), output) {
        (true, None) => Ok(None),
        (true, Some(schema)) => output_grammar(schema).map(Some),
        (false, _) => turn_grammar(tools, mode, output).map(Some),
    }
}

fn turn_grammar(
    tools: &[ToolSpec],
    mode: ToolMode,
    output: Option<&Value>,
) -> Result<Grammar, LocalError> {
    if tools.is_empty() {
        return Err(LocalError::Grammar(
            "a tool grammar needs at least one tool".into(),
        ));
    }
    if tools.len() > MAX_TOOLS {
        return Err(LocalError::Grammar(format!(
            "{} tools offered, a local tool grammar takes at most {MAX_TOOLS}",
            tools.len()
        )));
    }
    let mut builder = GbnfBuilder::new();
    let think = builder.rule(THINK_RULE.to_string())?;
    let mut branches = Vec::with_capacity(tools.len() + 1);
    for tool in tools {
        let fail = |e: LocalError| LocalError::Grammar(format!("tool {:?}: {e}", tool.name));
        if tool.schema.get("type").and_then(Value::as_str) != Some("object") {
            return Err(fail(LocalError::Grammar(
                "its schema must have `type: \"object\"` at the root".into(),
            )));
        }
        let arguments = builder
            .schema(&arguments_schema(&tool.schema))
            .map_err(fail)?;
        let name = serde_json::to_string(&tool.name).expect("a string serializes");
        let body = format!(
            r#"{think}? "{{" ws "\"tool\"" ws ":" ws {} ws "," ws "\"arguments\"" ws ":" ws {arguments} ws "}}""#,
            literal(&name)
        );
        branches.push(builder.rule(body)?);
    }
    if mode == ToolMode::Auto {
        let last = match output {
            None => TEXT_RULE.to_string(),
            Some(schema) => {
                if may_hold_tool_key(schema) {
                    return Err(LocalError::Grammar(
                        "output_schema may produce a top-level `tool` key (root `properties`, `const`, `enum`, `$ref`, `anyOf` or `oneOf`), which a local reply would read as a tool call".into(),
                    ));
                }
                builder.schema(schema)?
            }
        };
        branches.push(builder.rule(format!("{think}? ({last})"))?);
    }
    assert_eq!(
        branches.len(),
        tools.len() + usize::from(mode == ToolMode::Auto),
        "one branch per tool, plus the Auto branch"
    );
    builder.finish(&branches.join(" | "))
}

/// Tells whether a value of `schema` may be an object with a top-level
/// `tool` key. Root `$ref`, `anyOf` and `oneOf` count as may, since
/// their targets are not walked. Input: the output schema.
fn may_hold_tool_key(schema: &Value) -> bool {
    let holds = |value: &Value| value.get("tool").is_some();
    ["$ref", "anyOf", "oneOf"]
        .iter()
        .any(|k| schema.get(k).is_some())
        || schema.get("properties").is_some_and(holds)
        || schema.get("const").is_some_and(holds)
        || schema
            .get("enum")
            .and_then(Value::as_array)
            .is_some_and(|values| values.iter().any(holds))
}

/// Returns the tool argument `schema` without the checks a grammar cannot
/// express: `minLength`, `minProperties`, `maxProperties`,
/// `propertyNames`, and `minimum` or `maximum` on a non-integer number;
/// a `maxLength` above the grammar's cap is narrowed to it.
/// The registry still checks every argument against the full schema
/// before the tool runs, so the grammar only shapes generation. A map
/// whose keys are a `propertyNames` enum becomes one optional property per
/// key. Walks schema positions only, so a property named like a keyword
/// stays.
fn arguments_schema(schema: &Value) -> Value {
    let Value::Object(obj) = schema else {
        return schema.clone();
    };
    let fractional = match obj.get("type") {
        Some(Value::String(t)) => t == "number",
        Some(Value::Array(ts)) => {
            ts.iter().any(|t| t == "number") && !ts.iter().any(|t| t == "integer")
        }
        _ => false,
    };
    if let Some(closed) = closed_map(obj) {
        return arguments_schema(&closed);
    }
    let mut out = serde_json::Map::new();
    for (key, value) in obj {
        if ARGUMENT_ONLY.contains(&key.as_str())
            || (fractional && (key == "minimum" || key == "maximum"))
        {
            continue;
        }
        let kept = match key.as_str() {
            "properties" | "$defs" => match value {
                Value::Object(map) => Value::Object(
                    map.iter()
                        .map(|(name, sub)| (name.clone(), arguments_schema(sub)))
                        .collect(),
                ),
                other => other.clone(),
            },
            "maxLength" => match value.as_u64() {
                Some(n) if n > MAX_LENGTH => Value::from(MAX_LENGTH),
                _ => value.clone(),
            },
            "items" | "additionalProperties" => arguments_schema(value),
            "anyOf" | "oneOf" => match value {
                Value::Array(list) => Value::Array(list.iter().map(arguments_schema).collect()),
                other => other.clone(),
            },
            _ => value.clone(),
        };
        out.insert(key.clone(), kept);
    }
    assert_eq!(
        out.get("type"),
        obj.get("type"),
        "the type is never dropped"
    );
    Value::Object(out)
}

/// Rewrites an object whose keys come from a `propertyNames` enum and
/// whose values share one `additionalProperties` schema as the same object
/// with one optional property per key and no others. Output: `None` for
/// any other object.
fn closed_map(obj: &serde_json::Map<String, Value>) -> Option<Value> {
    let names = obj.get("propertyNames")?.get("enum")?.as_array()?;
    let values = obj.get("additionalProperties").filter(|v| v.is_object())?;
    if obj.contains_key("properties") || names.iter().any(|n| !n.is_string()) {
        return None;
    }
    let mut out = obj.clone();
    out.remove("propertyNames");
    let properties: serde_json::Map<String, Value> = names
        .iter()
        .filter_map(Value::as_str)
        .map(|n| (n.to_string(), values.clone()))
        .collect();
    assert_eq!(properties.len(), names.len(), "every enum name is a string");
    out.insert("properties".into(), Value::Object(properties));
    out.insert("additionalProperties".into(), Value::Bool(false));
    Some(Value::Object(out))
}