ai icon indicating copy to clipboard operation
ai copied to clipboard

reasoning part reasoning-0 not found due to bug in extractReasoningMiddleware

Open jovanwongzixi opened this issue 10 months ago • 2 comments

Description

There have been issues raised in some coding agent platforms (eg. OpenCode, cherry-studio) over the past few months regarding a "reasoning part reasoning-0 not found" error. Below are 2 such examples raised in their respective repos

These issues are particularly prevalent for Zhipu's GLM series of models, especially those using the locally hosted (eg. LMStudio, vLLM) models instead of Zhipu's endpoints. The "reasoning part reasoning-0 not found" error is triggered when the LLM endpoint replies with an empty thinking block .

I created a mock LLM server to stream a reply with an empty thinking block as a test case, and it throws the error as shown in the screenshot below. Image

The root cause is due to the lack of checks in the extract-reasoning-middleware.ts file, where a 'reasoning-end' event will be emitted without checking if a 'reasoning-start' event has been emitted. In the scenario of a empty thinking block, the 'reasoning-start' event will never be sent as text.length>0 check will fail here.

This will result in activeReasoning being null and the error will be thrown here

        if (part.type === 'reasoning-end') {
          const activeReasoning = activeReasoningContent[part.id];


          if (activeReasoning == null) {
            controller.enqueue({
              part: {
                type: 'error',
                error: `reasoning part ${part.id} not found`,
              },
              partialOutput: undefined,
            });

I will submit a PR with a fix for this issue

AI SDK Version

  • ai: 5.0.119 - 5.0.123

I tested this issue on versions 5.0.119 to 5.0.123 as OpenCode is using version 5.0.119 currently, and using versions >6.0.0 seems to introduce breaking changes in OpenCode. However, this issue should theoretically be applicable to the latest versions too as there are similarly no checks if reasoning-start is emitted.

Code of Conduct

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

jovanwongzixi avatar Jan 27 '26 09:01 jovanwongzixi

Identify issue type

Identified as Bug
Confidence: High

Rationale

This is a concrete failure in existing reasoning-stream handling: an empty thinking block creates an unmatched end event and triggers an error.

Evidence

  • An LLM response containing an empty <think></think> block reproducibly produces the error reasoning part reasoning-0 not found.
  • The middleware emits a reasoning-end event even though no reasoning-start event was emitted because the reasoning text is empty.
  • The failure is reported in AI SDK versions 5.0.119 through 5.0.123, with corresponding source locations identified.

lgrammel avatar Jul 22 '26 11:07 lgrammel

There is still an empty-block case after #12055: an empty <think></think> block after a nonempty reasoning block emits reasoning-end without its matching reasoning-start.

On published [email protected]:

  • <think></think>Answer. works.
  • <think>Reason.</think>Before.<think></think>After. emits reasoning part reasoning-1 not found in fullStream.

The guard uses isFirstReasoning, which stays false after the first nonempty block. The later empty block therefore misses the start event. I am adding this here because it is the same missing-start defect. I also found the open related PR #13110, which handles missing starts in the consumer; this reproduction identifies a remaining source of those events in the middleware.

No API key is needed. Install [email protected] and [email protected], save as repro.mts, and run node repro.mts with Node 24:

import { extractReasoningMiddleware, streamText, wrapLanguageModel } from 'ai';
import { MockLanguageModelV4 } from 'ai/test';

for (const text of ['<think></think>Answer.', '<think>Reason.</think>Before.<think></think>After.']) {
  const model = new MockLanguageModelV4({ doStream: { stream: new ReadableStream({ start(controller) {
    controller.enqueue({ type: 'stream-start', warnings: [] });
    controller.enqueue({ type: 'text-start', id: 'a' });
    controller.enqueue({ type: 'text-delta', id: 'a', delta: text });
    controller.enqueue({ type: 'text-end', id: 'a' });
    controller.enqueue({ type: 'finish', finishReason: { unified: 'stop', raw: 'stop' }, usage: {
      inputTokens: { total: 1, noCache: 1, cacheRead: 0, cacheWrite: 0 },
      outputTokens: { total: 1, text: 1, reasoning: 0 },
    } });
    controller.close();
  } }) } });
  const result = streamText({
    model: wrapLanguageModel({ model, middleware: extractReasoningMiddleware({ tagName: 'think' }) }),
    prompt: 'Synthetic prompt.',
    maxRetries: 0,
  });
  const errors: unknown[] = [];
  for await (const event of result.fullStream) {
    if (event.type === 'error') errors.push(event.error);
  }
  console.log({ input: text, errors });
}

Expected: neither input produces error chunks. Actual:

{ input: '<think></think>Answer.', errors: [] }
{
  input: '<think>Reason.</think>Before.<think></think>After.',
  errors: [ 'reasoning part reasoning-1 not found' ]
}

The later-empty-block case fails with one large delta and character-by-character deltas, and with startWithReasoning both false and true. All four first-empty-block controls pass. Verified on Node 22.20.0 and 24.13.0; the reproduction passes strict TypeScript checking. The middleware source is unchanged at current main commit 12845693d7a6a517dc633d6b6a2e4f5bfd24d2ec (source comparison, not a runtime build of main).

I used AI assistance to investigate and prepare the reproduction and tests.

brennanbutler01 avatar Sep 18 '26 00:09 brennanbutler01