Skip to content

Commit 8af1b4a

Browse files
sashankhsteipetesashankh
authored
fix(deepseek): doubled-bar DSML tool calls are delivered as text and never executed (#128882)
* fix(deepseek): recover paired doubled DSML markers Share the observed delimiter grammar between recovery and filtering, and bind each closing tag to its opener. Co-authored-by: sashankh <[email protected]> * test: honor stream and resolved account contracts * test: prevent portal fixture from reusing its refused port --------- Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: sashankh <[email protected]>
1 parent b3eec24 commit 8af1b4a

7 files changed

Lines changed: 169 additions & 136 deletions
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
// Keep the shipped single-bar forms and the doubled full-width form observed
2+
// in provider output identical across tool recovery and visible-text filtering.
3+
export const DEEPSEEK_DSML_MARKERS = ["|", "|", "||"].map((bar) => `${bar}DSML${bar}`);
4+
export const DEEPSEEK_DSML_MARKER_PATTERN = `(${DEEPSEEK_DSML_MARKERS.map((marker) =>
5+
marker.replaceAll("|", "\\|"),
6+
).join("|")})`;

‎packages/ai/src/transports/deepseek-text-filter.ts‎

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,16 @@
1+
import { DEEPSEEK_DSML_MARKERS } from "./deepseek-dsml-grammar.js";
2+
13
/**
24
* DeepSeek DSML streaming text filter.
35
* Removes provider-emitted DSML tool markup while buffering split tag prefixes
46
* across streamed chunks.
57
*/
68
const DSML_KINDS = ["tool_use_error", "tool_calls", "tool_call", "function_calls"] as const;
7-
const DSML_BARS = ["|", "|"] as const;
89

9-
const DSML_OPEN_TOKENS = DSML_BARS.flatMap((bar) =>
10-
DSML_KINDS.map((kind) => `<${bar}DSML${bar}${kind}>`),
11-
);
12-
const DSML_CLOSE_TOKENS = DSML_BARS.flatMap((bar) =>
13-
DSML_KINDS.map((kind) => `</${bar}DSML${bar}${kind}>`),
10+
const DSML_OPEN_TOKENS = DEEPSEEK_DSML_MARKERS.flatMap((marker) =>
11+
DSML_KINDS.map((kind) => `<${marker}${kind}>`),
1412
);
1513
const MAX_OPEN_TOKEN_LEN = Math.max(...DSML_OPEN_TOKENS.map((token) => token.length));
16-
const MAX_CLOSE_TOKEN_LEN = Math.max(...DSML_CLOSE_TOKENS.map((token) => token.length));
1714

1815
interface DeepSeekTextFilter {
1916
/** Push one streamed text chunk and receive any safe visible text segments. */
@@ -25,7 +22,8 @@ interface DeepSeekTextFilter {
2522
/** Create an incremental text filter that strips DeepSeek DSML tool blocks. */
2623
export function createDeepSeekTextFilter(): DeepSeekTextFilter {
2724
let buffer = "";
28-
let insideDsml = false;
25+
// Only the matching delimiter and kind may end the block being suppressed.
26+
let closeToken: string | undefined;
2927

3028
const consume = (final: boolean): string[] => {
3129
const output: string[] = [];
@@ -36,19 +34,19 @@ export function createDeepSeekTextFilter(): DeepSeekTextFilter {
3634
};
3735

3836
while (buffer) {
39-
if (insideDsml) {
40-
const close = findEarliestToken(buffer, DSML_CLOSE_TOKENS);
41-
if (close) {
42-
buffer = buffer.slice(close.index + close.token.length);
43-
insideDsml = false;
37+
if (closeToken) {
38+
const closeIndex = buffer.indexOf(closeToken);
39+
if (closeIndex !== -1) {
40+
buffer = buffer.slice(closeIndex + closeToken.length);
41+
closeToken = undefined;
4442
continue;
4543
}
4644
// Keep a suffix that could still become a closing tag once the next
4745
// streamed chunk arrives; on final flush, drop the unterminated block.
48-
const keep = final ? 0 : Math.min(buffer.length, MAX_CLOSE_TOKEN_LEN - 1);
46+
const keep = final ? 0 : Math.min(buffer.length, closeToken.length - 1);
4947
buffer = buffer.slice(buffer.length - keep);
5048
if (final) {
51-
insideDsml = false;
49+
closeToken = undefined;
5250
}
5351
return output;
5452
}
@@ -57,7 +55,7 @@ export function createDeepSeekTextFilter(): DeepSeekTextFilter {
5755
if (open) {
5856
emit(buffer.slice(0, open.index));
5957
buffer = buffer.slice(open.index + open.token.length);
60-
insideDsml = true;
58+
closeToken = open.token.replace("<", "</");
6159
continue;
6260
}
6361

‎packages/ai/src/transports/openai-completions-dsml.recovery.test.ts‎

Lines changed: 73 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,11 @@ describe("openai completions DSML", () => {
293293
expect(output.content).toEqual([]);
294294
});
295295

296-
it("emits recovered DeepSeek content-filter terminals as errors", async () => {
296+
it.each([
297+
{ finishReason: "stop", allowed: true },
298+
{ finishReason: "length", allowed: false },
299+
{ finishReason: "content_filter", allowed: false },
300+
])("gates doubled DSML over HTTP on $finishReason", async ({ finishReason, allowed }) => {
297301
const server = createServer((req, res) => {
298302
req.resume();
299303
req.on("end", () => {
@@ -302,17 +306,12 @@ describe("openai completions DSML", () => {
302306
"cache-control": "no-cache",
303307
connection: "keep-alive",
304308
});
305-
res.write(
306-
`data: ${JSON.stringify(
307-
makeCompletionsChunk(
308-
{
309-
content:
310-
'<|DSML|tool_calls><|DSML|invoke name="read">{"path":"/tmp/partial.md"}</|DSML|invoke></|DSML|tool_calls>',
311-
},
312-
"content_filter",
313-
),
314-
)}\n\n`,
315-
);
309+
const content =
310+
'<||DSML||tool_calls><||DSML||invoke name="exec"><||DSML||parameter name="code" string="true">return "ready";</||DSML||parameter></||DSML||invoke></||DSML||tool_calls>';
311+
for (const char of content) {
312+
res.write(`data: ${JSON.stringify(makeCompletionsChunk({ content: char }))}\n\n`);
313+
}
314+
res.write(`data: ${JSON.stringify(makeCompletionsChunk({}, finishReason))}\n\n`);
316315
res.end("data: [DONE]\n\n");
317316
});
318317
});
@@ -329,42 +328,45 @@ describe("openai completions DSML", () => {
329328
...createDeepSeekCompletionsModel(),
330329
baseUrl: `http://127.0.0.1:${address.port}/v1`,
331330
});
332-
const stream = createOpenAICompletionsTransportStreamFn()(
331+
const stream = await createOpenAICompletionsTransportStreamFn()(
333332
model,
334333
{
335334
systemPrompt: "system",
336335
messages: [{ role: "user", content: "Read the file", timestamp: Date.now() }],
337336
tools: [],
338-
} as never,
339-
{ apiKey: "test-key" } as never,
337+
},
338+
{ apiKey: "test-key" },
340339
);
341340

342-
const terminalEvents: Array<{
343-
type: string;
344-
reason?: string;
345-
error?: Record<string, unknown>;
346-
}> = [];
347-
for await (const event of stream as AsyncIterable<{
348-
type: string;
349-
reason?: string;
350-
error?: Record<string, unknown>;
351-
}>) {
352-
if (event.type === "done" || event.type === "error") {
353-
terminalEvents.push(event);
354-
}
341+
const events = [];
342+
for await (const event of stream) {
343+
events.push(event);
355344
}
356-
357-
expect(terminalEvents).toEqual([
358-
expect.objectContaining({
345+
const terminal = events.at(-1);
346+
if (finishReason === "content_filter") {
347+
expect(terminal).toMatchObject({
359348
type: "error",
360349
reason: "error",
361-
error: expect.objectContaining({
350+
error: {
362351
stopReason: "error",
363352
errorMessage: "Provider finish_reason: content_filter",
364353
content: [],
365-
}),
366-
}),
367-
]);
354+
},
355+
});
356+
} else {
357+
expect(terminal).toMatchObject({
358+
type: "done",
359+
reason: allowed ? "toolUse" : "length",
360+
message: {
361+
stopReason: allowed ? "toolUse" : "length",
362+
content: allowed
363+
? [{ type: "toolCall", name: "exec", arguments: { code: 'return "ready";' } }]
364+
: [],
365+
},
366+
});
367+
}
368+
expect(events.filter((event) => event.type === "toolcall_end")).toHaveLength(allowed ? 1 : 0);
369+
expect(events.filter((event) => event.type === "text_delta")).toEqual([]);
368370
} finally {
369371
await new Promise<void>((resolve, reject) => {
370372
server.close((error) => (error ? reject(error) : resolve()));
@@ -431,26 +433,51 @@ describe("openai completions DSML", () => {
431433
]);
432434
});
433435

434-
it("does not recover malformed DeepSeek DSML tool calls", async () => {
436+
it.each([
437+
{
438+
name: "empty arguments",
439+
body: '<|DSML|invoke name="read"></|DSML|invoke>',
440+
},
441+
{
442+
name: "asymmetric invoke marker",
443+
body: '<|DSML|invoke name="read">{"path":"/tmp/unexecuted"}</|DSML|invoke>',
444+
},
445+
{
446+
name: "foreign invoke close",
447+
body: '<|DSML|invoke name="read">{"path":"/tmp/unexecuted"}</|DSML|invoke>',
448+
},
449+
{
450+
name: "asymmetric parameter marker",
451+
body: '<|DSML|invoke name="read"><|DSML|parameter name="path">/tmp/unexecuted</|DSML|parameter></|DSML|invoke>',
452+
},
453+
{
454+
name: "foreign parameter close",
455+
body: '<|DSML|invoke name="read"><|DSML|parameter name="path">/tmp/unexecuted</|DSML|parameter></|DSML|invoke>',
456+
},
457+
{
458+
name: "doubled invoke with single close",
459+
body: '<||DSML||invoke name="read">{"path":"/tmp/unexecuted"}</|DSML|invoke>',
460+
},
461+
{
462+
name: "mixed doubled marker",
463+
body: '<||DSML||invoke name="read">{"path":"/tmp/unexecuted"}</||DSML||invoke>',
464+
},
465+
])("does not authorize DSML with $name", async ({ body }) => {
435466
const model = createDeepSeekCompletionsModel();
436467
const output = createAssistantOutput(model);
437-
468+
const events: CapturedStreamEvent[] = [];
469+
const content = `<|DSML|tool_calls>${body}</|DSML|tool_calls>`;
438470
await processCompletionsStream(
439471
streamChunks([
440-
makeCompletionsChunk(
441-
{
442-
content:
443-
'<|DSML|tool_calls>\n<|DSML|invoke name="session_status">\n</|DSML|invoke>\n</|DSML|tool_calls>',
444-
},
445-
"stop",
446-
),
472+
...Array.from(content, (char) => makeCompletionsChunk({ content: char })),
473+
makeCompletionsChunk({}, "stop"),
447474
]),
448475
output,
449476
model,
450-
{ push() {} },
477+
{ push: (event) => events.push(event as CapturedStreamEvent) },
451478
);
452-
453479
expect(output.stopReason).toBe("stop");
454480
expect(output.content).toEqual([]);
481+
expect(events.filter((event) => event.type?.startsWith("toolcall_"))).toEqual([]);
455482
});
456483
});

‎packages/ai/src/transports/openai-completions-dsml.test.ts‎

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -235,20 +235,16 @@ describe("openai completions DSML", () => {
235235
expect(JSON.stringify(events)).not.toContain("DSML");
236236
});
237237

238-
it("recovers DeepSeek DSML parameter tool calls emitted as text", async () => {
238+
it.each(["|", "|", "||"])("recovers streamed %s DSML parameter tool calls", async (bar) => {
239239
const model = createDeepSeekCompletionsModel();
240240
const output = createAssistantOutput(model);
241241
const events: CapturedStreamEvent[] = [];
242242

243+
const content = `<${bar}DSML${bar}tool_calls><${bar}DSML${bar}invoke name="session_status"><${bar}DSML${bar}parameter name="sessionKey" string="true">current</${bar}DSML${bar}parameter></${bar}DSML${bar}invoke></${bar}DSML${bar}tool_calls>`;
243244
await processCompletionsStream(
244245
streamChunks([
245-
makeCompletionsChunk(
246-
{
247-
content:
248-
'<|DSML|tool_calls>\n<|DSML|invoke name="session_status">\n<|DSML|parameter name="sessionKey" string="true">current</|DSML|parameter>\n</|DSML|invoke>\n</|DSML|tool_calls>',
249-
},
250-
"stop",
251-
),
246+
...Array.from(content, (char) => makeCompletionsChunk({ content: char })),
247+
makeCompletionsChunk({}, "stop"),
252248
]),
253249
output,
254250
model,

0 commit comments

Comments
 (0)