use crate::tokenizer::Tokenizer;
use serde_json::Value;
use std::sync::Arc;
const MAX_DEPTH_CAP: usize = 32;
const MAX_SCHEMAS: usize = 4096;
const MAX_FIXED_STRINGS: usize = 1024;
const MAX_SCHEMA_PROPS: usize = 64;
const NO_SCHEMA: u16 = u16::MAX;
const NO_FIXED_STR: u16 = u16::MAX;
#[derive(Clone, Copy, Debug)]
pub struct GrammarLimits {
pub max_depth: u8,
pub max_container_items: u16,
pub max_string_bytes: u32,
pub max_ws_run: u8,
}
impl GrammarLimits {
pub const DEFAULT: Self = Self {
max_depth: 28,
max_container_items: 1024,
max_string_bytes: 256 * 1024,
max_ws_run: 64,
};
#[cfg(test)]
pub const fn adversarial_test() -> Self {
Self {
max_depth: 8,
max_container_items: 8,
max_string_bytes: 48,
max_ws_run: 4,
}
}
}
impl Default for GrammarLimits {
fn default() -> Self {
Self::DEFAULT
}
}
pub struct VocabBytes {
data: Vec<u8>,
offsets: Vec<u32>,
special_bits: Vec<u64>,
json_ws_bits: Vec<u64>,
str_interior_bits: Vec<u64>,
str_invalid_fresh_bits: Vec<u64>,
vocab_len: usize,
}
impl VocabBytes {
pub fn from_tokenizer(tk: &Tokenizer) -> Self {
let n = tk.vocab_len();
let mut total_bytes = 0usize;
for id in 0..n {
if !tk.is_special(id as u32) {
total_bytes += tk.decode_bytes(id as u32).len();
}
}
Self::build_from_iter(n, total_bytes, |id| {
if tk.is_special(id as u32) {
None
} else {
Some(tk.decode_bytes(id as u32))
}
})
}
fn build_from_iter<F>(n: usize, total_bytes: usize, mut get_bytes: F) -> Self
where
F: FnMut(usize) -> Option<Vec<u8>>,
{
let words = n.div_ceil(64);
let mut data = Vec::with_capacity(total_bytes);
let mut offsets = Vec::with_capacity(n + 1);
let mut special_bits = vec![0u64; words];
let mut json_ws_bits = vec![0u64; words];
let mut str_interior_bits = vec![0u64; words];
let mut str_invalid_fresh_bits = vec![0u64; words];
for id in 0..n {
offsets.push(data.len() as u32);
let word = id / 64;
let bit = 1u64 << (id % 64);
match get_bytes(id) {
None => {
special_bits[word] |= bit;
}
Some(bytes) => {
if !bytes.is_empty() {
if bytes.iter().all(|&b| is_json_ws(b)) {
json_ws_bits[word] |= bit;
}
let mut ss = StrSubState::new();
let mut all_continue = true;
let mut invalid_before_close = false;
for &b in &bytes {
match ss.step(b, u32::MAX) {
StrStep::Continue => {}
StrStep::Closed => {
all_continue = false;
break;
}
StrStep::Invalid => {
all_continue = false;
invalid_before_close = true;
break;
}
}
}
if all_continue {
str_interior_bits[word] |= bit;
} else if invalid_before_close {
str_invalid_fresh_bits[word] |= bit;
}
}
data.extend_from_slice(&bytes);
}
}
}
offsets.push(data.len() as u32);
Self {
data,
offsets,
special_bits,
json_ws_bits,
str_interior_bits,
str_invalid_fresh_bits,
vocab_len: n,
}
}
#[cfg(test)]
pub(crate) fn from_test_entries(entries: &[Option<&[u8]>]) -> Self {
let total_bytes: usize = entries.iter().filter_map(|e| e.map(|b| b.len())).sum();
Self::build_from_iter(entries.len(), total_bytes, |id| {
entries[id].map(|b| b.to_vec())
})
}
#[inline]
pub fn is_special(&self, id: u32) -> bool {
let idx = id as usize;
if idx >= self.vocab_len {
return true;
}
(self.special_bits[idx / 64] & (1u64 << (idx % 64))) != 0
}
#[inline]
fn bit_set(bits: &[u64], id: u32, vocab_len: usize) -> bool {
let idx = id as usize;
idx < vocab_len && (bits[idx / 64] & (1u64 << (idx % 64))) != 0
}
#[inline]
pub fn is_json_ws_token(&self, id: u32) -> bool {
Self::bit_set(&self.json_ws_bits, id, self.vocab_len)
}
#[inline]
pub fn is_str_interior(&self, id: u32) -> bool {
Self::bit_set(&self.str_interior_bits, id, self.vocab_len)
}
#[inline]
pub fn is_str_invalid_fresh(&self, id: u32) -> bool {
Self::bit_set(&self.str_invalid_fresh_bits, id, self.vocab_len)
}
#[inline]
pub fn non_special_bytes(&self, id: u32) -> Option<&[u8]> {
let idx = id as usize;
if idx >= self.vocab_len || self.is_special(id) {
return None;
}
let s = self.offsets[idx] as usize;
let e = self.offsets[idx + 1] as usize;
Some(&self.data[s..e])
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct TypeMask(u8);
impl TypeMask {
const OBJ: Self = Self(1 << 0);
const ARR: Self = Self(1 << 1);
const STR: Self = Self(1 << 2);
const NUM: Self = Self(1 << 3);
const INT: Self = Self(1 << 4);
const BOOL: Self = Self(1 << 5);
const NULL: Self = Self(1 << 6);
const CONTAINERS: Self = Self((1 << 0) | (1 << 1));
const ANY: Self = Self((1 << 0) | (1 << 1) | (1 << 2) | (1 << 3) | (1 << 5) | (1 << 6));
#[inline]
const fn contains(self, other: Self) -> bool {
(self.0 & other.0) != 0
}
#[inline]
const fn bitor(self, other: Self) -> Self {
Self(self.0 | other.0)
}
#[inline]
const fn without_containers_if_possible(self) -> Self {
let prims = self.0 & !Self::CONTAINERS.0;
if prims != 0 {
Self(prims)
} else {
self
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct PropValueSpec {
mask: TypeMask,
nested_schema: u16,
fixed_str: u16,
}
impl PropValueSpec {
const fn any() -> Self {
Self {
mask: TypeMask::ANY,
nested_schema: NO_SCHEMA,
fixed_str: NO_FIXED_STR,
}
}
const fn object(nested_schema: u16) -> Self {
Self {
mask: TypeMask::OBJ,
nested_schema,
fixed_str: NO_FIXED_STR,
}
}
const fn fixed_string(fixed_str: u16) -> Self {
Self {
mask: TypeMask::STR,
nested_schema: NO_SCHEMA,
fixed_str,
}
}
}
#[derive(Clone, Debug)]
struct PropSpec {
escaped: Vec<u8>,
spec: PropValueSpec,
}
#[derive(Clone, Debug)]
struct ObjectSchema {
props: Vec<PropSpec>,
required_mask: u64,
allow_additional: bool,
}
impl ObjectSchema {
#[inline]
fn all_props_mask(&self) -> u64 {
let n = self.props.len().min(MAX_SCHEMA_PROPS);
if n == 64 {
u64::MAX
} else {
(1u64 << n) - 1
}
}
#[inline]
fn required_satisfied(&self, seen_mask: u64) -> bool {
(seen_mask & self.required_mask) == self.required_mask
}
#[inline]
fn unseen_mask(&self, seen_mask: u64) -> u64 {
self.all_props_mask() & !seen_mask
}
#[inline]
fn can_add_more_keys(&self, seen_mask: u64) -> bool {
self.allow_additional || self.unseen_mask(seen_mask) != 0
}
}
#[derive(Clone, Debug, Default)]
pub struct SchemaArena {
schemas: Vec<ObjectSchema>,
fixed_strings: Vec<Vec<u8>>,
over_limit: Option<String>,
}
fn json_escaped_inner(s: &str) -> Vec<u8> {
let quoted = serde_json::to_string(s).expect("JSON string serialization");
quoted.as_bytes()[1..quoted.len() - 1].to_vec()
}
impl SchemaArena {
fn note_over_limit(&mut self, what: String) {
self.over_limit.get_or_insert(what);
}
fn intern_fixed_str(&mut self, s: &str) -> u16 {
if self.fixed_strings.len() >= MAX_FIXED_STRINGS {
self.note_over_limit(format!("more than {MAX_FIXED_STRINGS} tool names"));
return NO_FIXED_STR;
}
let esc = json_escaped_inner(s);
if let Some(pos) = self.fixed_strings.iter().position(|x| x == &esc) {
return pos as u16;
}
let idx = self.fixed_strings.len() as u16;
self.fixed_strings.push(esc);
idx
}
fn compile_prop_value(&mut self, schema: &Value, depth: usize) -> PropValueSpec {
let Some(obj) = schema.as_object() else {
return PropValueSpec::any();
};
let Some(ty_val) = obj.get("type") else {
if obj.contains_key("properties") || obj.contains_key("required") {
let nested = if depth < 6 {
self.compile_object_schema(schema, depth + 1)
} else {
NO_SCHEMA
};
return PropValueSpec::object(nested);
}
return PropValueSpec::any();
};
let parse_one = |name: &str| -> Option<TypeMask> {
match name {
"object" => Some(TypeMask::OBJ),
"array" => Some(TypeMask::ARR),
"string" => Some(TypeMask::STR),
"number" => Some(TypeMask::NUM),
"integer" => Some(TypeMask::INT),
"boolean" => Some(TypeMask::BOOL),
"null" => Some(TypeMask::NULL),
_ => None,
}
};
let mut mask = TypeMask(0);
match ty_val {
Value::String(s) => {
let Some(m) = parse_one(s) else {
return PropValueSpec::any();
};
mask = m;
}
Value::Array(items) => {
for item in items {
let Some(s) = item.as_str().and_then(parse_one) else {
return PropValueSpec::any();
};
mask = mask.bitor(s);
}
if mask.0 == 0 {
return PropValueSpec::any();
}
}
_ => return PropValueSpec::any(),
}
let nested_schema = if mask.contains(TypeMask::OBJ) && depth < 6 {
self.compile_object_schema(schema, depth + 1)
} else {
NO_SCHEMA
};
PropValueSpec {
mask,
nested_schema,
fixed_str: NO_FIXED_STR,
}
}
pub fn compile_object_schema(&mut self, schema: &Value, depth: usize) -> u16 {
if self.schemas.len() >= MAX_SCHEMAS {
self.note_over_limit(schemas_over_limit());
return NO_SCHEMA;
}
let Some(obj) = schema.as_object() else {
return NO_SCHEMA;
};
let allow_additional = !matches!(obj.get("additionalProperties"), Some(Value::Bool(false)));
let mut prop_names: Vec<String> = Vec::new();
let mut required_names: Vec<String> = Vec::new();
if let Some(req_arr) = obj.get("required").and_then(Value::as_array) {
for r in req_arr {
if let Some(name) = r.as_str() {
if !required_names.iter().any(|x| x == name) && required_names.len() < MAX_SCHEMA_PROPS {
required_names.push(name.to_owned());
}
if !prop_names.iter().any(|x| x == name) && prop_names.len() < MAX_SCHEMA_PROPS {
prop_names.push(name.to_owned());
}
}
}
}
let props_map = obj.get("properties").and_then(Value::as_object);
if let Some(pm) = props_map {
for k in pm.keys() {
if !prop_names.iter().any(|x| x == k) && prop_names.len() < MAX_SCHEMA_PROPS {
prop_names.push(k.clone());
}
}
}
let required = obj.get("required").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str);
let keys = props_map.into_iter().flat_map(|pm| pm.keys().map(String::as_str));
if prop_names.len() == MAX_SCHEMA_PROPS && required.chain(keys).any(|n| !prop_names.iter().any(|p| p == n)) {
self.note_over_limit(format!("an object schema with more than {MAX_SCHEMA_PROPS} properties"));
}
if prop_names.is_empty() && allow_additional {
return NO_SCHEMA;
}
let mut props = Vec::with_capacity(prop_names.len());
let mut required_mask = 0u64;
for (idx, name) in prop_names.iter().enumerate() {
let spec = props_map
.and_then(|pm| pm.get(name))
.map(|sub| self.compile_prop_value(sub, depth))
.unwrap_or_else(PropValueSpec::any);
if required_names.iter().any(|r| r == name) {
required_mask |= 1u64 << idx;
}
props.push(PropSpec {
escaped: json_escaped_inner(name),
spec,
});
}
if self.schemas.len() >= MAX_SCHEMAS {
self.note_over_limit(schemas_over_limit());
return NO_SCHEMA;
}
let id = self.schemas.len() as u16;
self.schemas.push(ObjectSchema {
props,
required_mask,
allow_additional,
});
id
}
fn build_tool_wrapper_schema(&mut self, fixed_tool_name: Option<&str>, args_schema: u16) -> u16 {
let name_spec = match fixed_tool_name.filter(|s| !s.is_empty()) {
Some(name) => {
let fs = self.intern_fixed_str(name);
if fs != NO_FIXED_STR {
PropValueSpec::fixed_string(fs)
} else {
PropValueSpec {
mask: TypeMask::STR,
nested_schema: NO_SCHEMA,
fixed_str: NO_FIXED_STR,
}
}
}
None => PropValueSpec {
mask: TypeMask::STR,
nested_schema: NO_SCHEMA,
fixed_str: NO_FIXED_STR,
},
};
let args_spec = PropValueSpec::object(args_schema);
let props = vec![
PropSpec {
escaped: b"name".to_vec(),
spec: name_spec,
},
PropSpec {
escaped: b"args".to_vec(),
spec: args_spec,
},
];
let id = self.schemas.len() as u16;
self.schemas.push(ObjectSchema {
props,
required_mask: 1u64 << 1,
allow_additional: false,
});
id
}
}
#[derive(Clone, Debug)]
struct ToolEntry {
name: String,
wrapper_schema: u16,
}
#[derive(Clone, Debug)]
pub struct ToolCatalog {
arena: SchemaArena,
fallback_wrapper_schema: u16,
names: Vec<Box<[u8]>>,
name_wrappers: Vec<u16>,
mask: bool,
header_cap: usize,
}
const UNCONSTRAINED_HEADER_CAP: usize = 256;
pub fn header_tool_name(header: &[u8]) -> std::borrow::Cow<'_, str> {
match String::from_utf8_lossy(header) {
std::borrow::Cow::Borrowed(s) => std::borrow::Cow::Borrowed(s.trim()),
std::borrow::Cow::Owned(s) => std::borrow::Cow::Owned(s.trim().to_owned()),
}
}
fn schemas_over_limit() -> String {
format!("more than {MAX_SCHEMAS} object schemas (one per tool, per tool's arguments and per nested object)")
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CallName {
Sent { name: String, offered: bool, consistent: bool },
Unoffered,
}
pub fn bind_call(tools: Option<&ToolCatalog>, header: Option<&[u8]>, body_name: Option<&str>) -> CallName {
let Some(cat) = tools else {
let name = match (body_name, header) {
(Some(b), _) => b.to_owned(),
(None, Some(h)) => header_tool_name(h).into_owned(),
(None, None) => String::new(),
};
return CallName::Sent { name, offered: false, consistent: true };
};
if let Some(h) = header {
if let (true, Ok(name)) = (cat.offers(h), std::str::from_utf8(h)) {
let consistent = body_name.is_none_or(|b| b == name);
return CallName::Sent { name: name.to_owned(), offered: true, consistent };
}
let trimmed = header_tool_name(h);
if cat.offers(trimmed.as_bytes()) {
return CallName::Sent { name: trimmed.into_owned(), offered: true, consistent: false };
}
}
match body_name {
Some(b) if cat.offers(b.as_bytes()) => CallName::Sent { name: b.to_owned(), offered: true, consistent: false },
_ => CallName::Unoffered,
}
}
#[cfg(test)]
thread_local! {
static NAME_PROBES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
#[inline(always)]
fn name_probe() {
#[cfg(test)]
NAME_PROBES.with(|c| c.set(c.get() + 1));
}
impl ToolCatalog {
pub fn over_limit(&self) -> Option<String> {
self.arena
.over_limit
.as_ref()
.map(|what| format!("tools: the request declares {what}; inky's tool-call grammar checks at most that many"))
}
pub fn from_request(req: &Value) -> Option<Arc<Self>> {
let arr = req.get("tools")?.as_array()?;
if arr.is_empty() {
return None;
}
let mut arena = SchemaArena::default();
let mut raw_tools: Vec<(String, Option<&Value>)> = Vec::new();
for item in arr {
if let Some(func) = item.get("function").and_then(Value::as_object) {
if let Some(name) = func.get("name").and_then(Value::as_str).filter(|s| !s.is_empty()) {
raw_tools.push((name.to_owned(), func.get("parameters")));
continue;
}
}
if let Some(obj) = item.as_object() {
if let Some(name) = obj.get("name").and_then(Value::as_str).filter(|s| !s.is_empty()) {
raw_tools.push((name.to_owned(), obj.get("input_schema").or_else(|| obj.get("parameters"))));
}
}
}
let choice = req.get("tool_choice");
let choice_none = choice.is_some_and(|c| c == "none" || c.get("type").is_some_and(|t| t == "none"));
let mut names: Vec<Box<[u8]>> = raw_tools.iter().map(|(name, _)| name.as_bytes().into()).collect();
names.sort_unstable();
names.dedup();
let mask = !choice_none && !names.is_empty();
let header_cap = names.iter().map(|n| n.len()).max().unwrap_or(0).max(UNCONSTRAINED_HEADER_CAP);
let mut tools = Vec::with_capacity(raw_tools.len());
for (name, params) in raw_tools {
if arena.schemas.len() + 2 >= MAX_SCHEMAS {
arena.note_over_limit(schemas_over_limit());
break;
}
let args_schema = params
.map(|p| arena.compile_object_schema(p, 0))
.unwrap_or(NO_SCHEMA);
let wrapper_schema = arena.build_tool_wrapper_schema(Some(&name), args_schema);
tools.push(ToolEntry {
name,
wrapper_schema,
});
}
let fallback_wrapper_schema = if tools.len() == 1 {
tools[0].wrapper_schema
} else {
arena.build_tool_wrapper_schema(None, NO_SCHEMA)
};
let mut name_wrappers = vec![NO_SCHEMA; names.len()];
for entry in &tools {
if let Ok(i) = names.binary_search_by(|n| (**n).cmp(entry.name.as_bytes())) {
if name_wrappers[i] == NO_SCHEMA {
name_wrappers[i] = entry.wrapper_schema;
}
}
}
Some(Arc::new(Self {
arena,
fallback_wrapper_schema,
names,
name_wrappers,
mask,
header_cap,
}))
}
fn find(&self, name: &[u8]) -> Option<usize> {
self.names
.binary_search_by(|n| {
name_probe();
(**n).cmp(name)
})
.ok()
}
pub fn offers(&self, name: &[u8]) -> bool {
self.find(name).is_some()
}
fn lower(&self, lo: usize, hi: usize, pos: usize, bytes: &[u8]) -> usize {
lo + self.names[lo..hi].partition_point(|n| {
name_probe();
&n[pos..] < bytes
})
}
fn narrow(&self, lo: usize, hi: usize, pos: usize, bytes: &[u8]) -> (usize, usize) {
let start = self.lower(lo, hi, pos, bytes);
let end = start
+ self.names[start..hi].partition_point(|n| {
name_probe();
n[pos..].starts_with(bytes)
});
(start, end)
}
fn continues(&self, lo: usize, hi: usize, pos: usize, bytes: &[u8]) -> bool {
let start = self.lower(lo, hi, pos, bytes);
start < hi && self.names[start][pos..].starts_with(bytes)
}
}
#[inline]
fn is_json_ws(b: u8) -> bool {
matches!(b, b' ' | b'\t' | b'\n' | b'\r')
}
#[inline]
fn hex_nibble(b: u8) -> Option<u16> {
match b {
b'0'..=b'9' => Some((b - b'0') as u16),
b'a'..=b'f' => Some((b - b'a' + 10) as u16),
b'A'..=b'F' => Some((b - b'A' + 10) as u16),
_ => None,
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum EscState {
None,
Backslash,
Hex { digits: u8, val: u16, after_high: bool },
NeedLowBackslash,
NeedLowU,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct StrSubState {
utf8_need: u8,
utf8_first_min: u8,
utf8_first_max: u8,
esc: EscState,
byte_len: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum StrStep {
Continue,
Closed,
Invalid,
}
impl StrSubState {
const fn new() -> Self {
Self {
utf8_need: 0,
utf8_first_min: 0x80,
utf8_first_max: 0xBF,
esc: EscState::None,
byte_len: 0,
}
}
#[inline]
fn step(&mut self, b: u8, max_bytes: u32) -> StrStep {
if self.utf8_need > 0 {
if b < self.utf8_first_min || b > self.utf8_first_max {
return StrStep::Invalid;
}
self.utf8_need -= 1;
self.utf8_first_min = 0x80;
self.utf8_first_max = 0xBF;
self.byte_len = self.byte_len.saturating_add(1);
return StrStep::Continue;
}
match self.esc {
EscState::None => {
if b == b'"' {
return StrStep::Closed;
}
if self.byte_len >= max_bytes {
return StrStep::Invalid;
}
if b == b'\\' {
self.esc = EscState::Backslash;
self.byte_len = self.byte_len.saturating_add(1);
return StrStep::Continue;
}
if b < 0x20 {
return StrStep::Invalid;
}
if b < 0x80 {
self.byte_len = self.byte_len.saturating_add(1);
return StrStep::Continue;
}
match b {
0xC2..=0xDF => {
self.utf8_need = 1;
self.utf8_first_min = 0x80;
self.utf8_first_max = 0xBF;
}
0xE0 => {
self.utf8_need = 2;
self.utf8_first_min = 0xA0;
self.utf8_first_max = 0xBF;
}
0xE1..=0xEC | 0xEE..=0xEF => {
self.utf8_need = 2;
self.utf8_first_min = 0x80;
self.utf8_first_max = 0xBF;
}
0xED => {
self.utf8_need = 2;
self.utf8_first_min = 0x80;
self.utf8_first_max = 0x9F;
}
0xF0 => {
self.utf8_need = 3;
self.utf8_first_min = 0x90;
self.utf8_first_max = 0xBF;
}
0xF1..=0xF3 => {
self.utf8_need = 3;
self.utf8_first_min = 0x80;
self.utf8_first_max = 0xBF;
}
0xF4 => {
self.utf8_need = 3;
self.utf8_first_min = 0x80;
self.utf8_first_max = 0x8F;
}
_ => return StrStep::Invalid,
}
self.byte_len = self.byte_len.saturating_add(1);
StrStep::Continue
}
EscState::Backslash => {
self.byte_len = self.byte_len.saturating_add(1);
match b {
b'"' | b'\\' | b'/' | b'b' | b'f' | b'n' | b'r' | b't' => {
self.esc = EscState::None;
StrStep::Continue
}
b'u' => {
self.esc = EscState::Hex {
digits: 0,
val: 0,
after_high: false,
};
StrStep::Continue
}
_ => StrStep::Invalid,
}
}
EscState::Hex {
digits,
val,
after_high,
} => {
let Some(nib) = hex_nibble(b) else {
return StrStep::Invalid;
};
if after_high {
if digits == 0 && nib != 0xD {
return StrStep::Invalid;
}
if digits == 1 && nib < 0xC {
return StrStep::Invalid;
}
} else if digits == 1 && val == 0xD && nib >= 0xC {
return StrStep::Invalid;
}
let next_val = (val << 4) | nib;
let next_digits = digits + 1;
self.byte_len = self.byte_len.saturating_add(1);
if next_digits == 4 {
if !after_high && (0xD800..=0xDBFF).contains(&next_val) {
self.esc = EscState::NeedLowBackslash;
} else {
self.esc = EscState::None;
}
} else {
self.esc = EscState::Hex {
digits: next_digits,
val: next_val,
after_high,
};
}
StrStep::Continue
}
EscState::NeedLowBackslash => {
if b != b'\\' {
return StrStep::Invalid;
}
self.byte_len = self.byte_len.saturating_add(1);
self.esc = EscState::NeedLowU;
StrStep::Continue
}
EscState::NeedLowU => {
if b != b'u' {
return StrStep::Invalid;
}
self.byte_len = self.byte_len.saturating_add(1);
self.esc = EscState::Hex {
digits: 0,
val: 0,
after_high: true,
};
StrStep::Continue
}
}
}
}
const NUM_INT_DIGITS_CAP: u8 = 21;
const NUM_FRAC_DIGITS_CAP: u8 = 33;
const NUM_EXP_DIGITS_CAP: u8 = 5;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum NumStage {
Sign,
Zero,
Int { digits: u8 },
FracNeedDigit,
Frac { digits: u8 },
ExpSignOrDigit,
ExpNeedDigit,
Exp { digits: u8 },
}
impl NumStage {
#[inline]
fn is_complete(self) -> bool {
matches!(
self,
Self::Zero | Self::Int { .. } | Self::Frac { .. } | Self::Exp { .. }
)
}
#[inline]
fn step_digit_or_part(&mut self, b: u8) -> bool {
let next = match *self {
Self::Sign => match b {
b'0' => Some(Self::Zero),
b'1'..=b'9' => Some(Self::Int { digits: 1 }),
_ => None,
},
Self::Zero => match b {
b'.' => Some(Self::FracNeedDigit),
b'e' | b'E' => Some(Self::ExpSignOrDigit),
_ => None,
},
Self::Int { digits } if digits < NUM_INT_DIGITS_CAP => match b {
b'0'..=b'9' => Some(Self::Int { digits: digits + 1 }),
b'.' => Some(Self::FracNeedDigit),
b'e' | b'E' => Some(Self::ExpSignOrDigit),
_ => None,
},
Self::FracNeedDigit => b.is_ascii_digit().then_some(Self::Frac { digits: 1 }),
Self::Frac { digits } if digits < NUM_FRAC_DIGITS_CAP => match b {
b'0'..=b'9' => Some(Self::Frac { digits: digits + 1 }),
b'e' | b'E' => Some(Self::ExpSignOrDigit),
_ => None,
},
Self::ExpSignOrDigit => match b {
b'+' | b'-' => Some(Self::ExpNeedDigit),
b'0'..=b'9' => Some(Self::Exp { digits: 1 }),
_ => None,
},
Self::ExpNeedDigit => b.is_ascii_digit().then_some(Self::Exp { digits: 1 }),
Self::Exp { digits } if digits < NUM_EXP_DIGITS_CAP => {
b.is_ascii_digit().then_some(Self::Exp { digits: digits + 1 })
}
Self::Int { .. } | Self::Frac { .. } | Self::Exp { .. } => None,
};
match next {
Some(stage) => {
*self = stage;
true
}
None => false,
}
}
}
fn number_reads_exactly(lit: &str) -> bool {
let b = lit.as_bytes();
let body = b.strip_prefix(b"-").unwrap_or(b);
let int_len = body.iter().take_while(|c| c.is_ascii_digit()).count();
let rest = &body[int_len..];
let (frac_len, rest) = match rest.strip_prefix(b".") {
Some(r) => {
let n = r.iter().take_while(|c| c.is_ascii_digit()).count();
(Some(n), &r[n..])
}
None => (None, rest),
};
let exp_len = match rest.first() {
Some(b'e' | b'E') => {
let r = rest[1..].strip_prefix(b"+").or_else(|| rest[1..].strip_prefix(b"-")).unwrap_or(&rest[1..]);
let n = r.iter().take_while(|c| c.is_ascii_digit()).count();
if n != r.len() {
return false;
}
Some(n)
}
Some(_) => return false,
None => None,
};
let well_formed = int_len > 0
&& (int_len == 1 || body[0] != b'0')
&& frac_len != Some(0)
&& exp_len != Some(0);
if !well_formed
|| int_len >= usize::from(NUM_INT_DIGITS_CAP)
|| frac_len.unwrap_or(0) >= usize::from(NUM_FRAC_DIGITS_CAP)
|| exp_len.unwrap_or(0) >= usize::from(NUM_EXP_DIGITS_CAP)
{
return false;
}
if frac_len.is_none() && exp_len.is_none() {
return if b[0] == b'-' { lit == "-0" || lit.parse::<i64>().is_ok() } else { lit.parse::<u64>().is_ok() };
}
let Ok(want) = lit.parse::<f64>() else {
return false;
};
let mantissa_nonzero = body.iter().take_while(|c| !matches!(c, b'e' | b'E')).any(|c| matches!(c, b'1'..=b'9'));
want.is_finite()
&& (want != 0.0 || !mantissa_nonzero)
&& serde_json::from_str::<f64>(lit).is_ok_and(|got| got.to_bits() == want.to_bits())
}
pub fn read_call_body(body: &str) -> Value {
let b = body.as_bytes();
let mut minus_zero: Vec<usize> = Vec::new();
let mut i = 0;
while i < b.len() {
match b[i] {
b'"' => {
i += 1;
while i < b.len() && b[i] != b'"' {
i += if b[i] == b'\\' { 2 } else { 1 };
}
i += 1;
}
b'-' | b'0'..=b'9' => {
let start = i;
while i < b.len() && matches!(b[i], b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-') {
i += 1;
}
let lit = &body[start..i];
if !number_reads_exactly(lit) {
return Value::Null;
}
if lit == "-0" {
minus_zero.push(start);
}
}
_ => i += 1,
}
}
let parsed = if minus_zero.is_empty() {
serde_json::from_str(body)
} else {
let mut fixed = b.to_vec();
for at in minus_zero {
fixed[at] = b' ';
}
serde_json::from_slice(&fixed)
};
parsed.unwrap_or(Value::Null)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Frame {
Empty,
Obj {
schema_idx: u16,
seen_mask: u64,
items: u16,
},
Arr {
items: u16,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum KeyMode {
Restricted {
schema_idx: u16,
cand_mask: u64,
pos: u16,
},
Free {
schema_idx: u16,
cand_mask: u64,
pos: u16,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum StrMode {
Free,
Fixed { fixed_str: u16, pos: u16 },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Phase {
BeforeRoot,
ObjExpectKeyOrEnd,
ObjExpectKey,
InKey(KeyMode),
ObjExpectColon(PropValueSpec),
ExpectValue(PropValueSpec),
ArrExpectValOrEnd,
ArrExpectVal,
InString(StrMode),
InNumber(NumStage),
InLit { target: [u8; 5], len: u8, pos: u8 },
AfterValue,
Complete,
}
#[derive(Clone, Copy, Debug)]
struct AutoState {
phase: Phase,
stack: [Frame; MAX_DEPTH_CAP],
depth: u8,
str_sub: StrSubState,
root_schema: u16,
ws_run: u8,
}
impl AutoState {
fn new(root_schema: u16) -> Self {
Self {
phase: Phase::BeforeRoot,
stack: [Frame::Empty; MAX_DEPTH_CAP],
depth: 0,
str_sub: StrSubState::new(),
root_schema,
ws_run: 0,
}
}
#[inline]
fn accept_ws(&mut self, limits: GrammarLimits) -> bool {
if self.ws_run >= limits.max_ws_run {
false
} else {
self.ws_run += 1;
true
}
}
#[inline]
fn is_complete(&self) -> bool {
matches!(self.phase, Phase::Complete)
}
#[inline]
fn top(&self) -> Frame {
self.stack[(self.depth - 1) as usize]
}
#[inline]
fn top_mut(&mut self) -> &mut Frame {
&mut self.stack[(self.depth - 1) as usize]
}
fn push_obj(&mut self, schema_idx: u16, arena: &SchemaArena) -> bool {
if self.depth as usize >= MAX_DEPTH_CAP {
return false;
}
self.stack[self.depth as usize] = Frame::Obj {
schema_idx,
seen_mask: 0,
items: 0,
};
self.depth += 1;
let has_req = schema_idx != NO_SCHEMA
&& !arena.schemas[schema_idx as usize].required_satisfied(0);
self.phase = if has_req {
Phase::ObjExpectKey
} else {
Phase::ObjExpectKeyOrEnd
};
true
}
fn push_arr(&mut self) -> bool {
if self.depth as usize >= MAX_DEPTH_CAP {
return false;
}
self.stack[self.depth as usize] = Frame::Arr { items: 0 };
self.depth += 1;
self.phase = Phase::ArrExpectValOrEnd;
true
}
fn pop_container(&mut self) {
self.depth -= 1;
self.stack[self.depth as usize] = Frame::Empty;
if self.depth == 0 {
self.phase = Phase::Complete;
} else {
self.phase = Phase::AfterValue;
}
}
fn begin_key(&mut self, arena: &SchemaArena) -> bool {
let Frame::Obj {
schema_idx,
seen_mask,
items,
} = self.top()
else {
return false;
};
let next_items = items.saturating_add(1);
*self.top_mut() = Frame::Obj {
schema_idx,
seen_mask,
items: next_items,
};
self.str_sub = StrSubState::new();
if schema_idx == NO_SCHEMA {
self.phase = Phase::InKey(KeyMode::Free {
schema_idx: NO_SCHEMA,
cand_mask: 0,
pos: 0,
});
return true;
}
let schema = &arena.schemas[schema_idx as usize];
let unseen = schema.unseen_mask(seen_mask);
if !schema.required_satisfied(seen_mask) || !schema.allow_additional {
if unseen == 0 {
return false;
}
self.phase = Phase::InKey(KeyMode::Restricted {
schema_idx,
cand_mask: unseen,
pos: 0,
});
true
} else {
self.phase = Phase::InKey(KeyMode::Free {
schema_idx,
cand_mask: unseen,
pos: 0,
});
true
}
}
fn start_value(&mut self, b: u8, mut spec: PropValueSpec, arena: &SchemaArena, limits: GrammarLimits) -> bool {
if is_json_ws(b) {
return self.accept_ws(limits);
}
self.ws_run = 0;
if self.depth >= limits.max_depth {
spec.mask = spec.mask.without_containers_if_possible();
}
match b {
b'{' if spec.mask.contains(TypeMask::OBJ) => self.push_obj(spec.nested_schema, arena),
b'[' if spec.mask.contains(TypeMask::ARR) => self.push_arr(),
b'"' if spec.mask.contains(TypeMask::STR) => {
self.str_sub = StrSubState::new();
if spec.fixed_str != NO_FIXED_STR {
self.phase = Phase::InString(StrMode::Fixed {
fixed_str: spec.fixed_str,
pos: 0,
});
} else {
self.phase = Phase::InString(StrMode::Free);
}
true
}
b'-' if spec.mask.contains(TypeMask::NUM) || spec.mask.contains(TypeMask::INT) => {
self.phase = Phase::InNumber(NumStage::Sign);
true
}
b'0' if spec.mask.contains(TypeMask::NUM) || spec.mask.contains(TypeMask::INT) => {
self.phase = Phase::InNumber(NumStage::Zero);
true
}
b'1'..=b'9' if spec.mask.contains(TypeMask::NUM) || spec.mask.contains(TypeMask::INT) => {
self.phase = Phase::InNumber(NumStage::Int { digits: 1 });
true
}
b't' if spec.mask.contains(TypeMask::BOOL) => {
self.phase = Phase::InLit {
target: *b"true\0",
len: 4,
pos: 1,
};
true
}
b'f' if spec.mask.contains(TypeMask::BOOL) => {
self.phase = Phase::InLit {
target: *b"false",
len: 5,
pos: 1,
};
true
}
b'n' if spec.mask.contains(TypeMask::NULL) => {
self.phase = Phase::InLit {
target: *b"null\0",
len: 4,
pos: 1,
};
true
}
_ => false,
}
}
fn step_after_value(&mut self, b: u8, arena: &SchemaArena, limits: GrammarLimits) -> bool {
if is_json_ws(b) {
return self.accept_ws(limits);
}
self.ws_run = 0;
match self.top() {
Frame::Obj {
schema_idx,
seen_mask,
items,
} => {
let (req_ok, more_ok) = if schema_idx == NO_SCHEMA {
(true, items < limits.max_container_items)
} else {
let s = &arena.schemas[schema_idx as usize];
let req_sat = s.required_satisfied(seen_mask);
let more = if !req_sat {
s.unseen_mask(seen_mask) != 0
} else {
items < limits.max_container_items && s.can_add_more_keys(seen_mask)
};
(req_sat, more)
};
match b {
b',' if more_ok => {
self.phase = Phase::ObjExpectKey;
true
}
b'}' if req_ok => {
self.pop_container();
true
}
_ => false,
}
}
Frame::Arr { items } => match b {
b',' if items < limits.max_container_items => {
self.phase = Phase::ArrExpectVal;
true
}
b']' => {
self.pop_container();
true
}
_ => false,
},
Frame::Empty => false,
}
}
fn step_byte(&mut self, b: u8, arena: &SchemaArena, limits: GrammarLimits) -> bool {
match self.phase {
Phase::BeforeRoot => {
if is_json_ws(b) {
return self.accept_ws(limits);
}
if b == b'{' {
self.ws_run = 0;
return self.push_obj(self.root_schema, arena);
}
false
}
Phase::ObjExpectKeyOrEnd => {
if is_json_ws(b) {
return self.accept_ws(limits);
}
self.ws_run = 0;
if b == b'}' {
let Frame::Obj {
schema_idx,
seen_mask,
..
} = self.top()
else {
return false;
};
if schema_idx != NO_SCHEMA
&& !arena.schemas[schema_idx as usize].required_satisfied(seen_mask)
{
return false;
}
self.pop_container();
return true;
}
if b == b'"' {
let can_key = match self.top() {
Frame::Obj {
schema_idx,
seen_mask,
items,
} => {
items < limits.max_container_items
&& (schema_idx == NO_SCHEMA
|| arena.schemas[schema_idx as usize].can_add_more_keys(seen_mask))
}
_ => false,
};
return can_key && self.begin_key(arena);
}
false
}
Phase::ObjExpectKey => {
if is_json_ws(b) {
return self.accept_ws(limits);
}
if b == b'"' {
self.ws_run = 0;
return self.begin_key(arena);
}
false
}
Phase::InKey(mode) => match mode {
KeyMode::Restricted {
schema_idx,
cand_mask,
pos,
} => {
let schema = &arena.schemas[schema_idx as usize];
let pos_usize = pos as usize;
if b == b'"' {
let mut matched_idx: Option<usize> = None;
let mut m = cand_mask;
while m != 0 {
let j = m.trailing_zeros() as usize;
m &= m - 1;
if schema.props[j].escaped.len() == pos_usize {
matched_idx = Some(j);
break;
}
}
if let Some(j) = matched_idx {
if let Frame::Obj { seen_mask, .. } = self.top_mut() {
*seen_mask |= 1u64 << j;
}
self.phase = Phase::ObjExpectColon(schema.props[j].spec);
return true;
}
}
let mut next_mask = 0u64;
let mut m = cand_mask;
while m != 0 {
let j = m.trailing_zeros() as usize;
m &= m - 1;
if schema.props[j].escaped.get(pos_usize) == Some(&b) {
next_mask |= 1u64 << j;
}
}
if next_mask == 0 || pos == u16::MAX {
return false;
}
self.phase = Phase::InKey(KeyMode::Restricted {
schema_idx,
cand_mask: next_mask,
pos: pos + 1,
});
true
}
KeyMode::Free {
schema_idx,
cand_mask,
pos,
} => match self.str_sub.step(b, limits.max_string_bytes) {
StrStep::Invalid => false,
StrStep::Closed => {
let mut val_spec = PropValueSpec::any();
if schema_idx != NO_SCHEMA && cand_mask != 0 {
let schema = &arena.schemas[schema_idx as usize];
let pos_usize = pos as usize;
let mut m = cand_mask;
while m != 0 {
let j = m.trailing_zeros() as usize;
m &= m - 1;
if schema.props[j].escaped.len() == pos_usize {
if let Frame::Obj { seen_mask, .. } = self.top_mut() {
*seen_mask |= 1u64 << j;
}
val_spec = schema.props[j].spec;
break;
}
}
}
self.phase = Phase::ObjExpectColon(val_spec);
true
}
StrStep::Continue => {
let mut next_mask = 0u64;
if schema_idx != NO_SCHEMA && cand_mask != 0 && (pos as usize) < usize::from(u16::MAX) {
let schema = &arena.schemas[schema_idx as usize];
let pos_usize = pos as usize;
let mut m = cand_mask;
while m != 0 {
let j = m.trailing_zeros() as usize;
m &= m - 1;
if schema.props[j].escaped.get(pos_usize) == Some(&b) {
next_mask |= 1u64 << j;
}
}
}
self.phase = Phase::InKey(KeyMode::Free {
schema_idx,
cand_mask: next_mask,
pos: pos.saturating_add(1),
});
true
}
},
},
Phase::ObjExpectColon(spec) => {
if is_json_ws(b) {
return self.accept_ws(limits);
}
if b == b':' {
self.ws_run = 0;
self.phase = Phase::ExpectValue(spec);
return true;
}
false
}
Phase::ExpectValue(spec) => self.start_value(b, spec, arena, limits),
Phase::ArrExpectValOrEnd => {
if is_json_ws(b) {
return self.accept_ws(limits);
}
self.ws_run = 0;
if b == b']' {
self.pop_container();
return true;
}
if let Frame::Arr { items } = self.top_mut() {
if *items >= limits.max_container_items {
return false;
}
*items += 1;
}
self.start_value(b, PropValueSpec::any(), arena, limits)
}
Phase::ArrExpectVal => {
if is_json_ws(b) {
return self.accept_ws(limits);
}
self.ws_run = 0;
if let Frame::Arr { items } = self.top_mut() {
*items = items.saturating_add(1);
}
self.start_value(b, PropValueSpec::any(), arena, limits)
}
Phase::InString(mode) => match mode {
StrMode::Free => match self.str_sub.step(b, limits.max_string_bytes) {
StrStep::Continue => true,
StrStep::Closed => {
self.phase = Phase::AfterValue;
true
}
StrStep::Invalid => false,
},
StrMode::Fixed { fixed_str, pos } => {
let target = &arena.fixed_strings[fixed_str as usize];
let pos_usize = pos as usize;
if pos_usize == target.len() {
if b == b'"' {
self.phase = Phase::AfterValue;
true
} else {
false
}
} else if target[pos_usize] == b {
self.phase = Phase::InString(StrMode::Fixed {
fixed_str,
pos: pos + 1,
});
true
} else {
false
}
}
},
Phase::InNumber(mut stage) => {
if stage.step_digit_or_part(b) {
self.phase = Phase::InNumber(stage);
return true;
}
if !stage.is_complete() {
return false;
}
self.phase = Phase::AfterValue;
self.step_after_value(b, arena, limits)
}
Phase::InLit { target, len, pos } => {
if target[pos as usize] != b {
return false;
}
if pos + 1 == len {
self.phase = Phase::AfterValue;
} else {
self.phase = Phase::InLit {
target,
len,
pos: pos + 1,
};
}
true
}
Phase::AfterValue => self.step_after_value(b, arena, limits),
Phase::Complete => {
if is_json_ws(b) {
self.accept_ws(limits)
} else {
false
}
}
}
}
}
#[cfg(test)]
#[derive(Clone, Debug)]
pub struct JsonObjectGrammar {
arena: Arc<SchemaArena>,
state: AutoState,
limits: GrammarLimits,
}
#[cfg(test)]
impl JsonObjectGrammar {
pub fn new() -> Self {
Self {
arena: Arc::new(SchemaArena::default()),
state: AutoState::new(NO_SCHEMA),
limits: GrammarLimits::DEFAULT,
}
}
pub fn with_schema(schema: &Value) -> Self {
let mut arena = SchemaArena::default();
let root = arena.compile_object_schema(schema, 0);
Self {
arena: Arc::new(arena),
state: AutoState::new(root),
limits: GrammarLimits::DEFAULT,
}
}
pub fn with_limits(mut self, limits: GrammarLimits) -> Self {
self.limits = limits;
self
}
#[inline]
pub fn is_complete(&self) -> bool {
self.state.is_complete()
}
#[inline]
pub fn accepts_bytes(&self, bytes: &[u8]) -> bool {
let mut next = self.state;
for &b in bytes {
if !next.step_byte(b, &self.arena, self.limits) {
return false;
}
}
true
}
#[inline]
pub fn advance_bytes(&mut self, bytes: &[u8]) -> bool {
let mut next = self.state;
for &b in bytes {
if !next.step_byte(b, &self.arena, self.limits) {
return false;
}
}
self.state = next;
true
}
}
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Copy, Debug)]
enum SpanMode {
Idle,
Header,
Json(AutoState),
}
#[derive(Clone, Debug)]
pub struct ToolCallGrammar {
catalog: Arc<ToolCatalog>,
header_buf: Vec<u8>,
dynamic_arena: Option<SchemaArena>,
mode: SpanMode,
limits: GrammarLimits,
marks: Option<SpanMarks>,
hdr: (u32, u32),
body_open: bool,
header_draws: u64,
header_masked: u64,
marker_rewrites: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SpanMarks {
pub msg_model: u32,
pub c_think: u32,
pub c_text: u32,
pub c_tool: u32,
pub end: u32,
}
impl ToolCallGrammar {
pub fn new(catalog: Arc<ToolCatalog>) -> Self {
Self {
catalog,
header_buf: Vec::with_capacity(64),
dynamic_arena: None,
mode: SpanMode::Idle,
limits: GrammarLimits::DEFAULT,
marks: None,
hdr: (0, 0),
body_open: false,
header_draws: 0,
header_masked: 0,
marker_rewrites: 0,
}
}
pub fn with_marks(mut self, marks: SpanMarks) -> Self {
self.marks = Some(marks);
self
}
#[cfg(test)]
pub fn with_limits(mut self, limits: GrammarLimits) -> Self {
self.limits = limits;
self
}
#[inline]
pub fn is_in_json(&self) -> bool {
matches!(self.mode, SpanMode::Json(_))
}
#[inline]
pub fn is_in_masked_header(&self) -> bool {
self.catalog.mask && matches!(self.mode, SpanMode::Header)
}
#[inline]
pub fn is_constrained(&self) -> bool {
self.is_in_json() || self.is_in_masked_header()
}
#[inline]
pub fn header_draws(&self) -> u64 {
self.header_draws
}
#[inline]
pub fn header_masked(&self) -> u64 {
self.header_masked
}
#[inline]
pub fn marker_rewrites(&self) -> u64 {
self.marker_rewrites
}
pub fn note_header_draw(&mut self, top_refused: bool) {
if self.is_in_masked_header() {
self.header_draws += 1;
self.header_masked += u64::from(top_refused);
}
}
fn header_is_offered_name(&self) -> bool {
let (lo, hi) = (self.hdr.0 as usize, self.hdr.1 as usize);
lo < hi && self.catalog.names[lo].len() == self.header_buf.len()
}
pub fn committed_token(&mut self, tok: u32) -> u32 {
let Some(m) = self.marks else { return tok };
if tok != m.c_tool || !self.catalog.mask {
return tok;
}
let to = match self.mode {
SpanMode::Json(_) => return tok,
SpanMode::Header if self.header_is_offered_name() => return tok,
SpanMode::Header => m.c_text,
SpanMode::Idle if self.body_open => m.end,
SpanMode::Idle => m.msg_model,
};
self.marker_rewrites += 1;
to
}
fn header_allows(&self, token_id: u32, vocab: &VocabBytes) -> bool {
let Some(m) = self.marks else { return true };
let (lo, hi) = (self.hdr.0 as usize, self.hdr.1 as usize);
let pos = self.header_buf.len();
if token_id == m.c_tool {
return self.header_is_offered_name();
}
if token_id == m.c_text || token_id == m.c_think {
return pos == 0 || lo == hi;
}
let Some(bytes) = vocab.non_special_bytes(token_id) else {
return false;
};
!bytes.is_empty() && lo < hi && self.catalog.continues(lo, hi, pos, bytes)
}
#[inline]
fn idle_allows(&self, token_id: u32) -> bool {
!(self.catalog.mask && self.marks.is_some_and(|m| m.c_tool == token_id))
}
#[inline]
fn active_arena(&self) -> &SchemaArena {
self.dynamic_arena.as_ref().unwrap_or(&self.catalog.arena)
}
#[inline]
pub fn allows_token(&self, token_id: u32, vocab: &VocabBytes, end_tok: u32) -> bool {
let state = match &self.mode {
SpanMode::Json(state) => state,
SpanMode::Header if self.catalog.mask => return self.header_allows(token_id, vocab),
SpanMode::Header => return true,
SpanMode::Idle => return self.idle_allows(token_id),
};
if token_id == end_tok {
return state.is_complete();
}
let Some(bytes) = vocab.non_special_bytes(token_id) else {
return false;
};
if bytes.is_empty() {
return false;
}
let arena = self.active_arena();
let b0 = bytes[0];
match state.phase {
Phase::Complete => {
return vocab.is_json_ws_token(token_id)
&& (state.ws_run as usize) + bytes.len() <= (self.limits.max_ws_run as usize);
}
Phase::InString(StrMode::Free) | Phase::InKey(KeyMode::Free { .. }) => {
if state.str_sub.utf8_need == 0 && state.str_sub.esc == EscState::None {
if vocab.is_str_interior(token_id)
&& u64::from(state.str_sub.byte_len) + bytes.len() as u64
<= u64::from(self.limits.max_string_bytes)
{
return true;
}
if vocab.is_str_invalid_fresh(token_id) {
return false;
}
}
}
Phase::BeforeRoot => {
if !is_json_ws(b0) && b0 != b'{' {
return false;
}
}
Phase::ObjExpectKeyOrEnd => {
if !is_json_ws(b0) && b0 != b'}' && b0 != b'"' {
return false;
}
}
Phase::ObjExpectKey => {
if !is_json_ws(b0) && b0 != b'"' {
return false;
}
}
Phase::ObjExpectColon(_) => {
if !is_json_ws(b0) && b0 != b':' {
return false;
}
}
Phase::AfterValue => {
if !is_json_ws(b0) && !matches!(b0, b',' | b'}' | b']') {
return false;
}
}
Phase::ExpectValue(_) | Phase::ArrExpectVal => {
if !is_json_ws(b0)
&& !matches!(b0, b'{' | b'[' | b'"' | b'-' | b'0'..=b'9' | b't' | b'f' | b'n')
{
return false;
}
}
Phase::ArrExpectValOrEnd => {
if !is_json_ws(b0)
&& !matches!(
b0,
b']' | b'{' | b'[' | b'"' | b'-' | b'0'..=b'9' | b't' | b'f' | b'n'
)
{
return false;
}
}
Phase::InLit { target, pos, .. } => {
if b0 != target[pos as usize] {
return false;
}
}
Phase::InString(StrMode::Fixed { fixed_str, pos }) => {
let target = &arena.fixed_strings[fixed_str as usize];
let expected = if (pos as usize) == target.len() {
b'"'
} else {
target[pos as usize]
};
if b0 != expected {
return false;
}
}
Phase::InNumber(stage) => {
let mut probe = stage;
if !probe.step_digit_or_part(b0)
&& !(stage.is_complete()
&& (is_json_ws(b0) || matches!(b0, b',' | b'}' | b']')))
{
return false;
}
}
Phase::InKey(KeyMode::Restricted {
schema_idx,
cand_mask,
pos,
}) => {
if b0 != b'"' {
let schema = &arena.schemas[schema_idx as usize];
let pos_usize = pos as usize;
let mut m = cand_mask;
let mut any = false;
while m != 0 {
let j = m.trailing_zeros() as usize;
m &= m - 1;
if schema.props[j].escaped.get(pos_usize) == Some(&b0) {
any = true;
break;
}
}
if !any {
return false;
}
}
}
}
let mut next = *state;
for &b in bytes {
if !next.step_byte(b, arena, self.limits) {
return false;
}
}
true
}
#[cfg(test)]
fn allows_token_ref(&self, token_id: u32, vocab: &VocabBytes, end_tok: u32) -> bool {
let state = match &self.mode {
SpanMode::Json(state) => state,
SpanMode::Header if self.catalog.mask => return self.header_allows(token_id, vocab),
SpanMode::Header => return true,
SpanMode::Idle => return self.idle_allows(token_id),
};
if token_id == end_tok {
return state.is_complete();
}
let Some(bytes) = vocab.non_special_bytes(token_id) else {
return false;
};
if bytes.is_empty() {
return false;
}
let arena = self.active_arena();
let mut next = *state;
for &b in bytes {
if !next.step_byte(b, arena, self.limits) {
return false;
}
}
true
}
#[allow(clippy::too_many_arguments)]
pub fn observe_token(
&mut self,
tok: u32,
vocab: &VocabBytes,
msg_model_tok: u32,
c_think_tok: u32,
c_text_tok: u32,
c_tool_tok: u32,
end_tok: u32,
end_sampling_tok: u32,
eos_tok: u32,
) {
self.marks = Some(SpanMarks {
msg_model: msg_model_tok,
c_think: c_think_tok,
c_text: c_text_tok,
c_tool: c_tool_tok,
end: end_tok,
});
if tok == msg_model_tok {
self.header_buf.clear();
self.dynamic_arena = None;
self.mode = SpanMode::Header;
self.hdr = (0, self.catalog.names.len() as u32);
self.body_open = false;
return;
}
if tok == c_think_tok
|| tok == c_text_tok
|| tok == end_tok
|| tok == end_sampling_tok
|| tok == eos_tok
{
self.header_buf.clear();
self.dynamic_arena = None;
self.mode = SpanMode::Idle;
self.body_open = tok == c_think_tok || tok == c_text_tok;
return;
}
if tok == c_tool_tok {
self.dynamic_arena = None;
self.body_open = false;
let cat = Arc::clone(&self.catalog);
let trimmed = std::str::from_utf8(&self.header_buf).map(str::trim).unwrap_or("");
let named = if cat.mask {
self.header_is_offered_name().then_some(self.hdr.0 as usize)
} else {
cat.find(&self.header_buf).or_else(|| cat.find(trimmed.as_bytes()))
};
let mut fixed_name_wrapper = |name: &str| {
let mut dyn_arena = SchemaArena::default();
let root = dyn_arena.build_tool_wrapper_schema(Some(name), NO_SCHEMA);
self.dynamic_arena = Some(dyn_arena);
root
};
let root_schema = match named {
Some(i) if cat.name_wrappers[i] != NO_SCHEMA => cat.name_wrappers[i],
Some(i) => fixed_name_wrapper(std::str::from_utf8(&cat.names[i]).unwrap_or("")),
None if !cat.mask && !trimmed.is_empty() => fixed_name_wrapper(trimmed),
None => {
debug_assert!(!cat.mask, "a tool marker was committed away from an offered header");
cat.fallback_wrapper_schema
}
};
self.mode = SpanMode::Json(AutoState::new(root_schema));
return;
}
match &mut self.mode {
SpanMode::Idle => {}
SpanMode::Header => {
if let Some(bytes) = vocab.non_special_bytes(tok) {
if self.catalog.mask {
let (lo, hi) = (self.hdr.0 as usize, self.hdr.1 as usize);
if lo < hi {
let (lo, hi) = self.catalog.narrow(lo, hi, self.header_buf.len(), bytes);
self.hdr = (lo as u32, hi as u32);
}
}
if self.header_buf.len() + bytes.len() <= self.catalog.header_cap {
self.header_buf.extend_from_slice(bytes);
}
}
}
SpanMode::Json(state) => {
if let Some(bytes) = vocab.non_special_bytes(tok) {
let arena_ptr: *const SchemaArena =
self.dynamic_arena.as_ref().unwrap_or(&self.catalog.arena);
let arena = unsafe { &*arena_ptr };
let mut next = *state;
for &b in bytes {
let ok = next.step_byte(b, arena, self.limits);
debug_assert!(ok, "observed token violated active ToolCallGrammar");
if !ok {
break;
}
}
*state = next;
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sampler::Sampler;
use serde_json::json;
#[test]
fn accepts_valid_nested_json_escapes_surrogates_and_utf8_across_splits() {
let valid = r#" {
"str": "hello \"world\" \\ \/ \b\f\n\r\t \u0041 \uD83D\uDE80 café 日本語",
"nums": [0, -0, 42, -17, 3.14159, -0.001, 1e9, 2.5E-4, -9e+12],
"lits": [true, false, null],
"nested": {"empty_obj": {}, "empty_arr": [], "deep": [{"k": "v"}]}
} "#;
let bytes = valid.as_bytes();
for step in [1usize, 2, 3, 5, 7] {
let mut g = JsonObjectGrammar::new();
for chunk in bytes.chunks(step) {
assert!(!g.is_complete() || chunk.iter().all(|&b| is_json_ws(b)));
assert!(g.advance_bytes(chunk), "rejected valid chunk {chunk:?} (step={step})");
}
assert!(g.is_complete(), "expected complete JSON at step={step}");
}
let parsed: Value = serde_json::from_str(valid).unwrap();
assert_eq!(parsed["nested"]["deep"][0]["k"], "v");
let schema = json!({"type": "object", "properties": {"a": {"type": "integer"}}, "required": ["a"]});
let schema_g = JsonObjectGrammar::with_schema(&schema).with_limits(GrammarLimits::DEFAULT);
assert!(schema_g.accepts_bytes(br#"{"a": 1}"#));
assert!(!schema_g.accepts_bytes(br#"{"a": "bad"}"#));
}
#[test]
fn rejects_malformed_json_and_invalid_utf8_or_surrogates() {
let invalid_cases: &[(&str, &[u8])] = &[
("unquoted key", br#"{foo: 1}"#),
("single-quoted string", br#"{"a": 'hi'}"#),
("trailing comma in object", br#"{"a": 1,}"#),
("trailing comma in array", br#"{"a": [1, 2,]}"#),
("double comma", br#"{"a": [1,,2]}"#),
("leading zero integer", br#"{"a": 01}"#),
("negative leading zero", br#"{"a": -01}"#),
("bare decimal point", br#"{"a": .5}"#),
("trailing decimal point", br#"{"a": 1.}"#),
("incomplete exponent", br#"{"a": 1e}"#),
("raw newline in string", b"{\"a\": \"line1\nline2\"}"),
("raw nul in string", b"{\"a\": \"bad\x00\"}"),
("bad escape", br#"{"a": "\x41"}"#),
("lone low surrogate", br#"{"a": "\uDC00"}"#),
("high surrogate without low", br#"{"a": "\uD83Dx"}"#),
("high surrogate followed by high", br#"{"a": "\uD83D\uD83D"}"#),
("overlong utf8 C0", b"{\"a\": \"\xC0\xAF\"}"),
("surrogate utf8 ED A0 80", b"{\"a\": \"\xED\xA0\x80\"}"),
("out of range utf8 F4 90 80 80", b"{\"a\": \"\xF4\x90\x80\x80\"}"),
("root array instead of object", br#"[1, 2, 3]"#),
("extra brace after root", br#"{"a": 1}}"#),
("concatenated objects", br#"{"a": 1}{"b": 2}"#),
];
for &(label, case) in invalid_cases {
let mut g = JsonObjectGrammar::new();
let accepted_all = g.advance_bytes(case);
assert!(
!accepted_all || !g.is_complete(),
"grammar should reject {label}: {:?}",
String::from_utf8_lossy(case)
);
}
for incomplete in [
br#"{"#.as_slice(),
br#"{"a""#.as_slice(),
br#"{"a":"#.as_slice(),
br#"{"a": 1"#.as_slice(),
br#"{"a": [1, 2"#.as_slice(),
br#"{"a": tru"#.as_slice(),
br#"{"a": 1."#.as_slice(),
] {
let mut g = JsonObjectGrammar::new();
assert!(g.advance_bytes(incomplete));
assert!(!g.is_complete(), "unclosed input marked complete: {:?}", String::from_utf8_lossy(incomplete));
}
}
#[test]
fn enforces_tool_schema_required_keys_types_and_end_token_boundary() {
let tk = Tokenizer::for_byte_test();
let vocab = VocabBytes::from_tokenizer(&tk);
let msg_model = tk.encode("<|message_model|>", true)[0];
let c_think = tk.encode("<|content_thinking|>", true)[0];
let c_text = tk.encode("<|content_text|>", true)[0];
let c_tool = tk.encode("<|content_invoke_tool_json|>", true)[0];
let end = tk.encode("<|end_message|>", true)[0];
let end_sampling = tk.encode("<|content_model_end_sampling|>", true)[0];
let req = json!({
"tools": [{
"type": "function",
"function": {
"name": "get_weather",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"},
"days": {"type": "integer"}
},
"required": ["city"],
"additionalProperties": false
}
}
}]
});
let catalog = ToolCatalog::from_request(&req).unwrap();
let mut g = ToolCallGrammar::new(catalog);
assert!(!g.is_in_json());
let step = |g: &mut ToolCallGrammar, tok: u32| {
g.observe_token(tok, &vocab, msg_model, c_think, c_text, c_tool, end, end_sampling, tk.eos);
};
step(&mut g, msg_model);
for tok in tk.encode("get_weather", false) {
step(&mut g, tok);
}
assert!(!g.is_in_json());
step(&mut g, c_tool);
assert!(g.is_in_json());
assert!(!g.allows_token(end, &vocab, end), "premature <|end_message|> before JSON must be blocked");
for tok in tk.encode(r#"{"name":"get_weather","args":{"#, false) {
assert!(g.allows_token(tok, &vocab, end));
step(&mut g, tok);
}
let close_brace = tk.encode("}", false)[0];
assert!(!g.allows_token(close_brace, &vocab, end), "closing args before required 'city' must be rejected");
for tok in tk.encode(r#""days":"#, false) {
assert!(g.allows_token(tok, &vocab, end));
step(&mut g, tok);
}
let quote_tok = tk.encode("\"", false)[0];
assert!(!g.allows_token(quote_tok, &vocab, end), "string value for integer property 'days' must be rejected");
for tok in tk.encode("3", false) {
assert!(g.allows_token(tok, &vocab, end));
step(&mut g, tok);
}
let dot_tok = tk.encode(".", false)[0];
assert!(g.allows_token(dot_tok, &vocab, end), "decimal point after an integer field's digits stays open");
assert!(!g.allows_token(close_brace, &vocab, end), "still missing required 'city'");
for tok in tk.encode(r#","city":"Seattle"}"#, false) {
assert!(g.allows_token(tok, &vocab, end));
step(&mut g, tok);
assert!(!g.allows_token(end, &vocab, end), "<|end_message|> must remain blocked before outer '}}'");
}
assert!(g.allows_token(close_brace, &vocab, end));
step(&mut g, close_brace);
assert!(g.allows_token(end, &vocab, end), "<|end_message|> must unlock once outer JSON object completes");
step(&mut g, end);
assert!(!g.is_in_json(), "grammar must reset to idle after <|end_message|>");
}
#[test]
fn hundred_of_hundred_adversarial_random_logit_tool_calls_parse_valid_json() {
let tk = Tokenizer::for_byte_test();
let vocab = VocabBytes::from_tokenizer(&tk);
let msg_model = tk.encode("<|message_model|>", true)[0];
let c_think = tk.encode("<|content_thinking|>", true)[0];
let c_text = tk.encode("<|content_text|>", true)[0];
let c_tool = tk.encode("<|content_invoke_tool_json|>", true)[0];
let end = tk.encode("<|end_message|>", true)[0];
let end_sampling = tk.encode("<|content_model_end_sampling|>", true)[0];
let req = json!({
"tools": [{
"type": "function",
"function": {
"name": "search_repo",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string"},
"max_results": {"type": "integer"},
"case_sensitive": {"type": "boolean"},
"filters": {"type": "object"}
},
"required": ["query", "max_results"]
}
}
}]
});
let catalog = ToolCatalog::from_request(&req).unwrap();
let vocab_len = tk.vocab_len();
let mut logits = vec![0.0f32; vocab_len];
let traps: Vec<u32> = [
end,
msg_model,
c_tool,
tk.eos,
tk.encode(",", false)[0],
tk.encode("}", false)[0],
tk.encode("]", false)[0],
tk.encode(":", false)[0],
tk.encode("\\", false)[0],
tk.encode("0", false)[0],
tk.encode(".", false)[0],
tk.encode("\n", false)[0],
tk.encode("\x00", false)[0],
]
.into_iter()
.collect();
let mut rng_state = 0xD1CE_CAFE_BAAD_F00Du64;
let mut next_f32 = || -> f32 {
rng_state ^= rng_state >> 12;
rng_state ^= rng_state << 25;
rng_state ^= rng_state >> 27;
let u = rng_state.wrapping_mul(0x2545F4914F6CDD1D) >> 40;
(u as f32 / ((1u32 << 24) as f32)) * 8.0 - 4.0
};
let mut refused = 0;
for trial in 0..100u64 {
let mut g = ToolCallGrammar::new(catalog.clone()).with_limits(GrammarLimits::adversarial_test());
g.observe_token(msg_model, &vocab, msg_model, c_think, c_text, c_tool, end, end_sampling, tk.eos);
for tok in tk.encode("search_repo", false) {
g.observe_token(tok, &vocab, msg_model, c_think, c_text, c_tool, end, end_sampling, tk.eos);
}
g.observe_token(c_tool, &vocab, msg_model, c_think, c_text, c_tool, end, end_sampling, tk.eos);
let temp = if trial % 5 == 0 { 0.0 } else { 1.1 };
let mut sampler = Sampler::new(temp, 64, 0.98, 0.0, 10_000 + trial);
let mut emitted_bytes = Vec::new();
let mut finished_with_end = false;
for step_idx in 0..2048usize {
for x in logits.iter_mut() {
*x = next_f32();
}
if trial % 2 == 1 {
for &trap in &traps {
logits[trap as usize] = 18.0 + (step_idx % 5) as f32;
}
}
let tok = sampler
.sample_next_filtered(&logits, None, 0.0, |id| g.allows_token(id, &vocab, end))
.unwrap_or_else(|e| panic!("trial {trial} step {step_idx} failed to sample: {e}"));
g.observe_token(tok, &vocab, msg_model, c_think, c_text, c_tool, end, end_sampling, tk.eos);
if tok == end {
finished_with_end = true;
break;
}
emitted_bytes.extend_from_slice(&tk.decode_bytes(tok));
}
assert!(finished_with_end, "trial {trial} did not reach <|end_message|>; partial={:?}", String::from_utf8_lossy(&emitted_bytes));
let body_str = std::str::from_utf8(&emitted_bytes)
.unwrap_or_else(|e| panic!("trial {trial} emitted invalid UTF-8 {emitted_bytes:?}: {e}"));
serde_json::from_str::<Value>(&zero_numbers(body_str))
.unwrap_or_else(|e| panic!("trial {trial} emitted invalid JSON {body_str:?}: {e}"));
let parsed = read_call_body(body_str);
if parsed.is_null() {
refused += 1;
continue;
}
assert_eq!(
parsed.get("name").and_then(Value::as_str).unwrap_or("search_repo"),
"search_repo",
"trial {trial}: unexpected tool name in {parsed}"
);
let args = parsed
.get("args")
.and_then(Value::as_object)
.unwrap_or_else(|| panic!("trial {trial}: missing args object in {parsed}"));
assert!(args.get("query").and_then(Value::as_str).is_some(), "trial {trial}: missing string 'query' in {parsed}");
assert!(args.get("max_results").is_some_and(Value::is_number), "trial {trial}: missing number 'max_results' in {parsed}");
}
assert!(refused <= 20, "{refused} of 100 adversarial calls refused for a number");
}
fn zero_numbers(body: &str) -> String {
let (b, mut out, mut i) = (body.as_bytes(), Vec::new(), 0);
while i < b.len() {
if b[i] == b'"' {
let start = i;
i += 1;
while i < b.len() && b[i] != b'"' {
i += if b[i] == b'\\' { 2 } else { 1 };
}
i = (i + 1).min(b.len());
out.extend_from_slice(&b[start..i]);
} else if matches!(b[i], b'-' | b'0'..=b'9') {
while i < b.len() && matches!(b[i], b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-') {
i += 1;
}
out.push(b'0');
} else {
out.push(b[i]);
i += 1;
}
}
String::from_utf8(out).unwrap()
}
#[test]
fn restricted_key_with_escaped_quote_and_rfc8259_numbers() {
let accepts_full = |g: &JsonObjectGrammar, s: &str| {
let mut c = g.clone();
c.advance_bytes(s.as_bytes()) && c.is_complete()
};
let schema: Value = serde_json::json!({
"type": "object",
"properties": {
"a\"b": { "type": "string" }
},
"required": ["a\"b"],
"additionalProperties": false
});
let g = JsonObjectGrammar::with_schema(&schema);
assert!(accepts_full(&g, r#"{"a\"b":"ok"}"#), "escaped quote inside restricted key must be accepted");
assert!(!accepts_full(&g, r#"{"a":"ok"}"#), "unmatched prefix must still be rejected");
let num_schema: Value = serde_json::json!({
"type": "object",
"properties": {
"n": { "type": "integer" },
"x": { "type": "number" }
},
"required": ["n", "x"],
"additionalProperties": false
});
let ng = JsonObjectGrammar::with_schema(&num_schema);
assert!(accepts_full(&ng, r#"{"n":0,"x":1e100}"#));
assert!(accepts_full(&ng, r#"{"n":-42,"x":1e-308}"#));
assert!(accepts_full(&ng, r#"{"n":0,"x":-0}"#), "number fields accept -0");
assert!(accepts_full(&ng, r#"{"n":-0,"x":1}"#), "integer fields take -0 (read_call_body sends it as 0)");
assert!(accepts_full(&ng, r#"{"n":-0.0,"x":1}"#), "integer fields take number syntax");
assert!(!accepts_full(&ng, r#"{"n":-01,"x":1}"#), "integer must still reject leading zero -01");
}
#[test]
fn vocab_bitsets_and_fast_path_match_reference_across_all_phases() {
const END_TOK: u32 = 0;
const MSG_MODEL: u32 = 1;
const C_TOOL: u32 = 2;
const C_TEXT: u32 = 3;
const C_THINK: u32 = 4;
const END_SAMP: u32 = 5;
const EOS: u32 = 6;
let entries: Vec<Option<&[u8]>> = vec![
None, None, None, None, None, None, None, Some(b""), Some(b" "), Some(b" \t\r\n"), Some(b" \n"), Some(b"{"), Some(b"}"), Some(b"["), Some(b"]"), Some(b":"), Some(b","), Some(b"\""), Some(b"hello"), Some(b"a\"b"), Some(b"ok\"}"), Some(b"ok\","), Some(b"ok\":"), Some(b"\\n"), Some(b"\\\""), Some(b"\\"), Some(b"\\x"), Some(b"\\u"), Some(b"\\u0041"), Some(b"\\uD83D"), Some(b"\\uD83D\\uDE80"), Some(b"\\uDC00"), Some(b"\\uD83D\\u0041"), Some(b"\x00"), Some(b"abc\x1fdef"), Some(b"\"\x00"), Some("é".as_bytes()), Some("🚀".as_bytes()), Some(&[0xC3]), Some(&[0xA9]), Some(&[0xC0, 0xAF]), Some(&[0xED, 0xA0, 0x80]), Some(&[0xF4, 0x90, 0x80, 0x80]), Some(b"0"), Some(b"1"), Some(b"-"), Some(b"-0"), Some(b"-42"), Some(b".5"), Some(b"e+10"), Some(b"true"), Some(b"tr"), Some(b"ue"), Some(b"false"), Some(b"null"), Some(b"name"), Some(b"args"), Some(b"query"), Some(b"n"), Some(b"x"), Some(b"arr"), Some(b"flag"), Some(b"extra"), Some(b"my_tool"), Some(b"my_"), Some(b"tool"), Some(b"\"name\":\"my_tool\""), Some(b"{\"name\":\"my_tool\","), Some(b" }"), Some(b" ]"), Some(b"123}"), Some(b"123,"), Some(b"123 "), Some(b"123abc"), Some(b"\"key\":1"), Some(b"0041"), Some(b"\\uDE80"), ];
let vocab = VocabBytes::from_test_entries(&entries);
assert!(!vocab.is_json_ws_token(0));
assert!(!vocab.is_json_ws_token(7));
assert!(vocab.is_json_ws_token(8));
assert!(vocab.is_json_ws_token(9));
assert!(vocab.is_json_ws_token(10));
assert!(!vocab.is_json_ws_token(68));
assert!(vocab.is_str_interior(18));
assert!(vocab.is_str_interior(23));
assert!(vocab.is_str_interior(25));
assert!(vocab.is_str_interior(29));
assert!(vocab.is_str_interior(30));
assert!(vocab.is_str_interior(36));
assert!(vocab.is_str_interior(37));
assert!(vocab.is_str_interior(38));
assert!(!vocab.is_str_interior(17));
assert!(!vocab.is_str_interior(19));
assert!(!vocab.is_str_interior(26));
assert!(!vocab.is_str_interior(35));
assert!(vocab.is_str_invalid_fresh(26));
assert!(vocab.is_str_invalid_fresh(31));
assert!(vocab.is_str_invalid_fresh(32));
assert!(vocab.is_str_invalid_fresh(33));
assert!(vocab.is_str_invalid_fresh(34));
assert!(vocab.is_str_invalid_fresh(39));
assert!(vocab.is_str_invalid_fresh(40));
assert!(vocab.is_str_invalid_fresh(41));
assert!(vocab.is_str_invalid_fresh(42));
assert!(!vocab.is_str_invalid_fresh(35));
let req = serde_json::json!({
"tools": [{
"type": "function",
"function": {
"name": "my_tool",
"parameters": {
"type": "object",
"properties": {
"query": { "type": "string" },
"n": { "type": "integer" },
"x": { "type": "number" },
"arr": { "type": "array" },
"flag": { "type": "boolean" },
"extra": { "type": "object", "additionalProperties": true }
},
"required": ["query", "n"]
}
}
}]
});
let catalog = ToolCatalog::from_request(&req).expect("tool catalog");
let check_all = |g: &ToolCallGrammar, label: &str| {
for id in 0..=(entries.len() as u32 + 2) {
let got = g.allows_token(id, &vocab, END_TOK);
let exp = g.allows_token_ref(id, &vocab, END_TOK);
assert_eq!(got, exp, "mismatch at state {label:?} for token id={id}");
}
};
let limits = GrammarLimits {
max_depth: 6,
max_container_items: 8,
max_string_bytes: 8,
max_ws_run: 4,
};
let mut g = ToolCallGrammar::new(Arc::clone(&catalog)).with_limits(limits);
check_all(&g, "idle");
g.observe_token(MSG_MODEL, &vocab, MSG_MODEL, C_THINK, C_TEXT, C_TOOL, END_TOK, END_SAMP, EOS);
check_all(&g, "header_empty");
g.observe_token(63, &vocab, MSG_MODEL, C_THINK, C_TEXT, C_TOOL, END_TOK, END_SAMP, EOS);
check_all(&g, "header_named");
let prefixes: &[(&str, &[u8])] = &[
("before_root", b""),
("before_root_ws", b" "),
("before_root_ws_full", b" "),
("obj_expect_key_or_end", b"{"),
("in_key_restricted_0", b"{\""),
("in_key_restricted_1", b"{\"na"),
("in_key_restricted_full", b"{\"name"),
("obj_expect_colon", b"{\"name\""),
("expect_value_fixed_str", b"{\"name\":"),
("in_str_fixed_0", b"{\"name\":\""),
("in_str_fixed_mid", b"{\"name\":\"my_"),
("in_str_fixed_end", b"{\"name\":\"my_tool"),
("after_value_obj", b"{\"name\":\"my_tool\""),
("obj_expect_key", b"{\"name\":\"my_tool\","),
("args_obj", b"{\"name\":\"my_tool\",\"args\":{"),
("in_str_free_fresh", b"{\"name\":\"my_tool\",\"args\":{\"query\":\""),
("in_str_free_near_limit_7", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"1234567"),
("in_str_free_at_limit_8", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"12345678"),
("in_str_free_backslash", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\\"),
("in_str_free_hex", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"\\u00"),
("in_str_free_high_surrogate", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"\\uD83D"),
("in_str_free_partial_utf8", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"\xC3"),
("in_num_int_expect", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":"),
("in_num_int_sign", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":-"),
("in_num_int_zero", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":0"),
("in_num_int_digits", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":12"),
("in_num_float_sign", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"x\":-"),
("in_num_float_zero", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"x\":0"),
("in_num_float_dot", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"x\":0."),
("in_num_float_frac", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"x\":0.5"),
("in_num_float_exp_e", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"x\":1e"),
("in_num_float_exp_sign", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"x\":1e+"),
("in_num_float_exp_dig", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"x\":1e+2"),
("arr_expect_val_or_end", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"arr\":["),
("arr_after_val", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"arr\":[1"),
("arr_expect_val", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"arr\":[1,"),
("in_lit_true", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"flag\":tr"),
("in_lit_false", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"flag\":fa"),
("in_lit_null", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"arr\":[nu"),
("in_key_free_fresh", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"extra\":{\""),
("in_key_free_near_limit", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"extra\":{\"1234567"),
("in_key_free_backslash", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1,\"extra\":{\"a\\"),
("complete_ws_0", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1}}"),
("complete_ws_2", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1}} "),
("complete_ws_4", b"{\"name\":\"my_tool\",\"args\":{\"query\":\"a\",\"n\":1}} "),
];
for &(label, prefix) in prefixes {
let mut st = ToolCallGrammar::new(Arc::clone(&catalog)).with_limits(limits);
st.observe_token(MSG_MODEL, &vocab, MSG_MODEL, C_THINK, C_TEXT, C_TOOL, END_TOK, END_SAMP, EOS);
st.observe_token(63, &vocab, MSG_MODEL, C_THINK, C_TEXT, C_TOOL, END_TOK, END_SAMP, EOS);
st.observe_token(C_TOOL, &vocab, MSG_MODEL, C_THINK, C_TEXT, C_TOOL, END_TOK, END_SAMP, EOS);
if let SpanMode::Json(ref mut auto) = st.mode {
let arena = &catalog.arena;
for &b in prefix {
assert!(
auto.step_byte(b, arena, limits),
"prefix {label:?} failed at byte {b:#x}"
);
}
} else {
panic!("expected Json mode for {label}");
}
check_all(&st, label);
}
let mut edge = ToolCallGrammar::new(Arc::clone(&catalog)).with_limits(limits);
edge.observe_token(MSG_MODEL, &vocab, MSG_MODEL, C_THINK, C_TEXT, C_TOOL, END_TOK, END_SAMP, EOS);
edge.observe_token(63, &vocab, MSG_MODEL, C_THINK, C_TEXT, C_TOOL, END_TOK, END_SAMP, EOS);
edge.observe_token(C_TOOL, &vocab, MSG_MODEL, C_THINK, C_TEXT, C_TOOL, END_TOK, END_SAMP, EOS);
if let SpanMode::Json(ref mut auto) = edge.mode {
for &b in b"{\"name\":\"my_tool\",\"args\":{\"query\":\"1234567" {
assert!(auto.step_byte(b, &catalog.arena, limits));
}
}
assert!(edge.allows_token(23, &vocab, END_TOK));
assert!(edge.allows_token(36, &vocab, END_TOK));
assert!(!edge.allows_token(18, &vocab, END_TOK));
}
fn sent_number(field: &str, lit: &str) -> (Option<String>, bool) {
let g = JsonObjectGrammar::with_schema(&json!({
"type": "object",
"properties": {"x": {"type": "number"}, "n": {"type": "integer"}},
"additionalProperties": false
}));
let mut written = format!("{{\"{field}\":");
let mut c = g.clone();
assert!(c.advance_bytes(written.as_bytes()));
for &b in lit.as_bytes() {
let mut next = c.clone();
if !next.advance_bytes(&[b]) {
break;
}
c = next;
written.push(char::from(b));
}
let cut = written.len() - field.len() - 4 < lit.len();
assert!(c.advance_bytes(b"}") && c.is_complete(), "the grammar must let {written:?} close (from {lit:?})");
written.push('}');
let v = read_call_body(&written);
((!v.is_null()).then(|| serde_json::to_string(&v[field]).unwrap()), cut)
}
#[test]
fn boundary_numbers_reach_the_client_exactly_or_the_call_is_refused() {
enum Want {
Same,
Text(&'static str),
Refused,
}
use Want::*;
let table: &[(&str, Want)] = &[
("-9223372036854775809", Refused), ("-9223372036854775808", Same), ("-1", Same),
("-0", Text("0")), ("0", Same),
("9223372036854775807", Same), ("9223372036854775808", Same), ("1733100000000000000", Same), ("10000000000000000000", Same), ("18446744073709551615", Same), ("18446744073709551616", Refused), ("99999999999999999999", Refused), ("100000000000000000000", Refused), ("123456789012345678901234", Refused), ("1e308", Text("1e+308")),
("1.7976931348623157e308", Text("1.7976931348623157e+308")), ("1.7976931348623159e308", Refused), ("1e309", Refused),
("1e400", Refused),
("1e+0400", Refused),
("1e000400", Refused), ("1e-0308", Text("1e-308")),
("5e-324", Same), ("1e-324", Refused), ("1e-400", Refused),
("0e-400", Text("0.0")),
("-0.0", Same),
("0.1", Same),
("0.30000000000000004", Same),
("1.5e3", Text("1500.0")),
("2.5e-3", Text("0.0025")),
("0.12345678901234567890123456789012", Text("0.12345678901234568")), ("0.123456789012345678901234567890123", Refused), ("0.1234567890123456789012345678901234567890", Refused), ];
for (lit, want) in table {
for field in ["x", "n"] {
let (got, cut) = sent_number(field, lit);
match want {
Same => assert_eq!(got.as_deref(), Some(*lit), "{field}={lit}"),
Text(t) => assert_eq!(got.as_deref(), Some(*t), "{field}={lit}"),
Refused => assert_eq!(got, None, "{field}={lit} must be refused, not sent"),
}
assert!(!cut || got.is_none(), "{field}={lit}: a literal the grammar cut must never be sent");
}
}
}
#[test]
fn numbers_sent_match_serde_json_exactly_and_are_never_cut() {
let mut state = 0x9E37_79B9_7F4A_7C15u64;
let mut rnd = |n: u64| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state % n
};
let digits = |rnd: &mut dyn FnMut(u64) -> u64, n: u64, lead: bool| -> String {
(0..n)
.map(|i| char::from(b'0' + if i == 0 && lead { 1 + rnd(9) } else { rnd(10) } as u8))
.collect()
};
let edges = ["9223372036854775807", "9223372036854775808", "18446744073709551615", "18446744073709551616"];
let (mut sent, mut refused) = (0, 0);
for _ in 0..20_000 {
let mut lit = String::new();
if rnd(2) == 0 {
lit.push('-');
}
match rnd(8) {
0 => lit.push('0'),
1 => {
let e = edges[rnd(4) as usize];
let keep = e.len() - 1 - rnd(3) as usize;
lit.push_str(&e[..keep]);
lit.push_str(&digits(&mut rnd, (e.len() - keep) as u64, false));
}
_ => {
let n = 1 + rnd(24);
lit.push_str(&digits(&mut rnd, n, true));
}
}
if rnd(3) == 0 {
lit.push('.');
let n = 1 + rnd(40);
lit.push_str(&digits(&mut rnd, n, false));
}
if rnd(3) == 0 {
lit.push(['e', 'E'][rnd(2) as usize]);
lit.push_str(["", "+", "-"][rnd(3) as usize]);
let n = 1 + rnd(6);
lit.push_str(&digits(&mut rnd, n, false));
}
let field = ["x", "n"][rnd(2) as usize];
let (got, cut) = sent_number(field, &lit);
let int_syntax = !lit.contains(['.', 'e', 'E']);
let unsigned = lit.trim_start_matches('-');
let int_digits = unsigned.bytes().take_while(u8::is_ascii_digit).count();
let frac_digits = lit.split_once('.').map_or(0, |(_, f)| f.bytes().take_while(u8::is_ascii_digit).count());
let exp_digits = lit.split_once(['e', 'E']).map_or(0, |(_, e)| e.trim_start_matches(['+', '-']).len());
let f = lit.parse::<f64>().unwrap();
let oracle = if int_syntax {
lit.parse::<i128>().is_ok_and(|v| (i128::from(i64::MIN)..=i128::from(u64::MAX)).contains(&v))
} else {
int_digits <= 20
&& frac_digits <= 32
&& exp_digits <= 4
&& f.is_finite()
&& (f != 0.0 || !lit.split(['e', 'E']).next().unwrap().contains(|c: char| ('1'..='9').contains(&c)))
};
assert_eq!(got.is_some(), oracle, "{field}={lit}: sent {got:?}");
let Some(text) = got else {
refused += 1;
continue;
};
sent += 1;
assert!(!cut, "{field}={lit}: sent although the grammar cut it");
let serde: Value = serde_json::from_str(&lit).unwrap();
if lit == "-0" {
assert_eq!(text, "0");
} else if int_syntax {
assert_eq!(text, lit, "an integer is sent as written");
assert!(serde.is_i64() || serde.is_u64(), "{lit}: serde_json reads it as an integer");
} else {
assert_eq!(text, serde.to_string(), "{lit}: sent as serde_json reads it");
assert_eq!(serde.as_f64().unwrap().to_bits(), f.to_bits(), "{lit}: serde_json's f64 is the nearest");
}
}
assert!(sent > 5_000 && refused > 2_000, "both outcomes exercised: sent {sent}, refused {refused}");
}
#[test]
fn catalog_past_a_bound_names_it() {
let tool = |i: usize, params: Value| json!({"type": "function", "function": {"name": format!("t{i}"), "parameters": params}});
let small = json!({"type": "object", "properties": {"a": {"type": "integer"}}});
let ok = ToolCatalog::from_request(&json!({"tools": (0..40).map(|i| tool(i, small.clone())).collect::<Vec<_>>()})).unwrap();
assert_eq!(ok.over_limit(), None);
let names = ToolCatalog::from_request(&json!({"tools": (0..1025).map(|i| tool(i, json!({}))).collect::<Vec<_>>()})).unwrap();
assert!(names.over_limit().unwrap().contains("more than 1024 tool names"), "{:?}", names.over_limit());
let schemas = ToolCatalog::from_request(&json!({"tools": (0..1000).map(|i| tool(i, json!({"type": "object", "properties": {
"a": {"type": "object", "properties": {"b": {"type": "integer"}}},
"c": {"type": "object", "properties": {"d": {"type": "integer"}}},
"e": {"type": "object", "properties": {"f": {"type": "integer"}}}
}}))).collect::<Vec<_>>()})).unwrap();
assert!(schemas.over_limit().unwrap().contains("more than 4096 object schemas"), "{:?}", schemas.over_limit());
let wide: serde_json::Map<String, Value> = (0..65).map(|i| (format!("p{i}"), json!({"type": "integer"}))).collect();
let props = ToolCatalog::from_request(&json!({"tools": [tool(0, json!({"type": "object", "properties": wide}))]})).unwrap();
assert!(props.over_limit().unwrap().contains("more than 64 properties"), "{:?}", props.over_limit());
let at64: serde_json::Map<String, Value> = (0..64).map(|i| (format!("p{i}"), json!({"type": "integer"}))).collect();
let req = json!({"type": "object", "properties": at64, "required": ["p0", "p63", "p0"]});
assert_eq!(ToolCatalog::from_request(&json!({"tools": [tool(0, req)]})).unwrap().over_limit(), None);
}
#[test]
fn catalog_keeps_every_tool_schema_past_sixty_four_schemas() {
let tools: Vec<Value> = (0..40)
.map(|i| {
json!({"type": "function", "function": {"name": format!("tool{i}"), "parameters": {
"type": "object",
"properties": {
"count": {"type": "integer"},
"opts": {"type": "object", "properties": {"deep": {"type": "boolean"}}}
},
"required": ["count"],
"additionalProperties": false
}}})
})
.collect();
let catalog = ToolCatalog::from_request(&json!({"tools": tools})).unwrap();
assert_eq!(catalog.names.len(), 40, "every requested tool must be in the catalog");
assert!(catalog.name_wrappers.iter().all(|&w| w != NO_SCHEMA), "every tool's schema must compile");
let last = catalog.names.iter().position(|n| &**n == b"tool39").expect("tool39 in the catalog");
let run = |doc: &str| {
let mut st = AutoState::new(catalog.name_wrappers[last]);
doc.bytes().all(|b| st.step_byte(b, &catalog.arena, GrammarLimits::DEFAULT)) && st.is_complete()
};
assert!(run(r#"{"name":"tool39","args":{"count":3}}"#));
assert!(!run(r#"{"name":"tool39","args":{"count":"three"}}"#), "tool39's integer must be enforced");
assert!(!run(r#"{"name":"tool39","args":{}}"#), "tool39's required key must be enforced");
}
mod header {
use super::*;
pub(super) const END: u32 = 0;
pub(super) const MSG_MODEL: u32 = 1;
pub(super) const C_THINK: u32 = 2;
pub(super) const C_TEXT: u32 = 3;
pub(super) const C_TOOL: u32 = 4;
pub(super) const END_SAMP: u32 = 5;
pub(super) const EOS: u32 = 6;
pub(super) const MSG_USER: u32 = 7;
pub(super) const PIECES: &[&[u8]] = &[
b"Read", b"File", b"Bash", b"Bash2", b"2", b" Read", b"R", b"ead", b"Re", b"ad", b"x", b"F", b"ile",
b"{", b"}", b"\"", b":", b",", b"name", b"args", b"Write", b"", b" ", b"Edit", b"\n", b"\\n",
];
pub(super) fn marks() -> SpanMarks {
SpanMarks { msg_model: MSG_MODEL, c_think: C_THINK, c_text: C_TEXT, c_tool: C_TOOL, end: END }
}
pub(super) fn call(name: &[&[u8]]) -> Vec<u32> {
let mut toks = vec![MSG_MODEL];
toks.extend(name.iter().map(|p| id(p)));
toks.push(C_TOOL);
toks.extend([b"{" as &[u8], b"\"", b"args", b"\"", b":", b"{", b"}", b"}"].iter().map(|p| id(p)));
toks.push(END);
toks
}
pub(super) fn vocab() -> VocabBytes {
let mut entries: Vec<Option<&[u8]>> = vec![None; 8];
entries.extend(PIECES.iter().map(|p| Some(*p)));
VocabBytes::from_test_entries(&entries)
}
pub(super) fn id(piece: &[u8]) -> u32 {
8 + PIECES.iter().position(|p| *p == piece).expect("piece in test vocab") as u32
}
pub(super) fn n_vocab() -> u32 {
8 + PIECES.len() as u32
}
pub(super) fn step(g: &mut ToolCallGrammar, vocab: &VocabBytes, tok: u32) {
g.observe_token(tok, vocab, MSG_MODEL, C_THINK, C_TEXT, C_TOOL, END, END_SAMP, EOS);
}
pub(super) fn catalog(names: &[&str], extra: Value) -> Arc<ToolCatalog> {
let tools: Vec<Value> = names
.iter()
.map(|n| json!({"type": "function", "function": {"name": n, "parameters": {"type": "object"}}}))
.collect();
let mut req = json!({ "tools": tools });
if let (Some(obj), Some(more)) = (req.as_object_mut(), extra.as_object()) {
for (k, v) in more {
obj.insert(k.clone(), v.clone());
}
}
ToolCatalog::from_request(&req).expect("catalog")
}
}
#[test]
fn tool_header_admits_offered_names_and_their_shared_prefixes_only() {
use header::*;
let vocab = vocab();
let cat = catalog(&["Read", "ReadFile", "Bash"], json!({}));
let mut g = ToolCallGrammar::new(cat);
step(&mut g, &vocab, MSG_MODEL);
assert!(g.is_constrained() && !g.is_in_json(), "the header of a request with tools is masked");
let allows = |g: &ToolCallGrammar, t: u32| g.allows_token(t, &vocab, END);
for ok in [id(b"Read"), id(b"R"), id(b"Re"), id(b"Bash"), C_TEXT, C_THINK] {
assert!(allows(&g, ok), "empty header must allow {ok}");
}
for bad in [id(b"Bash2"), id(b" Read"), id(b"x"), id(b"File"), id(b"Write"), id(b""), C_TOOL, END, END_SAMP, EOS, MSG_USER, MSG_MODEL] {
assert!(!allows(&g, bad), "empty header must refuse {bad}");
}
step(&mut g, &vocab, id(b"Read"));
assert!(allows(&g, C_TOOL) && allows(&g, id(b"File")) && allows(&g, id(b"F")));
for bad in [id(b"2"), id(b"Bash"), id(b"ead"), C_TEXT, C_THINK, END] {
assert!(!allows(&g, bad), "header \"Read\" must refuse {bad}");
}
let mut read_file = g.clone();
step(&mut read_file, &vocab, id(b"F"));
assert!(!allows(&read_file, C_TOOL), "\"ReadF\" names no tool");
assert!(allows(&read_file, id(b"ile")));
step(&mut read_file, &vocab, id(b"ile"));
assert!(allows(&read_file, C_TOOL));
step(&mut read_file, &vocab, C_TOOL);
assert!(read_file.is_in_json());
assert!(read_file.allows_token(id(b"{"), &vocab, END));
step(&mut g, &vocab, C_TOOL);
assert!(g.is_in_json(), "an exact offered name opens the JSON body");
let mut g = ToolCallGrammar::new(catalog(&["Read", "ReadFile", "Bash"], json!({})));
step(&mut g, &vocab, MSG_MODEL);
step(&mut g, &vocab, id(b"Bash"));
assert!(!g.allows_token(id(b"2"), &vocab, END), "\"Bash2\" was never offered");
assert!(g.allows_token(C_TOOL, &vocab, END));
}
#[test]
fn tool_header_mask_reaches_every_offered_name_and_nothing_else() {
use header::*;
let vocab = vocab();
let names = ["Read", "ReadFile", "Bash"];
let cat = catalog(&names, json!({}));
let mut start = ToolCallGrammar::new(cat);
step(&mut start, &vocab, MSG_MODEL);
let mut frontier = vec![(start, String::new())];
let mut reached = std::collections::BTreeSet::new();
for _depth in 0..8 {
let mut next = Vec::new();
for (g, text) in frontier {
for t in 0..n_vocab() {
if !g.allows_token(t, &vocab, END) {
continue;
}
if t == C_TOOL {
assert!(names.contains(&text.as_str()), "tool marker allowed after {text:?}");
reached.insert(text.clone());
continue;
}
if t == C_TEXT || t == C_THINK {
assert!(text.is_empty(), "content marker allowed after {text:?}");
continue;
}
let bytes = vocab.non_special_bytes(t).expect("only name pieces remain");
let mut g2 = g.clone();
step(&mut g2, &vocab, t);
let text2 = format!("{text}{}", std::str::from_utf8(bytes).unwrap());
assert!(names.iter().any(|n| n.starts_with(&text2)), "header {text2:?} is no offered name's prefix");
next.push((g2, text2));
}
}
frontier = next;
}
assert_eq!(reached.into_iter().collect::<Vec<_>>(), vec!["Bash", "Read", "ReadFile"]);
}
#[test]
fn tool_header_text_and_thinking_answers_stay_open() {
use header::*;
let vocab = vocab();
let cat = catalog(&["Read"], json!({}));
for marker in [C_TEXT, C_THINK] {
let mut g = ToolCallGrammar::new(cat.clone());
step(&mut g, &vocab, MSG_MODEL);
assert!(g.allows_token(marker, &vocab, END));
step(&mut g, &vocab, marker);
assert!(!g.is_constrained(), "a text or thinking message is not masked");
for t in 0..n_vocab() {
assert_eq!(g.allows_token(t, &vocab, END), t != C_TOOL, "message body, token {t}");
}
}
}
#[test]
fn a_tool_choice_none_catalog_masks_nothing_at_the_grammar_level() {
use header::*;
let vocab = vocab();
assert!(ToolCatalog::from_request(&json!({"messages": []})).is_none(), "no tools: no grammar at all");
assert!(ToolCatalog::from_request(&json!({"tools": []})).is_none());
for choice in [json!("none"), json!({"type": "none"})] {
let mut g =
ToolCallGrammar::new(catalog(&["Read"], json!({ "tool_choice": choice }))).with_marks(marks());
assert_eq!(g.committed_token(C_TOOL), C_TOOL, "tool_choice {choice}: no rewrite");
for at in [&[][..], &[MSG_MODEL][..], &[MSG_MODEL, C_TEXT][..]] {
let mut g = g.clone();
for &t in at {
step(&mut g, &vocab, t);
}
assert!(!g.is_constrained(), "tool_choice {choice} leaves the header alone");
for t in 0..n_vocab() {
assert!(g.allows_token(t, &vocab, END), "tool_choice {choice}, after {at:?}: must allow {t}");
}
}
}
let mut g = ToolCallGrammar::new(catalog(&["Read"], json!({ "tool_choice": "auto" })));
step(&mut g, &vocab, MSG_MODEL);
assert!(g.is_constrained());
}
#[test]
fn tool_header_after_a_forced_thinking_close_is_masked() {
use header::*;
let vocab = vocab();
let mut g = ToolCallGrammar::new(catalog(&["Read", "Bash"], json!({})));
for t in [MSG_MODEL, C_THINK, id(b"x"), id(b"x"), END, MSG_MODEL] {
step(&mut g, &vocab, t);
}
assert!(g.is_constrained());
assert!(!g.allows_token(id(b"Bash2"), &vocab, END));
assert!(!g.allows_token(END, &vocab, END), "the turn must not close an empty model message");
assert!(g.allows_token(id(b"Bash"), &vocab, END) && g.allows_token(C_TEXT, &vocab, END));
}
#[test]
fn tool_header_counts_draws_and_those_whose_top_token_was_refused() {
use header::*;
let vocab = vocab();
let mut g = ToolCallGrammar::new(catalog(&["Read", "Bash"], json!({})));
g.note_header_draw(true);
assert_eq!((g.header_draws(), g.header_masked()), (0, 0), "outside a header nothing is counted");
step(&mut g, &vocab, MSG_MODEL);
g.note_header_draw(true);
g.note_header_draw(false);
g.note_header_draw(false);
assert_eq!((g.header_draws(), g.header_masked()), (3, 1));
step(&mut g, &vocab, id(b"Bash"));
g.note_header_draw(true);
assert_eq!((g.header_draws(), g.header_masked()), (4, 2));
step(&mut g, &vocab, C_TOOL);
g.note_header_draw(true);
assert_eq!((g.header_draws(), g.header_masked()), (4, 2), "a JSON body is not a header");
}
#[test]
fn tool_marker_is_refused_wherever_it_does_not_follow_an_offered_header() {
use header::*;
let vocab = vocab();
let cat = catalog(&["Read", "ReadFile", "Bash"], json!({}));
let x = id(b"x");
let mut after_call = call(&[b"Read"]);
after_call.extend(call(&[b"Read", b"File"]));
let states: Vec<(&str, Vec<u32>)> = vec![
("the start of the reply", vec![]),
("a text message", vec![MSG_MODEL, C_TEXT, x]),
("a thinking message", vec![MSG_MODEL, C_THINK, x]),
("between messages", vec![MSG_MODEL, C_TEXT, x, END]),
("after two calls", after_call),
("after the turn's end", vec![MSG_MODEL, C_TEXT, x, END, END_SAMP]),
];
for (label, toks) in &states {
let mut g = ToolCallGrammar::new(cat.clone()).with_marks(marks());
for &t in toks {
assert!(g.allows_token(t, &vocab, END), "{label}: the walk itself must be allowed (token {t})");
step(&mut g, &vocab, t);
}
assert!(!g.is_constrained(), "{label}: not a masked state");
for t in 0..n_vocab() {
assert_eq!(g.allows_token(t, &vocab, END), t != C_TOOL, "{label}: token {t}");
}
}
let mut g = ToolCallGrammar::new(cat);
step(&mut g, &vocab, x);
assert!(!g.allows_token(C_TOOL, &vocab, END));
}
#[test]
fn a_tool_marker_drawn_away_from_an_offered_header_is_rewritten() {
use header::*;
let vocab = vocab();
let cat = catalog(&["Read", "ReadFile", "Bash"], json!({}));
let x = id(b"x");
let cases: Vec<(&str, Vec<u32>, u32, bool)> = vec![
("the start of the reply opens a message", vec![], MSG_MODEL, true),
("a text message ends", vec![MSG_MODEL, C_TEXT, x], END, true),
("an empty text message ends", vec![MSG_MODEL, C_TEXT], END, true),
("a thinking message ends", vec![MSG_MODEL, C_THINK, x], END, true),
("between messages the next one opens", vec![MSG_MODEL, C_TEXT, x, END], MSG_MODEL, true),
("after a call the next message opens", call(&[b"Read"]), MSG_MODEL, true),
("an empty header becomes a text message", vec![MSG_MODEL], C_TEXT, false),
("a partial name becomes a text message", vec![MSG_MODEL, id(b"Re")], C_TEXT, false),
("an offered name keeps the marker", vec![MSG_MODEL, id(b"Read")], C_TOOL, false),
("a longer offered name keeps the marker", vec![MSG_MODEL, id(b"Read"), id(b"File")], C_TOOL, false),
];
for (label, toks, want, maskless) in &cases {
let mut g = ToolCallGrammar::new(cat.clone()).with_marks(marks());
for &t in toks {
step(&mut g, &vocab, t);
}
assert_eq!(g.committed_token(C_TOOL), *want, "{label}");
assert_eq!(g.marker_rewrites(), u64::from(*want != C_TOOL), "{label}: counted");
for t in (0..n_vocab()).filter(|&t| t != C_TOOL) {
assert_eq!(g.committed_token(t), t, "{label}: token {t}");
}
assert_eq!(g.is_constrained(), !*maskless, "{label}");
let committed = g.committed_token(C_TOOL);
if *maskless {
assert!(g.allows_token(committed, &vocab, END), "{label}: the rewrite obeys the mask");
}
step(&mut g, &vocab, committed);
assert_eq!(g.is_in_json(), *want == C_TOOL, "{label}");
}
}
#[test]
fn a_completed_call_is_bound_to_an_offered_name_or_not_sent() {
use header::*;
let cat = catalog(&["Read", "ReadFile", "Bash"], json!({}));
let tools = Some(&*cat);
let sent = |name: &str, consistent: bool| CallName::Sent { name: name.into(), offered: true, consistent };
assert_eq!(bind_call(tools, Some(b"Read"), Some("Read")), sent("Read", true));
assert_eq!(bind_call(tools, Some(b"ReadFile"), None), sent("ReadFile", true));
assert_eq!(bind_call(tools, Some(b"Read"), Some("Evil")), sent("Read", false));
assert_eq!(bind_call(tools, Some(b"Read"), Some("Bash")), sent("Read", false));
assert_eq!(bind_call(tools, None, Some("Bash")), sent("Bash", false));
assert_eq!(bind_call(tools, Some(b""), Some("Bash")), sent("Bash", false));
assert_eq!(bind_call(tools, Some(b"Bash2"), Some("Bash")), sent("Bash", false));
for (header, body) in [
(None, Some("Evil")),
(None, None),
(Some(&b""[..]), None),
(Some(&b"Bash2"[..]), Some("Bash2")),
(Some(&b"Rea"[..]), Some("read")),
] {
assert_eq!(bind_call(tools, header, body), CallName::Unoffered, "{header:?} {body:?}");
}
assert_eq!(
bind_call(None, Some(b" Read"), None),
CallName::Sent { name: "Read".into(), offered: false, consistent: true }
);
assert_eq!(
bind_call(None, Some(b"Read"), Some("Evil")),
CallName::Sent { name: "Evil".into(), offered: false, consistent: true }
);
}
#[test]
fn a_name_offered_with_surrounding_whitespace_is_matched_and_sent_as_offered() {
use header::*;
let vocab = vocab();
let names = [" Read", "Read", "Edit\n"];
let quote = id(b"\"");
let name_value_open = |g: &mut ToolCallGrammar| {
for p in [b"{" as &[u8], b"\"", b"name", b"\"", b":", b"\""] {
assert!(g.allows_token(id(p), &vocab, END), "body prefix {p:?}");
step(g, &vocab, id(p));
}
};
for extra in [json!({}), json!({"tool_choice": "none"})] {
let cat = catalog(&names, extra.clone());
let mut padded = ToolCallGrammar::new(cat.clone());
for t in [MSG_MODEL, id(b" Read"), C_TOOL] {
assert!(padded.allows_token(t, &vocab, END), "{extra}: header token {t}");
step(&mut padded, &vocab, t);
}
name_value_open(&mut padded);
assert!(padded.allows_token(id(b" Read"), &vocab, END), "{extra}: the body names ` Read`");
assert!(!padded.allows_token(id(b"Read"), &vocab, END), "{extra}: not the trimmed `Read`");
let mut plain = ToolCallGrammar::new(cat.clone());
for t in [MSG_MODEL, id(b"Read"), C_TOOL] {
step(&mut plain, &vocab, t);
}
name_value_open(&mut plain);
assert!(plain.allows_token(id(b"Read"), &vocab, END) && !plain.allows_token(id(b" Read"), &vocab, END));
let mut newline = ToolCallGrammar::new(cat.clone());
for t in [MSG_MODEL, id(b"Edit"), id(b"\n"), C_TOOL] {
assert!(newline.allows_token(t, &vocab, END), "{extra}: header token {t}");
step(&mut newline, &vocab, t);
}
name_value_open(&mut newline);
for p in [b"Edit" as &[u8], b"\\n"] {
assert!(newline.allows_token(id(p), &vocab, END), "{extra}: body name piece {p:?}");
step(&mut newline, &vocab, id(p));
}
assert!(newline.allows_token(quote, &vocab, END));
let tools = Some(&*cat);
let sent = |name: &str, consistent: bool| CallName::Sent { name: name.into(), offered: true, consistent };
assert_eq!(bind_call(tools, Some(b" Read"), None), sent(" Read", true));
assert_eq!(bind_call(tools, Some(b" Read"), Some(" Read")), sent(" Read", true));
assert_eq!(bind_call(tools, Some(b"Read"), None), sent("Read", true));
assert_eq!(bind_call(tools, Some(b"Edit\n"), None), sent("Edit\n", true));
assert_eq!(bind_call(tools, Some(b"Read "), None), sent("Read", false));
assert_eq!(bind_call(tools, Some(b"\tRead"), None), sent("Read", false));
assert_eq!(bind_call(tools, Some(b"Edit"), None), CallName::Unoffered, "`Edit` was not offered");
}
let mut g = ToolCallGrammar::new(catalog(&["Read"], json!({})));
step(&mut g, &vocab, MSG_MODEL);
assert!(!g.allows_token(id(b" Read"), &vocab, END) && !g.allows_token(id(b" "), &vocab, END));
}
#[test]
fn offered_name_lookups_never_scan_the_catalog() {
const MSG_MODEL: u32 = 1;
const C_TOOL: u32 = 4;
let names: Vec<String> = (0..256).map(|i| format!("mcp__workspace__tool_{i:03}")).collect();
let mut tools: Vec<Value> = names
.iter()
.map(|n| json!({"type": "function", "function": {"name": n, "parameters": {"type": "object"}}}))
.collect();
tools.extend(tools.clone());
tools.reverse();
let cat = ToolCatalog::from_request(&json!({ "tools": tools })).unwrap();
assert_eq!(cat.names.len(), 256);
assert!(cat.names.windows(2).all(|w| w[0] < w[1]), "sorted, no duplicates");
let digits: Vec<String> = (0..10).map(|d| d.to_string()).chain((0..100).map(|d| format!("{d:02}"))).collect();
let fillers: Vec<String> = (0..2000u32).map(|i| format!("{}{}", ["m", "mc", "t", "w", "_"][i as usize % 5], i)).collect();
let mut pieces: Vec<&[u8]> = vec![b"mcp__workspace__tool_", b"mcp", b"__", b"workspace", b"tool", b"_", b"m", b"mcp__", b"x"];
pieces.extend(digits.iter().map(|d| d.as_bytes()));
pieces.extend(fillers.iter().map(|f| f.as_bytes()));
pieces.extend(names.iter().map(|n| n.as_bytes()));
let mut entries: Vec<Option<&[u8]>> = vec![None; 8];
entries.extend(pieces.iter().map(|p| Some(*p)));
let vocab = VocabBytes::from_test_entries(&entries);
let tok = |piece: &[u8]| 8 + pieces.iter().position(|p| *p == piece).unwrap() as u32;
let step = |g: &mut ToolCallGrammar, t: u32| g.observe_token(t, &vocab, MSG_MODEL, 2, 3, C_TOOL, 0, 5, 6);
let probes = || NAME_PROBES.with(|c| c.replace(0));
let walks: [&[&[u8]]; 5] = [
&[],
&[b"mcp"],
&[b"mcp__workspace__tool_"],
&[b"mcp__workspace__tool_", b"1"],
&[b"mcp__workspace__tool_", b"12", b"7"],
];
for walk in walks {
let mut g = ToolCallGrammar::new(cat.clone());
probes();
step(&mut g, MSG_MODEL);
for piece in walk {
step(&mut g, tok(piece));
let narrowed = probes();
assert!(narrowed <= 18, "narrowing by {piece:?} made {narrowed} comparisons");
}
let header: Vec<u8> = walk.concat();
let mut allowed = 0;
for t in 0..entries.len() as u32 {
let got = g.allows_token(t, &vocab, 0);
let made = probes();
assert!(made <= 9, "token {t} after {walk:?} made {made} comparisons");
let scan = match vocab.non_special_bytes(t) {
Some(bytes) => {
let text = [header.as_slice(), bytes].concat();
!bytes.is_empty() && names.iter().any(|n| n.as_bytes().starts_with(&text))
}
None if t == C_TOOL => names.iter().any(|n| n.as_bytes() == header),
None => header.is_empty() && (t == 2 || t == 3),
};
assert_eq!(got, scan, "token {t} after {walk:?}");
allowed += usize::from(got);
}
assert!(allowed > 0, "after {walk:?} something is allowed");
}
let mut g = ToolCallGrammar::new(cat.clone());
for t in [MSG_MODEL, tok(b"mcp__workspace__tool_255")] {
step(&mut g, t);
}
probes();
assert!(g.allows_token(C_TOOL, &vocab, 0));
step(&mut g, C_TOOL);
assert_eq!(probes(), 0, "the marker and the body's schema cost no comparison");
assert!(g.is_in_json());
assert!(cat.offers(b"mcp__workspace__tool_128") && !cat.offers(b"mcp__workspace__tool_256"));
assert!(probes() <= 18);
}
}