ai icon indicating copy to clipboard operation
ai copied to clipboard

[BUG]: deepseek, moonshotai, alibaba, groq, xai: empty `tool_calls: []` on reasoning deltas still fragments reasoning streams (siblings of #20253)

Open ondraulehla opened this issue 2 months ago • 8 comments

Description

Summary

#20253 fixed @ai-sdk/openai-compatible so that a streaming delta carrying "tool_calls": [] no longer closes the active reasoning block. I went looking for the same if (delta.tool_calls != null) check in the other providers that stream reasoning in an OpenAI compatible chunk shape, and five of them still have the original condition:

  • packages/deepseek/src/chat/deepseek-chat-language-model.ts:680
  • packages/moonshotai/src/moonshotai-chat-language-model.ts:729
  • packages/alibaba/src/alibaba-chat-language-model.ts:382
  • packages/groq/src/groq-chat-language-model.ts:489 (reads delta.reasoning instead of reasoning_content, same lifecycle code)
  • packages/xai/src/xai-chat-language-model.ts:593 (chat completions path, xai.chat(...))

Since [] != null is true, every reasoning delta that carries an empty tool_calls array ends the reasoning block, and the next delta opens a new one. All five packages accept a custom baseURL, so the same gateways that triggered #20203 (they attach tool_calls: [] to every chunk) hit this as soon as someone points createDeepSeek({ baseURL }), createGroq({ baseURL }) and so on at them.

mistral and openai have the same tool_calls != null check but don't end reasoning inside it, so they aren't affected.

Actual behavior

I streamed three reasoning deltas ("The", " user", " asks") followed by one text delta through streamText, every delta carrying "tool_calls": [], from a local node:http SSE mock (script below), with the published packages. Reasoning and error parts from fullStream:

openai-compatible 3.0.45 (control)
  reasoning-start, reasoning-delta, reasoning-delta, reasoning-delta, reasoning-end
  reasoningText="The user asks"
deepseek 3.0.40, moonshotai 3.0.46, alibaba 2.0.42, groq 4.0.38
  reasoning-start, reasoning-delta, reasoning-end, reasoning-start, reasoning-delta, reasoning-end, reasoning-start, reasoning-delta, reasoning-end
  reasoningText="The user asks"
xai 4.0.55 (xai.chat)
  reasoning-start, reasoning-delta, reasoning-end, reasoning-delta, error, reasoning-delta, error
  reasoningText="The"

xai is a bit worse than the others. Its stream transform keys blocks by value.id, so once the block is marked ended it never reopens. The later reasoning deltas are emitted against the closed id, streamText turns each of them into an error part (reasoning part reasoning-chatcmpl-1 not found), and result.reasoningText ends up as "The" instead of "The user asks". That's silent data loss on top of the fragmentation.

Expected behavior

Same as after #20253: an empty tool_calls array carries no information, so consecutive reasoning deltas should stay inside one reasoning-start / reasoning-delta* / reasoning-end span, exactly like when the key is absent or null.

Suggested fix

The same one line change as in openai-compatible, in each of the five files:

- if (delta.tool_calls != null) {
+ if (delta.tool_calls != null && delta.tool_calls.length > 0) {

I applied it locally on main (90a4e118) and ran test:node for the five packages: the failing test below passes and nothing else changes (deepseek 141, moonshotai 218, alibaba 151, groq 103, xai 474 tests, all green).

Existing precedent

  • #20203, the original report for openai-compatible, with the captured gateway chunks.
  • #20253, the merged fix, which only touched packages/openai-compatible.

I searched issues and PRs for the empty tool_calls case and checked the recent commits on the five files. Nothing after #20253 covers them.

Reproduction

Failing test, ported from the one added in #20253. I appended it to each of the five *-chat-language-model.test.ts files (with that package's server URL and model) and it fails on main in all five: deepseek, moonshotai, alibaba and groq receive two start/end cycles, xai receives reasoning-end before the second delta. For groq replace reasoning_content with reasoning; for xai add includeRawChunks: false to the doStream call.

it('should keep reasoning active when deltas include empty tool calls', async () => {
  server.urls['https://api.deepseek.com/chat/completions'].response = {
    type: 'stream-chunks',
    chunks: [
      `data: {"id":"chatcmpl-test","object":"chat.completion.chunk","created":1,"model":"test-model",` +
        `"choices":[{"index":0,"delta":{"role":"assistant","content":"","reasoning_content":"Think ","tool_calls":[]},"finish_reason":null}]}\n\n`,
      `data: {"id":"chatcmpl-test","object":"chat.completion.chunk","created":1,"model":"test-model",` +
        `"choices":[{"index":0,"delta":{"content":"","reasoning_content":"more...","tool_calls":[]},"finish_reason":null}]}\n\n`,
      `data: {"id":"chatcmpl-test","object":"chat.completion.chunk","created":1,"model":"test-model",` +
        `"choices":[{"index":0,"delta":{"content":"Hello","reasoning_content":"","tool_calls":[]},"finish_reason":"stop"}]}\n\n`,
      'data: [DONE]\n\n',
    ],
  };

  const { stream } = await provider.chat('deepseek-reasoner').doStream({
    prompt: TEST_PROMPT,
  });

  const events = await convertReadableStreamToArray(stream);

  expect(
    events
      .filter(({ type }) => type.startsWith('reasoning-'))
      .map(event => (event.type === 'reasoning-delta' ? `delta:${event.delta}` : event.type)),
  ).toStrictEqual([
    'reasoning-start',
    'delta:Think ',
    'delta:more...',
    'reasoning-end',
  ]);
});

Standalone script against the published packages (no API keys, the server is a local node:http SSE mock). Run with node repro.mjs after npm i ai @ai-sdk/openai-compatible @ai-sdk/deepseek @ai-sdk/moonshotai @ai-sdk/alibaba @ai-sdk/groq @ai-sdk/xai:

import http from 'node:http';
import { streamText } from 'ai';
import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
import { createDeepSeek } from '@ai-sdk/deepseek';
import { createMoonshotAI } from '@ai-sdk/moonshotai';
import { createAlibaba } from '@ai-sdk/alibaba';
import { createGroq } from '@ai-sdk/groq';
import { createXai } from '@ai-sdk/xai';

let field = 'reasoning_content';
const chunk = (delta, finish_reason = null) =>
  JSON.stringify({
    id: 'chatcmpl-1', object: 'chat.completion.chunk', created: 1, model: 'm',
    choices: [{ index: 0, delta, finish_reason }],
  });

const server = http.createServer((req, res) => {
  req.on('data', () => {});
  req.on('end', () => {
    res.writeHead(200, { 'content-type': 'text/event-stream' });
    for (const c of [
      chunk({ role: 'assistant', content: '', [field]: 'The', tool_calls: [] }),
      chunk({ content: '', [field]: ' user', tool_calls: [] }),
      chunk({ content: '', [field]: ' asks', tool_calls: [] }),
      chunk({ content: 'Hi', tool_calls: [] }),
      chunk({}, 'stop'),
    ]) res.write(`data: ${c}\n\n`);
    res.end('data: [DONE]\n\n');
  });
});
await new Promise(r => server.listen(0, r));
const baseURL = `http://127.0.0.1:${server.address().port}/v1`;
const apiKey = 'test';

async function run(name, model) {
  const result = streamText({ model, prompt: 'hi' });
  const parts = [];
  for await (const p of result.fullStream) parts.push(p);
  const seq = parts
    .filter(p => p.type.startsWith('reasoning-') || p.type === 'error')
    .map(p => p.type)
    .join(', ');
  console.log(`${name}\n  ${seq}\n  reasoningText=${JSON.stringify(await result.reasoningText)}`);
}

await run('openai-compatible (control)', createOpenAICompatible({ name: 'gw', baseURL, apiKey })('m'));
await run('deepseek', createDeepSeek({ baseURL, apiKey })('deepseek-reasoner'));
await run('moonshotai', createMoonshotAI({ baseURL, apiKey })('kimi-k2-thinking'));
await run('alibaba', createAlibaba({ baseURL, apiKey })('qwen3-max'));
await run('xai.chat', createXai({ baseURL, apiKey }).chat('grok-3-mini'));
field = 'reasoning';
await run('groq', createGroq({ baseURL, apiKey })('qwen/qwen3-32b'));
server.close();

Output I get:

openai-compatible (control)
  reasoning-start, reasoning-delta, reasoning-delta, reasoning-delta, reasoning-end
  reasoningText="The user asks"
deepseek
  reasoning-start, reasoning-delta, reasoning-end, reasoning-start, reasoning-delta, reasoning-end, reasoning-start, reasoning-delta, reasoning-end
  reasoningText="The user asks"
moonshotai
  (same as deepseek)
alibaba
  (same as deepseek)
xai.chat
  reasoning-start, reasoning-delta, reasoning-end, reasoning-delta, error, reasoning-delta, error
  reasoningText="The"
groq
  (same as deepseek)

AI SDK Version

  • ai: 7.0.95
  • @ai-sdk/openai-compatible: 3.0.45 (control, already fixed)
  • @ai-sdk/deepseek: 3.0.40
  • @ai-sdk/moonshotai: 3.0.46
  • @ai-sdk/alibaba: 2.0.42
  • @ai-sdk/groq: 4.0.38
  • @ai-sdk/xai: 4.0.55
  • main at 90a4e118 has the same five conditions
  • Node 24.2.0, macOS

Code of Conduct

  • [x] I agree to follow this project's Code of Conduct

ondraulehla avatar Sep 09 '26 16:09 ondraulehla

Identify issue type

Identified as Bug
Confidence: High

Rationale

This is a concrete defect in existing streaming behavior: empty tool-call arrays incorrectly terminate reasoning streams, and xAI additionally emits errors and loses reasoning content. The issue provides a detailed reproduction, affected versions, and a validated fix.

Evidence

  • Five provider implementations treat empty tool_calls: [] as active tool calls and prematurely close reasoning blocks.
  • The report includes reproducible stream output showing fragmented reasoning events across DeepSeek, MoonshotAI, Alibaba, and Groq, plus errors and lost reasoning text for xAI.
  • A regression test fails on main, while the analogous corrected OpenAI-compatible provider behaves as expected.

ai-sdk-factory[bot] avatar Sep 09 '26 16:09 ai-sdk-factory[bot]

Bug Reproduction - AI SDK 7

Bug was reproduced.

Branch: main PR: successful reproduction pull request

Details

  • The checked-out main package manifests match the reported AI SDK versions, and all five provider implementations still close reasoning whenever delta.tool_calls != null, unlike the corrected OpenAI-compatible implementation.
  • examples/ai-functions/src/reproduction/issue-20546-empty-tool-calls-reasoning.ts uses a local SSE endpoint to verify that three consecutive reasoning deltas with tool_calls: [] remain one reasoning span with reasoningText equal to The user asks.
  • DeepSeek, MoonshotAI, Alibaba, and Groq incorrectly emitted three separate reasoning spans, although their aggregated reasoning text remained complete.
  • xAI chat ended the reasoning block after the first delta, emitted two reasoning part reasoning-chatcmpl-1 not found errors, and returned only The as reasoning text, confirming the reported data loss.
  • The OpenAI-compatible control produced one continuous reasoning span with complete reasoning text, isolating the failure to the five affected provider adapters.

Relevant Documentation

  • https://api-docs.deepseek.com/api/create-chat-completion/
  • https://console.groq.com/docs/api-reference
  • https://console.groq.com/docs/reasoning
  • https://docs.x.ai/developers/advanced-api-usage/deferred-chat-completions

ai-sdk-factory[bot] avatar Sep 09 '26 17:09 ai-sdk-factory[bot]

Bugfix - AI SDK 7

Created bugfix and opened PR: #20554

Root Cause

All five stream transforms treated any non-null tool_calls array as active tool output. The reproduction confirmed that empty arrays prematurely closed reasoning blocks, while the corrected OpenAI-compatible adapter did not.

Summary

Require tool_calls to contain entries before ending active reasoning in the five providers, with a patch changeset for each affected package.

Testing

Added provider-specific regression tests verifying that consecutive reasoning deltas with tool_calls: [] remain one reasoning lifecycle.

ai-sdk-factory[bot] avatar Sep 09 '26 18:09 ai-sdk-factory[bot]

Bug Reproduction - AI SDK 6

Bug was reproduced.

Branch: release-v6.0 PR: successful reproduction pull request

Details

  • On the release-v6.0 target, all five provider adapters accept custom baseURL values and incorrectly treat non-null empty tool_calls arrays as active tool calls; the OpenAI-compatible control additionally checks tool_calls.length > 0.
  • Added examples/ai-functions/src/reproduction/issue-20546-empty-tool-calls-reasoning.ts, which expects three reasoning deltas to remain within one reasoning span and preserve reasoningText as The user asks.
  • DeepSeek, MoonshotAI, Alibaba, and Groq each emitted three fragmented reasoning spans, although their aggregated reasoning text remained complete.
  • xAI chat ended reasoning after the first delta, emitted two reasoning part reasoning-chatcmpl-1 not found errors, and returned only The, reproducing the reported data loss.
  • The OpenAI-compatible control emitted one continuous reasoning span with complete reasoning text, isolating the failure to the five affected adapters.

Relevant Documentation

  • https://api-docs.deepseek.com/api/create-chat-completion/
  • https://console.groq.com/docs/api-reference
  • https://console.groq.com/docs/reasoning
  • https://docs.x.ai/developers/advanced-api-usage/deferred-chat-completions
  • https://www.alibabacloud.com/help/en/model-studio/qwen-api-via-openai-chat-completions
  • https://docs.modelstudio.console.alibabacloud.com/en/model-studio/stream

ai-sdk-factory[bot] avatar Sep 10 '26 20:09 ai-sdk-factory[bot]

Bug Reproduction - AI SDK 5

Bug was reproduced.

Branch: release-v5.0 PR: successful reproduction pull request

Details

  • Added examples/ai-functions/src/reproduction/issue-20546-empty-tool-calls-reasoning.ts and examples/ai-functions/package.json; the local SSE reproduction expects each adapter to preserve one continuous reasoning span and the complete text The user asks.
  • On release-v5.0, DeepSeek and Alibaba emitted three separate reasoning spans when each reasoning delta contained tool_calls: [], while retaining the complete aggregated reasoning text.
  • xAI chat ended the reasoning block after The, emitted two reasoning part reasoning-chatcmpl-1 not found errors, and returned only The as reasoning text, reproducing the reported data loss.
  • MoonshotAI and Groq did not reproduce the reported fragmentation on this target branch; both produced one continuous reasoning span with complete reasoning text.
  • The OpenAI-compatible control produced one continuous reasoning span, confirming that the mock stream itself was valid.

Relevant Documentation

  • https://api-docs.deepseek.com/api/create-chat-completion/
  • https://api-docs.deepseek.com/guides/thinking_mode/
  • https://console.groq.com/docs/api-reference
  • https://console.groq.com/docs/reasoning
  • https://docs.x.ai/developers/advanced-api-usage/deferred-chat-completions
  • https://help.aliyun.com/en/model-studio/qwen-api-via-dashscope

ai-sdk-factory[bot] avatar Sep 10 '26 21:09 ai-sdk-factory[bot]

Backport to v6.0

created: #20610 (fixed merge).

ai-sdk-factory[bot] avatar Sep 10 '26 21:09 ai-sdk-factory[bot]

:rocket: Published in:

Package Version
ai 7.0.98 github npm
@ai-sdk/alibaba 2.0.45 github npm
@ai-sdk/amazon-bedrock 5.0.82 github npm
@ai-sdk/angular 3.0.98 github npm
@ai-sdk/anthropic 4.0.53 github npm
@ai-sdk/anthropic-aws 2.0.45 github npm
@ai-sdk/assemblyai 3.0.40 github npm
@ai-sdk/azure 4.0.69 github npm
@ai-sdk/baseten 2.1.26 github npm
@ai-sdk/black-forest-labs 2.0.41 github npm
@ai-sdk/bytedance 2.0.43 github npm
@ai-sdk/cartesia 3.0.35 github npm
@ai-sdk/cerebras 3.0.48 github npm
@ai-sdk/code-mode 1.0.55 github npm
@ai-sdk/cohere 4.0.41 github npm
@ai-sdk/deepgram 3.1.11 github npm
@ai-sdk/deepinfra 3.0.48 github npm
@ai-sdk/deepseek 3.0.43 github npm
@ai-sdk/devtools 1.0.19 github npm
@ai-sdk/elevenlabs 3.0.41 github npm
@ai-sdk/fal 3.0.41 github npm
@ai-sdk/fireworks 3.0.51 github npm
@ai-sdk/fish-audio 3.0.18 github npm
@ai-sdk/gateway 4.0.79 github npm
@ai-sdk/gladia 3.0.40 github npm
@ai-sdk/gmicloud 3.0.19 github npm
@ai-sdk/google 4.0.68 github npm
@ai-sdk/google-vertex 5.0.80 github npm
@ai-sdk/groq 4.0.41 github npm
@ai-sdk/harness 1.0.108 github npm
@ai-sdk/harness-acp 1.0.46 github npm
@ai-sdk/harness-claude-code 1.0.112 github npm
@ai-sdk/harness-cline 1.0.35 github npm
@ai-sdk/harness-codex 1.0.110 github npm
@ai-sdk/harness-cursor 1.0.21 github npm
@ai-sdk/harness-deepagents 1.0.108 github npm
@ai-sdk/harness-fx 1.0.21 github npm
@ai-sdk/harness-github-copilot 1.0.3 github npm
@ai-sdk/harness-grok-build 1.0.45 github npm
@ai-sdk/harness-opencode 1.0.110 github npm
@ai-sdk/harness-pi 1.0.110 github npm
@ai-sdk/huggingface 2.0.48 github npm
@ai-sdk/hume 3.0.40 github npm
@ai-sdk/klingai 4.0.42 github npm
@ai-sdk/langchain 3.0.98 github npm
@ai-sdk/llamaindex 3.0.98 github npm
@ai-sdk/luma 3.0.41 github npm
@ai-sdk/mcp 2.0.49 github npm
@ai-sdk/minimax 3.0.30 github npm
@ai-sdk/mistral 4.0.43 github npm
@ai-sdk/moonshotai 3.0.49 github npm
@ai-sdk/open-responses 2.0.44 github npm
@ai-sdk/openai 4.0.66 github npm
@ai-sdk/openai-compatible 3.0.48 github npm
@ai-sdk/otel 1.0.98 github npm
@ai-sdk/perplexity 4.0.43 github npm
@ai-sdk/policy-opa 1.0.98 github npm
@ai-sdk/prodia 2.0.41 github npm
@ai-sdk/provider 4.0.14 github npm
@ai-sdk/provider-utils 5.0.40 github npm
@ai-sdk/quiverai 2.0.40 github npm
@ai-sdk/react 4.0.101 github npm
@ai-sdk/replicate 3.0.41 github npm
@ai-sdk/revai 3.0.40 github npm
@ai-sdk/rsc 3.0.98 github npm
@ai-sdk/sandbox-just-bash 1.0.108 github npm
@ai-sdk/sandbox-vercel 1.0.108 github npm
@ai-sdk/svelte 5.0.98 github npm
@ai-sdk/togetherai 3.0.49 github npm
@ai-sdk/tui 1.0.99 github npm
@ai-sdk/valibot 3.0.40 github npm
@ai-sdk/voyage 2.0.40 github npm
@ai-sdk/vue 4.0.98 github npm
@ai-sdk/workflow 2.0.29 github npm
@ai-sdk/workflow-harness 1.0.108 github npm
@ai-sdk/xai 4.0.58 github npm
@ai-sdk/zai 3.0.10 github npm

github-actions[bot] avatar Sep 11 '26 19:09 github-actions[bot]

Backport to v5.0

created: #20668 (fixed merge).

ai-sdk-factory[bot] avatar Sep 11 '26 20:09 ai-sdk-factory[bot]