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",
];
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ToolMode {
#[default]
Auto,
Required,
}
pub fn tool_prompt(tools: &[ToolSpec], mode: ToolMode) -> String {
turn_prompt(tools, mode, None)
}
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
}
pub fn tool_grammar(tools: &[ToolSpec], mode: ToolMode) -> Result<Grammar, LocalError> {
turn_grammar(tools, mode, None)
}
pub fn output_grammar(schema: &Value) -> Result<Grammar, LocalError> {
schema_to_gbnf(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(" | "))
}
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))
}
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)
}
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))
}