From d43acaf7fd9a4788bf729cd788ef938e9402b5c7 Mon Sep 17 00:00:00 2001
From: fylorn <249551762+fylorn@users.noreply.github.com>
Date: Sat, 10 Oct 2026 18:29:46 +0800
Subject: [PATCH] feat(dialect): recognise tool calls a Chat upstream writes
into its text
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Self-hosted and relayed Chat-format models (DeepSeek, GLM, Qwen, Llama
and friends) sometimes do not answer with `tool_calls` and instead write
the call into `content` in the template they were trained on. The client
then sees a tagged piece of prose and executes nothing, and the tool-call
guard never sees the call either.
`chat::text_calls` is a pure parser for four text forms:
- `{"name": …, "arguments": {…}}` (`parameters`
accepted for the arguments, and a string holding JSON text)
- DeepSeek's `<|tool▁calls▁begin|>…` group, with or without the
`function` word and the code fence, closing markers optional at the end
- GLM's `NAME\n……`,
values typed when they parse as JSON numbers, booleans, objects, arrays
- `v…`, closing
tags optional at the end
Only names the request defined are converted; anything else, and any bare
JSON object in prose, stays text. The ids use the same `call_` scheme as
the other synthesised calls.
The conversion session now keeps the request's tool names. For a Chat
upstream, a whole answer is rewritten before encoding, and a streamed
answer goes through a stage between the parser and the writer that buffers
a text block from the first opening marker to its close (or the end of the
block) and then emits ordinary ToolCall blocks, so the tool-call guard
inspects them like any structured call. Text before the marker streams as
it arrives. A `stop` finish becomes `tool_use` when a call was recovered.
Once a structured call has been seen the stage leaves later text alone.
Same-format passthrough (Chat client on a Chat upstream) is unchanged, as
the gateway never rewrites bytes there.
Also boxes the Responses variant of the stream `Writer` enum in
`convert.rs`: the current stable clippy (1.98) flags it as
`large_enum_variant` (456 bytes against 232 for the next one), which
would fail `-D warnings` as soon as CI's toolchain catches up.
Co-Authored-By: Claude Fable 5.1
---
crates/tw-dialect/src/chat/mod.rs | 1 +
crates/tw-dialect/src/chat/text_calls.rs | 996 +++++++++++++++++++++++
crates/tw-dialect/src/convert.rs | 32 +-
crates/tw-gateway/tests/conversion.rs | 158 ++++
4 files changed, 1183 insertions(+), 4 deletions(-)
create mode 100644 crates/tw-dialect/src/chat/text_calls.rs
diff --git a/crates/tw-dialect/src/chat/mod.rs b/crates/tw-dialect/src/chat/mod.rs
index 55d0cf08..5c74f2f2 100644
--- a/crates/tw-dialect/src/chat/mod.rs
+++ b/crates/tw-dialect/src/chat/mod.rs
@@ -7,6 +7,7 @@
pub mod request;
pub mod response;
pub mod stream;
+pub mod text_calls;
pub use request::{decode_request, encode_request};
pub use response::{decode_response, encode_response};
diff --git a/crates/tw-dialect/src/chat/text_calls.rs b/crates/tw-dialect/src/chat/text_calls.rs
new file mode 100644
index 00000000..6e93f2d2
--- /dev/null
+++ b/crates/tw-dialect/src/chat/text_calls.rs
@@ -0,0 +1,996 @@
+//! 模型把工具调用写进了回答正文:认出来,换成结构化的调用。
+//!
+//! 说 Chat 格式的上游不止 OpenAI:DeepSeek、GLM、Qwen、Llama 这些模型(尤其是自己部署
+//! 的、或者经中转站转发的)有时不走 `tool_calls`,而是把调用按训练时的模板直接写进
+//! `content`。客户端看到的是一段带标签的文字,什么都不会执行;工具调用审查也看不到它。
+//!
+//! 认四种写法:
+//!
+//! 1. `{"name": …, "arguments": {…}}`(Qwen、Hermes;参数也可以叫
+//! `parameters`)
+//! 2. DeepSeek:`<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>名字\n`
+//! ```` ```json\n{…}\n``` ````` `<|tool▁call▁end|>…<|tool▁calls▁end|>`,也认不写
+//! `function`、不带代码围栏的新写法
+//! 3. GLM:`名字\nk\nv…`
+//! 4. `v…`(Llama 一系)
+//!
+//! **只认请求里定义过的工具名**:名字对不上的原样留在正文里。**只认带标签的写法**:
+//! 正文里一段裸的 JSON 对象不碰,模型解释代码时写的 JSON 太多了。收尾标签在回答末尾
+//! 缺了也认(模型到上限被截断、或者模板里本来就不写)。
+//!
+//! 只在上游说 Chat 格式、请求带了工具定义、回答里没有结构化的 `tool_calls` 时做。
+//! 同格式直通不经过这里。
+
+use std::collections::{HashMap, HashSet};
+
+use serde_json::{Map, Value};
+
+use crate::ir::*;
+
+const TAG_OPEN: &str = "";
+const TAG_CLOSE: &str = "";
+const DS_CALLS_BEGIN: &str = "<|tool▁calls▁begin|>";
+const DS_CALLS_END: &str = "<|tool▁calls▁end|>";
+const DS_CALL_BEGIN: &str = "<|tool▁call▁begin|>";
+const DS_CALL_END: &str = "<|tool▁call▁end|>";
+const DS_SEP: &str = "<|tool▁sep|>";
+const FN_OPEN: &str = "";
+
+/// 正文拆开后的一段。
+#[derive(Debug, Clone, PartialEq)]
+pub enum Piece {
+ Text(String),
+ Call(Box),
+}
+
+/// 哪种写法开了头。
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Form {
+ /// ``:JSON 或 GLM 的键值对
+ Tag,
+ /// DeepSeek 的整组调用
+ DeepSeekGroup,
+ /// DeepSeek 的单个调用,没有外层标记
+ DeepSeekOne,
+ /// ``
+ Function,
+}
+
+impl Form {
+ fn open(self) -> &'static str {
+ match self {
+ Form::Tag => TAG_OPEN,
+ Form::DeepSeekGroup => DS_CALLS_BEGIN,
+ Form::DeepSeekOne => DS_CALL_BEGIN,
+ Form::Function => FN_OPEN,
+ }
+ }
+
+ /// 流里从开头标记起要攒到哪个标记为止
+ fn close(self) -> &'static str {
+ match self {
+ Form::Tag => TAG_CLOSE,
+ Form::DeepSeekGroup => DS_CALLS_END,
+ Form::DeepSeekOne => DS_CALL_END,
+ Form::Function => FN_CLOSE,
+ }
+ }
+}
+
+const FORMS: [Form; 4] = [
+ Form::Tag,
+ Form::DeepSeekGroup,
+ Form::DeepSeekOne,
+ Form::Function,
+];
+
+/// 最早出现的开头标记:在哪、是哪种
+fn next_marker(s: &str) -> Option<(usize, Form)> {
+ FORMS
+ .iter()
+ .filter_map(|f| s.find(f.open()).map(|i| (i, *f)))
+ .min_by_key(|(i, f)| (*i, std::cmp::Reverse(f.open().len())))
+}
+
+/// 一段正文 → 文字和调用。**纯函数**:名字对不上、解析不了的原样留作文字。
+pub fn split(text: &str, tools: &HashSet) -> Vec {
+ let mut out: Vec = Vec::new();
+ let mut pos = 0;
+ while let Some((at, form)) = next_marker(&text[pos..]) {
+ let at = pos + at;
+ push_text(&mut out, &text[pos..at]);
+ match parse_block(&text[at..], form, tools) {
+ Some((pieces, consumed)) => {
+ for p in pieces {
+ match p {
+ Piece::Text(t) => push_text(&mut out, &t),
+ call => out.push(call),
+ }
+ }
+ pos = at + consumed;
+ }
+ // 不是调用:标记本身留作文字,从它后面接着找 —— 它后面可能还有真的
+ None => {
+ let len = form.open().len();
+ push_text(&mut out, &text[at..at + len]);
+ pos = at + len;
+ }
+ }
+ }
+ push_text(&mut out, &text[pos..]);
+ // 换成了调用的话,调用之间只剩空白的文字不要:客户端会把它显示成一段空话
+ if out.iter().any(|p| matches!(p, Piece::Call(_))) {
+ out.retain(|p| !matches!(p, Piece::Text(t) if t.trim().is_empty()));
+ }
+ out
+}
+
+fn push_text(out: &mut Vec, t: &str) {
+ if t.is_empty() {
+ return;
+ }
+ match out.last_mut() {
+ Some(Piece::Text(prev)) => prev.push_str(t),
+ _ => out.push(Piece::Text(t.to_string())),
+ }
+}
+
+/// `rest` 以某种开头标记起头:解出这一块里的调用,和这一块有多长。
+/// 一个调用都认不出的是 None。
+fn parse_block(rest: &str, form: Form, tools: &HashSet) -> Option<(Vec, usize)> {
+ match form {
+ Form::Tag => {
+ let body_at = TAG_OPEN.len();
+ let (inner, consumed) = match rest[body_at..].find(TAG_CLOSE) {
+ Some(i) => (&rest[body_at..body_at + i], body_at + i + TAG_CLOSE.len()),
+ None => (&rest[body_at..], rest.len()),
+ };
+ let inner = inner.trim();
+ let call = if inner.starts_with('{') {
+ json_call(inner)
+ } else {
+ glm_call(inner)
+ };
+ let call = call.filter(|c| tools.contains(&c.name))?;
+ Some((vec![Piece::Call(Box::new(call))], consumed))
+ }
+ Form::DeepSeekGroup | Form::DeepSeekOne => deepseek_block(rest, form, tools),
+ Form::Function => {
+ let after = &rest[FN_OPEN.len()..];
+ let gt = after.find('>')?;
+ let name = after[..gt].trim();
+ if !plausible_name(name) || !tools.contains(name) {
+ return None;
+ }
+ let body_at = FN_OPEN.len() + gt + 1;
+ let (body, consumed) = match rest[body_at..].find(FN_CLOSE) {
+ Some(i) => (&rest[body_at..body_at + i], body_at + i + FN_CLOSE.len()),
+ None => (&rest[body_at..], rest.len()),
+ };
+ let input = if body.trim().starts_with('{') {
+ serde_json::from_str::(body.trim()).ok()?
+ } else {
+ Value::Object(parameters(body))
+ };
+ Some((
+ vec![Piece::Call(Box::new(ToolCall {
+ id: new_id("call_"),
+ name: name.to_string(),
+ input: ToolInput::Json(input),
+ }))],
+ consumed,
+ ))
+ }
+ }
+}
+
+/// `{"name": …, "arguments": {…}}`。参数写成字符串的(里面是 JSON 文本)也认
+fn json_call(inner: &str) -> Option {
+ let v: Value = serde_json::from_str(inner).ok()?;
+ let name = v.get("name")?.as_str()?;
+ if !plausible_name(name) {
+ return None;
+ }
+ let input = match v.get("arguments").or_else(|| v.get("parameters")) {
+ None | Some(Value::Null) => Value::Object(Map::new()),
+ Some(Value::String(s)) => {
+ serde_json::from_str(s).unwrap_or_else(|_| Value::String(s.clone()))
+ }
+ Some(x) => x.clone(),
+ };
+ Some(ToolCall {
+ id: new_id("call_"),
+ name: name.to_string(),
+ input: ToolInput::Json(input),
+ })
+}
+
+/// GLM:第一行是名字,后面是 `kv` 对
+fn glm_call(inner: &str) -> Option {
+ let (name, rest) = inner.split_once('\n').unwrap_or((inner, ""));
+ let name = name.trim();
+ if !plausible_name(name) {
+ return None;
+ }
+ let mut args = Map::new();
+ let mut s = rest;
+ while let Some(k) = s.find("") {
+ let s1 = &s[k + "".len()..];
+ let Some(ke) = s1.find("") else {
+ break;
+ };
+ let key = s1[..ke].trim();
+ let s2 = &s1[ke + "".len()..];
+ let Some(v) = s2.find("") else {
+ break;
+ };
+ let s3 = &s2[v + "".len()..];
+ // 收尾标签缺了(回答在这里截断):到末尾为止都是值
+ let (value, after) = match s3.find("") {
+ Some(ve) => (&s3[..ve], &s3[ve + "".len()..]),
+ None => (s3, ""),
+ };
+ args.insert(key.to_string(), typed(value));
+ s = after;
+ }
+ Some(ToolCall {
+ id: new_id("call_"),
+ name: name.to_string(),
+ input: ToolInput::Json(Value::Object(args)),
+ })
+}
+
+/// `v` 对(也认 `v`,那种写法
+/// 值前后带换行,去掉)。最后一个的收尾标签缺了也认
+fn parameters(body: &str) -> Map {
+ let mut args = Map::new();
+ let mut s = body;
+ while let Some(p) = s.find("') else { break };
+ (&q[..qe], &q[qe + gt + 1..], false)
+ } else if let Some(q) = s1.strip_prefix('=') {
+ let Some(gt) = q.find('>') else { break };
+ (q[..gt].trim(), &q[gt + 1..], true)
+ } else {
+ break;
+ };
+ let (value, after) = match s2.find("") {
+ Some(ve) => (&s2[..ve], &s2[ve + "".len()..]),
+ None => (s2, ""),
+ };
+ let value = if trim { value.trim() } else { value };
+ args.insert(key.to_string(), typed(value));
+ s = after;
+ }
+ args
+}
+
+/// DeepSeek 的一组(或一个)调用。名字对不上的那个调用原样留作文字,别的照常换
+fn deepseek_block(rest: &str, form: Form, tools: &HashSet) -> Option<(Vec, usize)> {
+ let group = form == Form::DeepSeekGroup;
+ let mut pos = if group { DS_CALLS_BEGIN.len() } else { 0 };
+ let (region_end, consumed) = match rest.find(DS_CALLS_END).filter(|_| group) {
+ Some(i) => (i, i + DS_CALLS_END.len()),
+ None => (rest.len(), rest.len()),
+ };
+ let mut pieces = Vec::new();
+ let mut matched = false;
+ while let Some(b) = rest[pos..region_end].find(DS_CALL_BEGIN) {
+ let start = pos + b;
+ push_text(&mut pieces, &rest[pos..start]);
+ let body_at = start + DS_CALL_BEGIN.len();
+ let (body, next) = match rest[body_at..region_end].find(DS_CALL_END) {
+ Some(e) => (&rest[body_at..body_at + e], body_at + e + DS_CALL_END.len()),
+ None => (&rest[body_at..region_end], region_end),
+ };
+ match deepseek_call(body).filter(|c| tools.contains(&c.name)) {
+ Some(c) => {
+ matched = true;
+ pieces.push(Piece::Call(Box::new(c)));
+ }
+ None => push_text(&mut pieces, &rest[start..next]),
+ }
+ pos = next;
+ if !group {
+ break;
+ }
+ }
+ if !matched {
+ return None;
+ }
+ push_text(&mut pieces, &rest[pos..region_end]);
+ Some((pieces, if group { consumed } else { pos }))
+}
+
+/// `function<|tool▁sep|>名字\n```json\n{…}\n```` 或者 `名字<|tool▁sep|>{…}`
+fn deepseek_call(body: &str) -> Option {
+ let (head, tail) = body.split_once(DS_SEP)?;
+ let (name, args) = match head.trim() {
+ "function" => tail.trim_start().split_once('\n').unwrap_or((tail, "")),
+ name => (name, tail),
+ };
+ let name = name.trim();
+ if !plausible_name(name) {
+ return None;
+ }
+ let mut args = args.trim();
+ if let Some(fenced) = args.strip_prefix("```") {
+ // 围栏的第一行是语言名(`json`),收尾的围栏在截断时可能没有
+ args = fenced.split_once('\n').map(|(_, a)| a).unwrap_or("");
+ args = args.trim().strip_suffix("```").unwrap_or(args).trim();
+ }
+ let input = if args.is_empty() {
+ Value::Object(Map::new())
+ } else {
+ serde_json::from_str(args).ok()?
+ };
+ Some(ToolCall {
+ id: new_id("call_"),
+ name: name.to_string(),
+ input: ToolInput::Json(input),
+ })
+}
+
+/// 一个值:是 JSON 的数字、布尔、对象、数组、null 就按那个类型,否则是字符串
+fn typed(raw: &str) -> Value {
+ match serde_json::from_str::(raw.trim()) {
+ Ok(Value::String(_)) | Err(_) => Value::String(raw.to_string()),
+ Ok(v) => v,
+ }
+}
+
+/// 像个工具名:非空、没有空白和标签字符
+fn plausible_name(name: &str) -> bool {
+ !name.is_empty() && !name.contains(|c: char| c.is_whitespace() || c == '<' || c == '>')
+}
+
+/// 整包回答:正文里的调用换成结构化的调用。已经有结构化调用的不碰
+pub fn rewrite(r: &mut Response, tools: &HashSet) {
+ if tools.is_empty() || r.blocks.iter().any(|b| matches!(b, Block::ToolCall(_))) {
+ return;
+ }
+ let mut synthesized = false;
+ let mut blocks = Vec::with_capacity(r.blocks.len());
+ for b in r.blocks.drain(..) {
+ match b {
+ Block::Text(t) => {
+ for p in split(&t, tools) {
+ blocks.push(match p {
+ Piece::Text(t) => Block::Text(t),
+ Piece::Call(c) => {
+ synthesized = true;
+ Block::ToolCall(*c)
+ }
+ });
+ }
+ }
+ other => blocks.push(other),
+ }
+ }
+ r.blocks = blocks;
+ // 上游以为自己只是在说话(`stop`):客户端要看到的是「要调工具」
+ if synthesized && matches!(r.stop, None | Some(StopReason::EndTurn)) {
+ r.stop = Some(StopReason::ToolUse);
+ }
+}
+
+// ───────────────────────────────────────────────────────── 流
+
+/// 一块文本的流式扫描:开头标记之前的文字照常放行,见到开头标记就攒,攒到收尾标记
+/// (或流结束)再解析。可能是标记开头的尾巴(`,
+ pending: String,
+ buffering: Option