Repository navigation
serve: reasoning as thinking blocks on the Messages API (and reasoning_content with tool calls) #135
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
serve: reasoning as thinking blocks on the Messages API (and reasoning_content with tool calls) #135
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3936,10 +3936,68 @@ fn open_browser(url: &str) { | |
| /// One Messages API stream event. | ||
| fn sse(w: &mut impl Write, v: serde_json::Value) -> anyhow::Result<()> { Ok(write!(w, "event: {}\ndata: {v}\n\n", v["type"].as_str().unwrap_or_default())?) } | ||
|
|
||
| /// Streamed reply text as a Messages API text block (index 0), started by the first piece. | ||
| fn text_delta(w: &mut impl Write, opened: &mut bool, t: &str) -> anyhow::Result<()> { | ||
| if !std::mem::replace(opened, true) { sse(w, json!({"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}))?; } | ||
| sse(w, json!({"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": t}})) | ||
| /// A whole reply split into (reasoning, answer) at `</think>`, as a streamed reply is split piece by piece. | ||
| fn split_think(open: bool, text: &str) -> (String, String) { | ||
| let mut th = Think::new(open); | ||
| let (mut r, mut a) = th.feed(text); | ||
| let (r2, a2) = th.finish(); | ||
| r += &r2; | ||
| a += &a2; | ||
| (r, a) | ||
| } | ||
|
|
||
| /// The content of a whole Messages API reply: the reasoning as a `thinking` block (its signature empty: a local model | ||
| /// has none to give), then the answer as a `text` block, then the tool calls. | ||
| fn anthropic_content(reasoning: &str, text: &str, uses: Vec<serde_json::Value>) -> Vec<serde_json::Value> { | ||
| let thinking = (!reasoning.is_empty()).then(|| json!({"type": "thinking", "thinking": reasoning, "signature": ""})); | ||
| let text = (!text.is_empty()).then(|| json!({"type": "text", "text": text})); | ||
| thinking.into_iter().chain(text).chain(uses).collect() | ||
| } | ||
|
|
||
| /// A streamed Messages API reply: the reasoning as a `thinking` block, then the answer as a `text` block. Each block | ||
| /// starts with its first piece and stops before the next one starts; `next` is the index the next block (a tool | ||
| /// call) takes. A thinking block gets an empty `signature_delta` before it stops, as the API requires. | ||
| struct AnthStream { think: Think, open: Option<bool>, next: usize } | ||
|
|
||
| impl AnthStream { | ||
| fn new(think_open: bool) -> AnthStream { AnthStream { think: Think::new(think_open), open: None, next: 0 } } | ||
| /// Sends what is safe to send of `t` (a `</think>` split over two pieces waits for the second). | ||
| fn feed(&mut self, w: &mut impl Write, t: &str) -> anyhow::Result<()> { | ||
| let p = self.think.feed(t); | ||
| self.send(w, p) | ||
| } | ||
| /// Sends `rest` and what the splitter still holds, then stops the open block. | ||
| fn finish(&mut self, w: &mut impl Write, rest: &str) -> anyhow::Result<()> { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ✅ No longer detected as of 🔵 Low · Maintainability · 2 of 4 AnthStream::finish re-implements the split_think feed/finish sequence instead of reusing it. The Think feed-then-finish sequence now lives in split_think, in AnthStream::finish, and in AnthStream::feed/send. A later change to how Think flushes held text (for example a partial </think> at end of stream) must be made in several places, and one copy can drift from the others. Prompt for your AI agentReply
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in dab867e: |
||
| self.feed(w, rest)?; | ||
| let p = self.think.finish(); | ||
| self.send(w, p)?; | ||
| self.close(w) | ||
| } | ||
| fn send(&mut self, w: &mut impl Write, (r, a): (String, String)) -> anyhow::Result<()> { | ||
| self.piece(w, true, &r)?; | ||
| self.piece(w, false, &a) | ||
| } | ||
| fn piece(&mut self, w: &mut impl Write, thinking: bool, t: &str) -> anyhow::Result<()> { | ||
| if t.is_empty() { return Ok(()); } | ||
| if self.open != Some(thinking) { | ||
| self.close(w)?; | ||
| // The same shape as a whole reply's block; the (empty) signature also comes as a `signature_delta` at the end. | ||
| let block = if thinking { json!({"type": "thinking", "thinking": "", "signature": ""}) } else { json!({"type": "text", "text": ""}) }; | ||
| sse(w, json!({"type": "content_block_start", "index": self.next, "content_block": block}))?; | ||
| self.open = Some(thinking); | ||
| } | ||
| let delta = if thinking { json!({"type": "thinking_delta", "thinking": t}) } else { json!({"type": "text_delta", "text": t}) }; | ||
| sse(w, json!({"type": "content_block_delta", "index": self.next, "delta": delta})) | ||
| } | ||
| fn close(&mut self, w: &mut impl Write) -> anyhow::Result<()> { | ||
| let Some(thinking) = self.open.take() else { return Ok(()) }; | ||
| if thinking { | ||
| sse(w, json!({"type": "content_block_delta", "index": self.next, "delta": {"type": "signature_delta", "signature": ""}}))?; | ||
| } | ||
| sse(w, json!({"type": "content_block_stop", "index": self.next}))?; | ||
| self.next += 1; | ||
| Ok(()) | ||
| } | ||
| } | ||
|
|
||
| fn llama_timings(l: &serve::Last) -> serde_json::Value { | ||
|
|
@@ -4186,12 +4244,12 @@ fn handle(mut w: TcpStream, q: anyhow::Result<serve::Request>, l: Option<&mut Lo | |
| let tools = req.tool_calls && !req.tools.is_empty(); | ||
| let mut cached = 0; | ||
| let mut k = 0; // tokens decoded | ||
| let mut opened = false; // Messages API stream: the text block has started | ||
| let mut hold = Hold::new(tools, req.stop); | ||
| let mut streamed = Vec::new(); // the tool-call arguments a stream has sent | ||
| // A prompt that ends in an open think block makes the reply start with reasoning, up to `</think>`. | ||
| let think_open = prompt.trim_end().ends_with("<think>"); | ||
| let mut think = Think::new(think_open); | ||
| let mut blocks = AnthStream::new(think_open); // a Messages API stream's content blocks | ||
| let n_system = tok.encode(&system)?.len(); | ||
| let (mut t0, mut t1) = (Instant::now(), Instant::now()); | ||
| // Under `--parallel` a request is busy (and its prefill timed) from when the model takes it, not while it | ||
|
|
@@ -4239,7 +4297,7 @@ fn handle(mut w: TcpStream, q: anyhow::Result<serve::Request>, l: Option<&mut Lo | |
| let t = hold.push(t); | ||
| if req.stream { | ||
| if !t.is_empty() { | ||
| if !anth { send_split(&mut w, &chunk, think.feed(&t))?; } else { text_delta(&mut w, &mut opened, &t)?; } | ||
| if !anth { send_split(&mut w, &chunk, think.feed(&t))?; } else { blocks.feed(&mut w, &t)?; } | ||
| last_stream_activity = Instant::now(); | ||
| } else if last_stream_activity.elapsed() >= Duration::from_secs(15) { | ||
| w.write_all(b": keep-alive\n\n")?; | ||
|
|
@@ -4299,24 +4357,32 @@ fn handle(mut w: TcpStream, q: anyhow::Result<serve::Request>, l: Option<&mut Lo | |
| if stream { c["index"] = k.into(); } | ||
| c | ||
| }).collect(); | ||
| if stream { json!({"tool_calls": c}) } | ||
| else { json!({"role": "assistant", "content": if content.is_empty() { None } else { Some(content) }, "tool_calls": c}) } | ||
| if stream { | ||
| // A stream sent the reasoning already, as `reasoning_content` deltas before the calls. | ||
| json!({"tool_calls": c}) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ✅ No longer detected as of 🔵 Low · Correctness · 2 of 2 The streaming tool-call branch relies on reasoning already having been sent as reasoning_content deltas, which the diff does not show. If the streaming path does not emit reasoning_content deltas before tool calls, the reasoning is dropped for streamed tool-call replies, while the non-streamed branch still returns it. The stream and non-stream outputs would then differ silently. Prompt for your AI agentReply |
||
| } else { | ||
| // The text before the calls opens with the reasoning when the prompt ended in an open think block. | ||
| let (r, a) = split_think(think_open, content); | ||
| let mut m = json!({"role": "assistant", "content": if a.is_empty() { None } else { Some(a) }, "tool_calls": c}); | ||
| if !r.is_empty() { m["reasoning_content"] = r.into(); } | ||
| m | ||
| } | ||
| }; | ||
| if anth { | ||
| let reason = if calls.is_some() { "tool_use" } else if stop { "end_turn" } else { "max_tokens" }; | ||
| let usage = json!({"input_tokens": ids.len() - cached, "cache_read_input_tokens": cached, "cache_creation_input_tokens": 0, "output_tokens": out.len()}); | ||
| let uses: Vec<_> = calls.iter().flat_map(|c| &c.1).enumerate().map(|(k, (f, a))| json!({"type": "tool_use", "id": format!("toolu_{i}_{k}"), | ||
| "name": f, "input": serde_json::from_str::<serde_json::Value>(a).unwrap_or(json!({}))})).collect(); | ||
| if !req.stream { | ||
| let text = calls.as_ref().map_or(&hold.text, |c| &c.0); | ||
| let content: Vec<_> = (!text.is_empty()).then(|| json!({"type": "text", "text": text})).into_iter().chain(uses).collect(); | ||
| let (reasoning, text) = split_think(think_open, calls.as_ref().map_or(&hold.text, |c| &c.0)); | ||
| let content = anthropic_content(&reasoning, &text, uses); | ||
| return send(&mut w, "200 OK", json!({"id": format!("msg_{i}"), "type": "message", "role": "assistant", "model": name, "content": content, | ||
| "stop_reason": reason, "stop_sequence": null, "usage": usage, "timings": timings})); | ||
| } | ||
| if calls.is_none() && !hold.rest().is_empty() { text_delta(&mut w, &mut opened, hold.rest())?; } | ||
| if opened { sse(&mut w, json!({"type": "content_block_stop", "index": 0}))?; } | ||
| // A parsed call's text stays held back: only the text before it (already sent) goes out. | ||
| blocks.finish(&mut w, if calls.is_none() { hold.rest() } else { "" })?; | ||
| for (k, u) in uses.iter().enumerate() { | ||
| let (index, input) = (k + opened as usize, u["input"].to_string()); | ||
| let (index, input) = (blocks.next + k, u["input"].to_string()); | ||
| let mut start = u.clone(); | ||
| start["input"] = json!({}); | ||
| sse(&mut w, json!({"type": "content_block_start", "index": index, "content_block": start}))?; | ||
|
|
@@ -4345,10 +4411,7 @@ fn handle(mut w: TcpStream, q: anyhow::Result<serve::Request>, l: Option<&mut Lo | |
| Ok(write!(w, "data: {last}\n\ndata: [DONE]\n\n")?) | ||
| } else { | ||
| let message = match &calls { Some(c) => calls_json(c, false), None => { | ||
| let mut th = Think::new(think_open); | ||
| let (mut r, mut a) = th.feed(&hold.text); | ||
| let (r2, a2) = th.finish(); | ||
| r += &r2; a += &a2; | ||
| let (r, a) = split_think(think_open, &hold.text); | ||
| if r.is_empty() { json!({"role": "assistant", "content": a}) } else { json!({"role": "assistant", "content": a, "reasoning_content": r}) } | ||
| } }; | ||
| send(&mut w, "200 OK", json!({"id": id, "object": "chat.completion", "created": created, "model": name, | ||
|
|
@@ -4359,6 +4422,70 @@ fn handle(mut w: TcpStream, q: anyhow::Result<serve::Request>, l: Option<&mut Lo | |
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod messages_api_tests { | ||
| use super::*; | ||
|
|
||
| /// The events a Messages API stream wrote, one line each. | ||
| fn events(out: &[u8]) -> Vec<String> { | ||
| String::from_utf8_lossy(out).split("\n\n").filter_map(|e| e.lines().find_map(|l| l.strip_prefix("data: "))).map(|d| { | ||
| let e: serde_json::Value = serde_json::from_str(d).unwrap(); | ||
| let (i, d) = (&e["index"], &e["delta"]); | ||
| match e["type"].as_str().unwrap() { | ||
| "content_block_start" => format!("start {i} {}", e["content_block"]["type"].as_str().unwrap()), | ||
| "content_block_stop" => format!("stop {i}"), | ||
| _ => match d["type"].as_str().unwrap() { | ||
| "thinking_delta" => format!("{i} thinking {:?}", d["thinking"].as_str().unwrap()), | ||
| "text_delta" => format!("{i} text {:?}", d["text"].as_str().unwrap()), | ||
| t => format!("{i} {t} {:?}", d["signature"].as_str().unwrap_or("")), | ||
| }, | ||
| } | ||
| }).collect() | ||
| } | ||
|
|
||
| #[test] | ||
| fn streamed_reasoning_is_a_thinking_block_before_the_text() { | ||
| let (mut out, mut b) = (Vec::new(), AnthStream::new(true)); | ||
| for p in ["Let me", " think.\n</th", "ink>\n\nThe answer", " is 4."] { b.feed(&mut out, p).unwrap(); } | ||
| b.finish(&mut out, "").unwrap(); | ||
| assert_eq!(events(&out), ["start 0 thinking", r#"0 thinking "Let me""#, r#"0 thinking " think.\n""#, r#"0 signature_delta """#, | ||
| "stop 0", "start 1 text", r#"1 text "The answer""#, r#"1 text " is 4.""#, "stop 1"]); | ||
| assert_eq!(b.next, 2); // a tool call would be block 2 | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ✅ No longer detected as of 🔵 Low · Maintainability · 1 of 2 The new test reads the first Prompt for your AI agentReply |
||
| // The thinking block starts with the same fields as a whole reply's: an empty signature included. | ||
| let start: serde_json::Value = serde_json::from_str(String::from_utf8_lossy(&out).lines() | ||
| .find_map(|l| l.strip_prefix("data: ")).unwrap()).unwrap(); | ||
| assert_eq!(start["content_block"], json!({"type": "thinking", "thinking": "", "signature": ""})); | ||
| } | ||
|
|
||
| #[test] | ||
| fn streamed_reply_without_think_block_is_one_text_block() { | ||
| let (mut out, mut b) = (Vec::new(), AnthStream::new(false)); | ||
| b.feed(&mut out, "Hi").unwrap(); | ||
| b.finish(&mut out, " there").unwrap(); | ||
| assert_eq!(events(&out), ["start 0 text", r#"0 text "Hi""#, r#"0 text " there""#, "stop 0"]); | ||
| assert_eq!(b.next, 1); | ||
| } | ||
|
|
||
| #[test] | ||
| fn reasoning_cut_off_by_max_tokens_still_stops_its_block() { | ||
| let (mut out, mut b) = (Vec::new(), AnthStream::new(true)); | ||
| b.feed(&mut out, "still thinking").unwrap(); | ||
| b.finish(&mut out, "").unwrap(); | ||
| assert_eq!(events(&out), ["start 0 thinking", r#"0 thinking "still thinking""#, r#"0 signature_delta """#, "stop 0"]); | ||
| } | ||
|
|
||
| #[test] | ||
| fn whole_reply_puts_reasoning_in_a_thinking_block() { | ||
| let (r, a) = split_think(true, "Reasoning.\n</think>\n\n391"); | ||
| assert_eq!((r.as_str(), a.as_str()), ("Reasoning.", "391")); | ||
| assert_eq!(split_think(false, "no think block"), (String::new(), "no think block".to_string())); | ||
| let types = |c: Vec<serde_json::Value>| c.iter().map(|b| b["type"].as_str().unwrap().to_string()).collect::<Vec<_>>(); | ||
| assert_eq!(types(anthropic_content(&r, &a, vec![json!({"type": "tool_use"})])), ["thinking", "text", "tool_use"]); | ||
| assert_eq!(types(anthropic_content("", "391", vec![])), ["text"]); | ||
| assert_eq!(anthropic_content(&r, &a, vec![])[0], json!({"type": "thinking", "thinking": "Reasoning.", "signature": ""})); | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod interface_tests { | ||
| #[test] | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -869,7 +869,8 @@ pub fn detokenize(tok: &crate::tokenizer::Tokenizer, body: &[u8]) -> anyhow::Res | |
|
|
||
| /// An Anthropic Messages API request (`POST /v1/messages`, what Claude Code sends) as the OpenAI chat request | ||
| /// `chat_request` reads: the system blocks become a system message, `tool_use` blocks tool calls, `tool_result` | ||
| /// blocks tool messages, and `thinking: {"type": "enabled"}` turns thinking on. Images and server tools are dropped. | ||
| /// blocks tool messages, and `thinking: {"type": "enabled"}` / `{"type": "disabled"}` turns thinking on / off. | ||
| /// Images and server tools are dropped. | ||
| pub fn messages_body(body: &[u8]) -> anyhow::Result<Vec<u8>> { | ||
| let j: Json = serde_json::from_slice(body)?; | ||
| let s = |x: &str| Json::Str(x.into()); | ||
|
|
@@ -940,11 +941,34 @@ pub fn messages_body(body: &[u8]) -> anyhow::Result<Vec<u8>> { | |
| for (from, to) in [("max_tokens", "max_tokens"), ("temperature", "temperature"), ("top_p", "top_p"), ("min_p", "min_p"), ("top_k", "top_k"), ("stop_sequences", "stop"), ("stream", "stream")] { | ||
| if !matches!(j.get(from), Json::Null) { out.push((to, j.get(from).clone())); } | ||
| } | ||
| if j.get("thinking").get("type").as_str() == Some("enabled") { | ||
| out.push(("chat_template_kwargs", obj(vec![("enable_thinking", Json::Bool(true))]))); | ||
| if !matches!(j.get("thinking").get("budget_tokens"), Json::Null) { | ||
| out.push(("thinking_budget", j.get("thinking").get("budget_tokens").clone())); | ||
| match j.get("thinking").get("type").as_str() { | ||
| Some("enabled") => { | ||
| out.push(("chat_template_kwargs", obj(vec![("enable_thinking", Json::Bool(true))]))); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟠 High · Correctness · 1 of 1 thinking disabled sets enable_thinking false, but the model still writes a short think block, which then leaks into the answer The docs say Inkling 2 still writes a short thinking block at effort 0, even with enable_thinking false. A Messages request with thinking {"type":"disabled"} therefore gets a reply that opens with reasoning and a literal </think>. The caller builds Think::new(think_open) with think_open false, so nothing is split: the reasoning and the tag land in the text block. That is the leak this PR is meant to fix, and it returns for exactly the requests that asked to turn thinking off. Prompt for your AI agentReply |
||
| if !matches!(j.get("thinking").get("budget_tokens"), Json::Null) { | ||
| out.push(("thinking_budget", j.get("thinking").get("budget_tokens").clone())); | ||
| } | ||
| } | ||
| // Without this the server default (`--think`) applies, and a client could not turn thinking off. | ||
| Some("disabled") => out.push(("chat_template_kwargs", obj(vec![("enable_thinking", Json::Bool(false))]))), | ||
| _ => {} | ||
| } | ||
| Ok(obj(out).dump().into_bytes()) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod messages_tests { | ||
| use super::messages_body; | ||
|
|
||
| /// `thinking` maps to the template's `enable_thinking`, both ways, and its budget to `thinking_budget`. | ||
| #[test] | ||
| fn thinking_turns_thinking_on_and_off() { | ||
| let mapped = |thinking: &str| { | ||
| let body = format!(r#"{{"model":"m","max_tokens":8,"messages":[{{"role":"user","content":"hi"}}]{thinking}}}"#); | ||
| let v: serde_json::Value = serde_json::from_slice(&messages_body(body.as_bytes()).unwrap()).unwrap(); | ||
| (v["chat_template_kwargs"]["enable_thinking"].clone(), v["thinking_budget"].clone()) | ||
| }; | ||
| assert_eq!(mapped(r#","thinking":{"type":"enabled","budget_tokens":512}"#), (serde_json::json!(true), serde_json::json!(512))); | ||
| assert_eq!(mapped(r#","thinking":{"type":"disabled"}"#), (serde_json::json!(false), serde_json::Value::Null)); | ||
| assert_eq!(mapped(""), (serde_json::Value::Null, serde_json::Value::Null)); // the server default | ||
| } | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
✅ No longer detected as of
dab867ec231d.🟡 Medium · Correctness · 4 of 4
Non-streaming reply with reasoning but no text or tool calls returns only a thinking block. A reply that is all reasoning (for example one cut off by max_tokens before </think>) yields content with only a thinking block. Clients that read content[0].text, or expect a text block as the final answer, get nothing usable and may treat the reply as empty.
Prompt for your AI agent
Reply
/dismiss(optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
/dismiss By design. A reply cut off by
max_tokensinside the reasoning has no answer, and the Messages API says exactly that: a thinking block alone, withstop_reason: "max_tokens". Anthropic's API does the same, and llama.cpp's server builds the same blocks. An empty text block would be a shape the API never sends.