use super::{Specials, Tokenizer};
use crate::json_grammar::{bind_call, CallName, ToolCatalog};
use serde_json::{json, Value};
use std::sync::Arc;
struct ToolPart { name: String, args: Value, unparsed: bool, offered: bool, consistent: bool }
enum ReplyPart { Text(String), Thinking(String), Tool(ToolPart), Unoffered, Cut, Truncated(String, String) }
fn parse_tool_call(tools: Option<&ToolCatalog>, header: Option<&[u8]>, body: &[u8]) -> Option<ToolPart> {
let s = String::from_utf8_lossy(body);
let v = crate::json_grammar::read_call_body(&s);
let CallName::Sent { name, offered, consistent } = bind_call(tools, header, v["name"].as_str()) else {
return None;
};
let parsed = v["args"].is_object();
let args = if parsed { v["args"].clone() } else { json!({"_unparsed": s}) };
Some(ToolPart { name, args, unparsed: !parsed, offered, consistent })
}
fn visit_reply(tk: &Tokenizer, sp: &Specials, toks: &[u32], tools: Option<&ToolCatalog>, mut emit: impl FnMut(ReplyPart)) {
#[derive(PartialEq)] enum M { Header, Think, Text, Tool, None }
let (mut mode, mut cur, mut header, mut text_acc) = (M::None, Vec::<u8>::new(), Vec::<u8>::new(), String::new());
let mut header_ok = false;
let flush_open = |mode: &M, cur: &mut Vec<u8>, text_acc: &mut String, emit: &mut dyn FnMut(ReplyPart)| {
match mode {
M::Think => {
text_acc.push_str(&take_stream_text(cur, true));
emit(ReplyPart::Thinking(std::mem::take(text_acc)));
}
M::Text => {
text_acc.push_str(&take_stream_text(cur, true));
emit(ReplyPart::Text(std::mem::take(text_acc)));
}
_ => {
cur.clear();
text_acc.clear();
}
}
};
for &t in toks {
if sp.is_role_stop(t) {
if mode == M::Tool {
emit(ReplyPart::Cut);
}
flush_open(&mode, &mut cur, &mut text_acc, &mut emit);
mode = M::None;
break;
}
let ends = t == sp.end || t == sp.end_sampling || t == tk.eos;
if t == sp.msg_model || t == sp.c_think || t == sp.c_text || t == sp.c_tool || ends {
if t == sp.c_text && mode == M::Text {
text_acc.push_str(&take_stream_text(&mut cur, true));
continue;
}
match mode {
M::Text | M::Think => flush_open(&mode, &mut cur, &mut text_acc, &mut emit),
M::Tool if ends => {
match parse_tool_call(tools, header_ok.then_some(header.as_slice()), &cur) {
Some(part) => emit(ReplyPart::Tool(part)),
None => emit(ReplyPart::Unoffered),
}
cur.clear();
}
M::Tool => {
emit(ReplyPart::Cut);
cur.clear();
}
_ => cur.clear(),
}
if t == sp.c_tool {
header_ok = mode == M::Header;
}
mode = if t == sp.msg_model { header.clear(); M::Header }
else if t == sp.c_think { M::Think } else if t == sp.c_text { M::Text }
else if t == sp.c_tool { M::Tool } else { M::None };
} else {
match mode { M::Header => header.extend(tk.decode_bytes(t)), M::None => {}, _ => cur.extend(tk.decode_bytes(t)) }
}
}
if mode == M::Tool {
emit(ReplyPart::Truncated(if header_ok { String::from_utf8_lossy(&header).into_owned() } else { String::new() }, String::from_utf8_lossy(&cur).into_owned()));
}
flush_open(&mode, &mut cur, &mut text_acc, &mut emit);
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct ToolTally {
pub(super) unparsed: u64,
pub(super) truncated: bool,
pub(super) unoffered: u64,
pub(super) malformed: u64,
pub(super) cut: u64,
}
pub(super) fn tool_call_tally(tk: &Tokenizer, sp: &Specials, toks: &[u32], tools: Option<&ToolCatalog>) -> ToolTally {
let mut tally = ToolTally::default();
visit_reply(tk, sp, toks, tools, |part| match part {
ReplyPart::Tool(call) => {
tally.unparsed += u64::from(call.unparsed);
tally.unoffered += u64::from(!call.offered);
tally.malformed += u64::from(call.offered && !call.consistent);
}
ReplyPart::Unoffered => tally.unoffered += 1,
ReplyPart::Cut => tally.cut += 1,
ReplyPart::Truncated(..) => tally.truncated = true,
ReplyPart::Text(_) | ReplyPart::Thinking(_) => {}
});
tally
}
pub(super) struct Parsed { pub(super) text: String, pub(super) thinking: String, pub(super) calls: Vec<(String, Value)> }
#[cfg(test)]
pub(super) fn parse(tk: &Tokenizer, sp: &Specials, toks: &[u32]) -> Parsed { parse_with_tools(tk, sp, toks, None) }
pub(super) fn parse_with_tools(tk: &Tokenizer, sp: &Specials, toks: &[u32], tools: Option<&ToolCatalog>) -> Parsed {
let mut p = Parsed { text: String::new(), thinking: String::new(), calls: Vec::new() };
visit_reply(tk, sp, toks, tools, |part| match part {
ReplyPart::Text(s) => p.text.push_str(&s),
ReplyPart::Thinking(s) => p.thinking.push_str(&s),
ReplyPart::Tool(call) => p.calls.push((call.name, call.args)),
ReplyPart::Unoffered | ReplyPart::Cut | ReplyPart::Truncated(..) => {}
});
p
}
pub(super) const SERVER_INSERTED_THINK_CLOSE: &str = "think_budget_close";
pub(super) fn record_output(
tk: &Tokenizer,
sp: &Specials,
toks: &[u32],
finish_reason: Option<&str>,
inserted: Option<(usize, usize, &str)>,
tools: Option<&ToolCatalog>,
) -> crate::record::RecordedOutput {
use crate::record::RecordedToolCall;
let mut out = crate::record::RecordedOutput {
finish_reason: finish_reason.map(str::to_owned),
token_ids: toks.to_vec(),
server_inserted: inserted
.and_then(|(start, len, cause)| {
let len = len.min(toks.len().saturating_sub(start));
(len > 0).then(|| crate::record::InsertedSpan { start, len, cause: cause.to_owned() })
})
.into_iter()
.collect::<Vec<_>>()
.into(),
..Default::default()
};
visit_reply(tk, sp, toks, tools, |part| match part {
ReplyPart::Text(s) => out.content.push_str(&s),
ReplyPart::Thinking(s) => out.reasoning.push_str(&s),
ReplyPart::Tool(ToolPart { name, mut args, unparsed, .. }) => out.tool_calls.push(if unparsed {
let raw = match args.get_mut("_unparsed").map(Value::take) {
Some(Value::String(raw)) => raw,
_ => String::new(),
};
RecordedToolCall { name, arguments: None, arguments_raw: Some(raw) }
} else {
RecordedToolCall { name, arguments: Some(args), arguments_raw: None }
}),
ReplyPart::Truncated(name, raw) => {
out.truncated_tool_call = Some(RecordedToolCall { name, arguments: None, arguments_raw: Some(raw) })
}
ReplyPart::Unoffered | ReplyPart::Cut => {}
});
out
}
pub(super) fn anthropic_stop_reason(has_calls: bool, reason: &str) -> &'static str {
if has_calls { "tool_use" } else if reason == "length" { "max_tokens" } else { "end_turn" }
}
pub(super) fn tool_use_id(nonce: &str, seq: u64, i: usize) -> String { format!("toolu_{nonce}_{seq}_{i}") }
pub(super) const THINKING_SIGNATURE: &str = "inky";
#[cfg(test)]
pub(super) fn anthropic_content(tk: &Tokenizer, sp: &Specials, toks: &[u32], nonce: &str, seq: u64) -> Vec<Value> {
anthropic_content_with_tools(tk, sp, toks, nonce, seq, None)
}
pub(super) fn anthropic_content_with_tools(tk: &Tokenizer, sp: &Specials, toks: &[u32], nonce: &str, seq: u64, tools: Option<&ToolCatalog>) -> Vec<Value> {
let mut content = Vec::new();
let mut calls = 0;
visit_reply(tk, sp, toks, tools, |part| match part {
ReplyPart::Text(text) => content.push(json!({"type": "text", "text": text})),
ReplyPart::Tool(call) => {
content.push(json!({"type": "tool_use", "id": tool_use_id(nonce, seq, calls), "name": call.name, "input": call.args}));
calls += 1;
}
ReplyPart::Thinking(text) => {
if !text.is_empty() {
content.push(json!({"type": "thinking", "thinking": text, "signature": THINKING_SIGNATURE}));
}
}
ReplyPart::Unoffered | ReplyPart::Cut | ReplyPart::Truncated(..) => {}
});
content
}
pub(super) fn anthropic_usage(prompt: usize, cached: usize, gen: usize) -> Value {
json!({"input_tokens": prompt.saturating_sub(cached), "output_tokens": gen,
"cache_creation_input_tokens": 0, "cache_read_input_tokens": cached})
}
pub(super) fn streaming_delta_usage(prompt: usize, cached: usize, gen: usize) -> Value { anthropic_usage(prompt, cached, gen) }
pub(super) fn sse_text(event: &str, data: &Value) -> String { format!("event: {event}\ndata: {data}\n\n") }
pub(super) fn take_stream_text(pend: &mut Vec<u8>, end: bool) -> String {
let mut text = String::new();
crate::stream_text::stream_text(pend, end, |s| text.push_str(s));
text
}
pub(super) struct BlockStream { nonce: String, seq: u64, next: usize, pub(super) calls: usize, text_index: usize, open_text: bool,
think_index: usize, open_think: bool,
mode: u8, pend: Vec<u8>, header: Vec<u8>, tool: Vec<u8>, in_header: bool, stopped: bool,
header_ok: bool,
tools: Option<Arc<ToolCatalog>> }
impl BlockStream {
pub(super) fn new(nonce: &str, seq: u64) -> BlockStream {
BlockStream { nonce: nonce.to_string(), seq, next: 0, calls: 0, text_index: 0, open_text: false, think_index: 0, open_think: false,
mode: 0, pend: vec![], header: vec![], tool: vec![], in_header: false, stopped: false, header_ok: false, tools: None }
}
pub(super) fn with_tools(mut self, tools: Option<Arc<ToolCatalog>>) -> BlockStream {
self.tools = tools;
self
}
fn think_delta(&mut self, out: &mut Vec<String>, end: bool) {
let text = take_stream_text(&mut self.pend, end);
if text.is_empty() { return; }
if !self.open_think {
self.think_index = self.next; self.next += 1; self.open_think = true;
out.push(sse_text("content_block_start", &json!({"type": "content_block_start", "index": self.think_index,
"content_block": {"type": "thinking", "thinking": "", "signature": ""}})));
}
out.push(sse_text("content_block_delta", &json!({"type": "content_block_delta", "index": self.think_index,
"delta": {"type": "thinking_delta", "thinking": text}})));
}
fn close_think(&mut self, out: &mut Vec<String>) {
if self.mode != 1 { return; }
self.think_delta(out, true);
if self.open_think {
out.push(sse_text("content_block_delta", &json!({"type": "content_block_delta", "index": self.think_index,
"delta": {"type": "signature_delta", "signature": THINKING_SIGNATURE}})));
out.push(sse_text("content_block_stop", &json!({"type": "content_block_stop", "index": self.think_index})));
self.open_think = false;
}
self.pend.clear();
}
fn close_open(&mut self, out: &mut Vec<String>) {
self.close_think(out);
self.close_text(out);
}
fn flush_text(&mut self, out: &mut Vec<String>) {
if !self.open_text { self.pend.clear(); return; }
let text = take_stream_text(&mut self.pend, false);
if !text.is_empty() {
out.push(sse_text("content_block_delta", &json!({"type": "content_block_delta", "index": self.text_index,
"delta": {"type": "text_delta", "text": text}})));
}
}
fn close_text(&mut self, out: &mut Vec<String>) {
if self.open_text {
let text = take_stream_text(&mut self.pend, true);
if !text.is_empty() {
out.push(sse_text("content_block_delta", &json!({"type": "content_block_delta", "index": self.text_index,
"delta": {"type": "text_delta", "text": text}})));
}
out.push(sse_text("content_block_stop", &json!({"type": "content_block_stop", "index": self.text_index})));
self.open_text = false;
}
self.pend.clear();
}
fn emit_tool(&mut self, out: &mut Vec<String>) {
let header = self.header_ok.then_some(self.header.as_slice());
let Some(ToolPart { name, args, .. }) = parse_tool_call(self.tools.as_deref(), header, &self.tool) else {
self.tool.clear();
return;
};
let index = self.next; self.next += 1;
let id = tool_use_id(&self.nonce, self.seq, self.calls); self.calls += 1;
out.push(sse_text("content_block_start", &json!({"type": "content_block_start", "index": index,
"content_block": {"type": "tool_use", "id": id, "name": name, "input": {}}})));
out.push(sse_text("content_block_delta", &json!({"type": "content_block_delta", "index": index,
"delta": {"type": "input_json_delta", "partial_json": args.to_string()}})));
out.push(sse_text("content_block_stop", &json!({"type": "content_block_stop", "index": index})));
self.tool.clear();
}
pub(super) fn on_token(&mut self, tk: &Tokenizer, sp: &Specials, t: u32) -> Vec<String> {
if self.stopped { return Vec::new(); }
let mut out = Vec::new();
if sp.is_role_stop(t) {
if self.mode == 3 { self.tool.clear(); }
self.close_open(&mut out);
self.mode = 0;
self.in_header = false;
self.stopped = true;
return out;
}
if t == sp.msg_model { self.close_open(&mut out); self.mode = 0; self.in_header = true; self.header.clear(); return out; }
if t == sp.c_think { self.close_open(&mut out); self.mode = 1; self.in_header = false; return out; }
if t == sp.c_text {
self.close_think(&mut out);
if self.open_text {
let text = take_stream_text(&mut self.pend, true);
if !text.is_empty() {
out.push(sse_text("content_block_delta", &json!({"type": "content_block_delta", "index": self.text_index,
"delta": {"type": "text_delta", "text": text}})));
}
} else {
self.text_index = self.next; self.next += 1; self.open_text = true;
out.push(sse_text("content_block_start", &json!({"type": "content_block_start", "index": self.text_index,
"content_block": {"type": "text", "text": ""}})));
}
self.mode = 2; self.in_header = false; return out;
}
if t == sp.c_tool { self.close_open(&mut out); self.mode = 3; self.header_ok = self.in_header; self.in_header = false; self.tool.clear(); return out; }
if t == sp.end || t == sp.end_sampling || t == tk.eos {
if self.mode == 3 { self.emit_tool(&mut out); }
self.close_open(&mut out);
self.mode = 0; self.in_header = false; return out;
}
let b = tk.decode_bytes(t);
match self.mode {
1 => { self.pend.extend(&b); self.think_delta(&mut out, false); }
2 => { self.pend.extend(&b); self.flush_text(&mut out); }
3 => self.tool.extend(&b),
_ if self.in_header => self.header.extend(&b),
_ => {}
}
out
}
pub(super) fn close_all(&mut self) -> Vec<String> {
let mut out = Vec::new();
if self.mode == 3 { self.tool.clear(); self.mode = 0; }
self.close_open(&mut out);
self.mode = 0;
out
}
}
#[cfg(test)]
pub(super) mod tests {
use super::*;
pub(in crate::serve) fn off_template_tool_turn(tk: &Tokenizer, sp: &Specials) -> Vec<u32> {
let mut toks = Vec::new();
let body = |toks: &mut Vec<u32>, header: Option<&str>, json: &str| {
if let Some(h) = header {
toks.push(sp.msg_model);
toks.extend(tk.encode(h, false));
}
toks.push(sp.c_tool);
toks.extend(tk.encode(json, false));
toks.push(sp.end);
};
body(&mut toks, Some("ping"), r#"{"name":"ping","args":{"n":1}}"#);
body(&mut toks, None, r#"{"name":"Evil","args":{"n":2}}"#);
body(&mut toks, None, r#"{"args":{"n":3}}"#);
body(&mut toks, None, r#"{"name":"pong","args":{"n":4}}"#);
body(&mut toks, Some("ping"), r#"{"name":"Evil","args":{"n":5}}"#);
toks.extend([sp.msg_model, sp.c_text]);
toks.extend(tk.encode("hi", false));
body(&mut toks, None, r#"{"name":"Evil","args":{"n":6}}"#);
body(&mut toks, Some("Evil"), r#"{"name":"Evil","args":{"n":7}}"#);
body(&mut toks, Some("pong"), r#"{"args":{"n":8}}"#);
toks.push(sp.end_sampling);
toks
}
pub(in crate::serve) fn ping_pong_catalog() -> Arc<ToolCatalog> {
ToolCatalog::from_request(&json!({"tools": [
{"type": "function", "function": {"name": "ping", "parameters": {"type": "object"}}},
{"type": "function", "function": {"name": "pong", "parameters": {"type": "object"}}},
]}))
.unwrap()
}
#[test]
fn a_request_with_tools_is_only_sent_names_it_offered_on_every_reply_path() {
let tk = Tokenizer::for_byte_test();
let sp = Specials::try_from_tokenizer(&tk).unwrap();
let toks = off_template_tool_turn(&tk, &sp);
let cat = ping_pong_catalog();
let want = vec![
("ping".to_string(), json!({"n": 1})),
("pong".to_string(), json!({"n": 4})),
("ping".to_string(), json!({"n": 5})),
("pong".to_string(), json!({"n": 8})),
];
let parsed = parse_with_tools(&tk, &sp, &toks, Some(&cat));
assert_eq!(parsed.calls, want);
assert_eq!(parsed.text, "hi");
let content = anthropic_content_with_tools(&tk, &sp, &toks, "n", 1, Some(&cat));
let uses: Vec<(String, Value)> = content
.iter()
.filter(|c| c["type"] == "tool_use")
.map(|c| (c["name"].as_str().unwrap().to_string(), c["input"].clone()))
.collect();
assert_eq!(uses, want);
let mut bs = BlockStream::new("n", 1).with_tools(Some(cat.clone()));
let mut streamed: Vec<(String, Value)> = Vec::new();
let mut name = None;
let mut frames: Vec<String> = toks.iter().flat_map(|&t| bs.on_token(&tk, &sp, t)).collect();
frames.extend(bs.close_all());
for raw in frames {
let ev: Value = serde_json::from_str(raw.split("\ndata: ").nth(1).unwrap().trim_end()).unwrap();
if ev["content_block"]["type"] == "tool_use" {
name = ev["content_block"]["name"].as_str().map(str::to_owned);
} else if ev["delta"]["type"] == "input_json_delta" {
let input = serde_json::from_str(ev["delta"]["partial_json"].as_str().unwrap()).unwrap();
streamed.push((name.take().unwrap(), input));
}
}
assert_eq!(streamed, want);
assert_eq!(bs.calls, 4, "the stream's stop reason counts sent calls only");
let tally = tool_call_tally(&tk, &sp, &toks, Some(&cat));
assert_eq!(tally, ToolTally { unparsed: 0, truncated: false, unoffered: 4, malformed: 2, cut: 0 });
let mut clean = Vec::new();
for (name, body) in [("ping", r#"{"name":"ping","args":{}}"#), ("pong", r#"{"args":{}}"#), ("ping", r#"{"args":{}}"#)] {
clean.push(sp.msg_model);
clean.extend(tk.encode(name, false));
clean.push(sp.c_tool);
clean.extend(tk.encode(body, false));
clean.push(sp.end);
}
assert_eq!(parse_with_tools(&tk, &sp, &clean, Some(&cat)).calls.len(), 3);
assert_eq!(tool_call_tally(&tk, &sp, &clean, Some(&cat)), ToolTally::default());
let loose = parse(&tk, &sp, &toks);
assert_eq!(loose.calls.len(), 8);
assert_eq!(loose.calls[2].0, "", "a body with no header and no name is not named by an earlier header");
assert_eq!(tool_call_tally(&tk, &sp, &toks, None).unoffered, 8);
}
#[test]
fn a_name_offered_with_surrounding_whitespace_is_sent_as_offered() {
let tk = Tokenizer::for_byte_test();
let sp = Specials::try_from_tokenizer(&tk).unwrap();
let cat = ToolCatalog::from_request(&json!({"tools": [
{"type": "function", "function": {"name": " Read", "parameters": {"type": "object"}}},
{"type": "function", "function": {"name": "Read", "parameters": {"type": "object"}}},
{"type": "function", "function": {"name": "Edit\n", "parameters": {"type": "object"}}},
]}))
.unwrap();
let mut toks = Vec::new();
for (header, body) in [(" Read", r#"{"args":{"n":1}}"#), ("Read", r#"{"args":{"n":2}}"#), ("Edit\n", r#"{"name":"Edit\n","args":{"n":3}}"#)] {
toks.push(sp.msg_model);
toks.extend(tk.encode(header, false));
toks.push(sp.c_tool);
toks.extend(tk.encode(body, false));
toks.push(sp.end);
}
let want = vec![" Read", "Read", "Edit\n"];
let parsed = parse_with_tools(&tk, &sp, &toks, Some(&cat));
assert_eq!(parsed.calls.iter().map(|c| c.0.as_str()).collect::<Vec<_>>(), want);
let content = anthropic_content_with_tools(&tk, &sp, &toks, "n", 1, Some(&cat));
assert_eq!(content.iter().filter_map(|c| c["name"].as_str()).collect::<Vec<_>>(), want);
let mut bs = BlockStream::new("n", 1).with_tools(Some(cat.clone()));
let mut streamed = Vec::new();
for raw in toks.iter().flat_map(|&t| bs.on_token(&tk, &sp, t)) {
let ev: Value = serde_json::from_str(raw.split("\ndata: ").nth(1).unwrap().trim_end()).unwrap();
if ev["content_block"]["type"] == "tool_use" {
streamed.push(ev["content_block"]["name"].as_str().unwrap().to_string());
}
}
assert_eq!(streamed, want);
assert_eq!(tool_call_tally(&tk, &sp, &toks, Some(&cat)), ToolTally::default());
}
#[test]
fn a_tool_body_cut_by_a_role_stop_or_a_marker_is_counted() {
let tk = Tokenizer::for_byte_test();
let sp = Specials::try_from_tokenizer(&tk).unwrap();
let cat = ping_pong_catalog();
let open = |cut: &[u32]| {
let mut toks = vec![sp.msg_model];
toks.extend(tk.encode("ping", false));
toks.push(sp.c_tool);
toks.extend(tk.encode(r#"{"args":"#, false));
toks.extend_from_slice(cut);
toks
};
for cut in [&[sp.msg_user][..], &[sp.msg_model, sp.c_text, sp.end][..], &[sp.c_text, sp.end][..]] {
let toks = open(cut);
assert!(parse_with_tools(&tk, &sp, &toks, Some(&cat)).calls.is_empty());
let tally = tool_call_tally(&tk, &sp, &toks, Some(&cat));
assert_eq!(tally, ToolTally { cut: 1, ..ToolTally::default() }, "cut by {cut:?}");
}
let tally = tool_call_tally(&tk, &sp, &open(&[]), Some(&cat));
assert_eq!(tally, ToolTally { truncated: true, ..ToolTally::default() });
}
#[test]
fn a_padded_header_without_a_body_name_goes_out_under_the_trimmed_name() {
let tk = Tokenizer::for_byte_test();
let sp = Specials::try_from_tokenizer(&tk).unwrap();
let mut toks = vec![sp.msg_model];
toks.extend(tk.encode(" Read", false));
toks.push(sp.c_tool);
toks.extend(tk.encode(r#"{"args":{"path":"a"}}"#, false));
toks.push(sp.end);
let parsed = parse(&tk, &sp, &toks);
assert_eq!(parsed.calls.len(), 1);
assert_eq!(parsed.calls[0].0, "Read");
assert_eq!(parsed.calls[0].1, json!({"path": "a"}));
let content = anthropic_content(&tk, &sp, &toks, "test", 1);
assert!(content.iter().any(|c| c["type"] == "tool_use" && c["name"] == "Read"), "{content:?}");
let mut bs = BlockStream::new("test", 1);
let mut names = Vec::new();
for &t in &toks {
for raw in bs.on_token(&tk, &sp, t) {
let data = raw.split("\ndata: ").nth(1).unwrap().trim_end();
let ev: Value = serde_json::from_str(data).unwrap();
if ev["content_block"]["type"] == "tool_use" {
names.push(ev["content_block"]["name"].clone());
}
}
}
assert_eq!(names, vec![json!("Read")]);
}
#[test]
fn consecutive_content_text_flushes_incomplete_utf8_matching_block_stream() {
let tk = Tokenizer::for_byte_test();
let sp = Specials::try_from_tokenizer(&tk).unwrap();
let byte_tok = |b: u8| tk.eos + 1 + u32::from(b);
let toks = [sp.c_text, byte_tok(0xE2), sp.c_text, byte_tok(0x82), byte_tok(0xAC), sp.end];
let parsed = parse(&tk, &sp, &toks);
let content = anthropic_content(&tk, &sp, &toks, "test", 1);
let mut bs = BlockStream::new("test", 1);
let mut events: Vec<Value> = Vec::new();
for &t in &toks {
for raw in bs.on_token(&tk, &sp, t) {
let data = raw.split("\ndata: ").nth(1).unwrap().trim_end();
events.push(serde_json::from_str(data).unwrap());
}
}
for raw in bs.close_all() {
let data = raw.split("\ndata: ").nth(1).unwrap().trim_end();
events.push(serde_json::from_str(data).unwrap());
}
let bs_starts = events.iter().filter(|e| e["type"] == "content_block_start").count();
let bs_text: String = events
.iter()
.filter(|e| e["delta"]["type"] == "text_delta")
.map(|e| e["delta"]["text"].as_str().unwrap())
.collect();
assert_eq!(bs_starts, 1);
assert_eq!(bs_text, "\u{FFFD}\u{FFFD}\u{FFFD}");
assert_eq!(parsed.text, bs_text);
assert_eq!(content, vec![json!({"type": "text", "text": "\u{FFFD}\u{FFFD}\u{FFFD}"})]);
let ascii_toks = [sp.c_text, byte_tok(b'H'), byte_tok(b'i'), sp.c_text, byte_tok(b'!'), sp.end];
assert_eq!(parse(&tk, &sp, &ascii_toks).text, "Hi!");
assert_eq!(anthropic_content(&tk, &sp, &ascii_toks, "test", 2), vec![json!({"type": "text", "text": "Hi!"})]);
}
#[test]
fn record_output_keeps_reasoning_calls_parse_failures_and_a_cut_tool_body() {
let tk = Tokenizer::for_byte_test();
let sp = Specials::try_from_tokenizer(&tk).unwrap();
let bytes = |s: &str| s.bytes().map(|b| tk.eos + 1 + u32::from(b)).collect::<Vec<_>>();
let mut toks = vec![sp.c_think];
toks.extend(bytes("Read it first."));
toks.extend([sp.end, sp.msg_model, sp.c_tool]);
toks.extend(bytes(r#"{"name":"read_file","args":{"path":"a.rs"}}"#));
toks.extend([sp.end, sp.msg_model, sp.c_tool]);
toks.extend(bytes(r#"{"name":"run","args":[1"#));
toks.extend([sp.end, sp.msg_model, sp.c_text]);
toks.extend(bytes("Done."));
toks.extend([sp.end, sp.msg_model, sp.c_tool]);
toks.extend(bytes(r#"{"name":"edit","ar"#));
let out = record_output(&tk, &sp, &toks, Some("length"), None, None);
assert_eq!(out.reasoning, "Read it first.");
assert_eq!(out.content, "Done.");
assert_eq!(out.token_ids, toks);
assert_eq!(out.finish_reason.as_deref(), Some("length"));
assert_eq!(out.tool_calls.len(), 2);
assert_eq!(out.tool_calls[0].name, "read_file");
assert_eq!(out.tool_calls[0].arguments, Some(json!({"path": "a.rs"})));
assert_eq!(out.tool_calls[0].arguments_raw, None);
assert_eq!(out.tool_calls[1].arguments, None);
assert_eq!(out.tool_calls[1].arguments_raw.as_deref(), Some(r#"{"name":"run","args":[1"#));
let cut = out.truncated_tool_call.expect("cut tool body");
assert_eq!((cut.arguments, cut.arguments_raw.as_deref()), (None, Some(r#"{"name":"edit","ar"#)));
let p = parse(&tk, &sp, &toks);
assert_eq!((p.text.as_str(), p.thinking.as_str(), p.calls.len()), ("Done.", "Read it first.", 2));
assert_eq!(record_output(&tk, &sp, &toks[..3], None, None, None).finish_reason, None);
assert_eq!(out.server_inserted, Some(vec![]), "always written, empty when nothing was inserted");
let cut = |start, len| record_output(&tk, &sp, &toks[..4], None, Some((start, len, SERVER_INSERTED_THINK_CLOSE)), None).server_inserted.unwrap();
assert_eq!(cut(2, 5).iter().map(|r| (r.start, r.len)).collect::<Vec<_>>(), [(2, 2)]);
assert!(cut(4, 2).is_empty());
}
fn recorded_message(out: &crate::record::RecordedOutput) -> Value {
let mut m = json!({"role": "assistant", "content": out.content});
if !out.reasoning.is_empty() {
m["reasoning_content"] = json!(out.reasoning);
}
if !out.tool_calls.is_empty() {
m["tool_calls"] = out
.tool_calls
.iter()
.enumerate()
.map(|(i, c)| {
let args = c.arguments.as_ref().expect("a parsed call").to_string();
json!({"id": format!("call_{i}"), "type": "function", "function": {"name": c.name, "arguments": args}})
})
.collect();
}
m
}
#[test]
fn recorded_output_renders_back_through_the_chat_template_to_its_token_ids() {
let tk = Tokenizer::for_byte_test();
let sp = Specials::try_from_tokenizer(&tk).unwrap();
let user = json!({"role": "user", "content": "fix the failing test"});
let prefix = super::super::prompt::render(&tk, &sp, &json!({"messages": [user]}), "low").unwrap();
let assistant = |m: &Value| {
let full = super::super::prompt::render(&tk, &sp, &json!({"messages": [user, m]}), "low").unwrap();
assert_eq!(full[..prefix.len()], prefix[..], "the assistant turn renders after the prompt");
full[prefix.len()..].to_vec()
};
let call = |name: &str, args: Value| json!({"id": "c", "type": "function", "function": {"name": name, "arguments": args.to_string()}});
let cases = [
json!({"role": "assistant", "content": "Done."}),
json!({"role": "assistant", "content": "It passes now.", "reasoning_content": "The assert is off by one.\n\"x\" \u{e9}\u{1F600}"}),
json!({"role": "assistant", "content": null, "reasoning_content": "Read it first.", "tool_calls": [call("read_file", json!({"path": "src/lib.rs"}))]}),
json!({"role": "assistant", "content": "Two calls.", "reasoning_content": "Plan.",
"tool_calls": [call("read_file", json!({"path": "a.rs", "range": [1, 40]})), call("run_test", json!({"name": "t", "opts": {"q": true}}))]}),
];
for m in &cases {
let generated = assistant(m);
assert_eq!(generated.last(), Some(&sp.end_sampling), "the reply ends on its stop token");
let out = record_output(&tk, &sp, &generated, Some("stop"), None, None);
assert_eq!(out.token_ids, generated);
assert_eq!(assistant(&recorded_message(&out)), out.token_ids, "round trip of {m}");
}
let mut generated = assistant(&json!({"role": "assistant", "content": null, "tool_calls": [call("f", json!({}))]}));
let body_at = generated.iter().position(|&t| t == sp.c_tool).unwrap() + 1;
let end_at = generated.iter().rposition(|&t| t == sp.end).unwrap();
generated.splice(body_at..end_at, tk.encode(r#"{"name":"f","args":{"b":1,"a":2}}"#, false));
let out = record_output(&tk, &sp, &generated, Some("stop"), None, None);
assert_eq!(out.tool_calls[0].arguments, Some(json!({"a": 2, "b": 1})));
assert_ne!(assistant(&recorded_message(&out)), out.token_ids);
}
#[test] fn stream_utf8_recovers_and_flushes_incomplete_sequences() {
let mut pend = vec![0xff, b'h', b'i', 0xe2, 0x82];
assert_eq!(take_stream_text(&mut pend, false), "�hi");
assert_eq!(pend, vec![0xe2, 0x82]);
pend.push(0xac);
assert_eq!(take_stream_text(&mut pend, false), "€");
pend.extend([0xe2, 0x82]);
assert_eq!(take_stream_text(&mut pend, true), "�");
assert!(pend.is_empty());
let mut bs = BlockStream::new("test", 1);
bs.open_text = true;
bs.pend = vec![0xff, b'h', b'i', 0xe2];
let mut events = Vec::new();
bs.flush_text(&mut events);
bs.close_text(&mut events);
let text: String = events.iter().filter_map(|event| {
let v: Value = serde_json::from_str(event.split("\ndata: ").nth(1)?.trim_end()).ok()?;
v["delta"]["text"].as_str().map(str::to_owned)
}).collect();
assert_eq!(text, "�hi�");
}
}