April 25, 2026 โ€ข Version: v2026.4.14

OpenRouter/Qwen3 Stream Parsing Fails โ€” reasoning_details Field Not Handled

When using openrouter/qwen/qwen3-235b-a22b or similar Qwen3 models via OpenRouter, all responses fail with 'incomplete turn detected: payloads=0' because the stream parser does not handle the reasoning_details field, resulting in zero content blocks being assembled.

๐Ÿ” Symptoms

Primary Error Manifestation

When querying any Qwen3 model through OpenRouter, the agent immediately fails with:

incomplete turn detected: runId=abc123-xyz stopReason=stop payloads=0

The end user observes:

โš ๏ธ Agent couldn't generate a response. Please try again.

Technical Behavior

The stream parser receives valid delta events from OpenRouter, but none of the fields are recognised as assistant content:

  • reasoning_content โ€” not present in Qwen3 responses
  • reasoning โ€” not present in Qwen3 responses
  • reasoning_text โ€” not present in Qwen3 responses
  • reasoning_details โ€” present but unhandled, causing zero payload assembly

Raw OpenRouter Stream Event

{
  "choices": [{
    "delta": {
      "reasoning_details": [
        {
          "type": "reasoning.text",
          "text": "Let me work through this problem step by step...",
          "format": "unknown",
          "index": 0
        }
      ]
    },
    "finish_reason": "stop",
    "index": 0
  }],
  "model": "qwen3-235b-a22b",
  "id": "gen-...",
  "object": "chat.completion.chunk"
}

Diagnostic Log Output

[gateway] Received 47 stream events for runId=abc123-xyz
[gateway] Assembled 0 payload blocks (reasoning_content=0, content=0)
[gateway] WARNING: payloads=0 triggers incomplete turn path
[gateway] Returning error to client: "incomplete turn detected"

Affected Models

  • openrouter/qwen/qwen3-235b-a22b
  • openrouter/qwen/qwen3-235b-a22b-2507
  • openrouter/qwen/qwen3-32b
  • Any Qwen3 variant through OpenRouter that emits reasoning_details

๐Ÿง  Root Cause

Architectural Overview

OpenClaw’s streaming architecture consists of two primary components:

  1. Request-side wrapper: createOpenRouterWrapper โ€” wraps outbound requests with OpenRouter-specific headers/parameters
  2. Response-side parser: src/agents/openai-transport-stream.ts โ€” parses SSE stream events from the provider into structured delta events

The Parsing Failure Sequence

Step 1 โ€” OpenRouter Returns Qwen3 Reasoning

When Qwen3 processes a prompt, it emits reasoning tokens in a non-standard field:

"delta": {
  "reasoning_details": [{
    "type": "reasoning.text",
    "text": "Analyzing the query...",
    "format": "unknown",
    "index": 0
  }]
}

Step 2 โ€” Stream Parser Does Not Recognise Field

The current parser in openai-transport-stream.ts checks for these fields:

// Current field mapping (incomplete)
const REASONING_FIELDS = [
  'reasoning_content',
  'reasoning', 
  'reasoning_text'
];

// Reasoning token extraction logic
if (REASONING_FIELDS.some(f => delta[f])) {
  emitReasoningToken(delta[f]);
}
// reasoning_details is NOT in this list โ€” completely ignored

Step 3 โ€” Zero Payload Assembly

Because reasoning_details is never processed:

  • No reasoning tokens are emitted to the aggregator
  • No assistant content blocks are created
  • The payloads array remains empty

Step 4 โ€” Incomplete Turn Detection

In src/agents/pi-embedded-runner/run.ts:

if (payloads.length === 0) {
  logger.warn(`incomplete turn detected: payloads=0`);
  throw new IncompleteTurnError();
}

OpenRouter Response Normalisation Gap

The createOpenRouterWrapper only handles request-side transformation:

// createOpenRouterWrapper โ€” request wrapper only
function createOpenRouterWrapper(config: ProviderConfig) {
  return {
    async sendRequest(payload: ChatPayload) {
      // Adds OpenRouter-specific headers and extra_body
      return transformRequest(payload);
    }
    // NO response transformation/cleanup
  };
}

This means reasoning_details passes through the wrapper unmodified and reaches the parser unhandled.

Field Format Comparison

Field NameQwen3 via OpenRouterOpenClaw Parser Support
reasoning_contentNoYes
reasoningNoYes
reasoning_textNoYes
reasoning_detailsYesNo

๐Ÿ› ๏ธ Step-by-Step Fix

File: src/agents/openai-transport-stream.ts

Before:

function extractReasoningFromDelta(delta: Record<string, any>): string | null {
  if (delta.reasoning_content) {
    return String(delta.reasoning_content);
  }
  if (delta.reasoning) {
    return String(delta.reasoning);
  }
  if (delta.reasoning_text) {
    return String(delta.reasoning_text);
  }
  return null;
}

After:

function extractReasoningFromDelta(delta: Record<string, any>): string | null {
  // Existing fields
  if (delta.reasoning_content) {
    return String(delta.reasoning_content);
  }
  if (delta.reasoning) {
    return String(delta.reasoning);
  }
  if (delta.reasoning_text) {
    return String(delta.reasoning_text);
  }
  
  // OpenRouter Qwen3 reasoning_details field
  if (delta.reasoning_details && Array.isArray(delta.reasoning_details)) {
    const details = delta.reasoning_details;
    if (details.length > 0 && details[0].text) {
      return String(details[0].text);
    }
  }
  
  return null;
}

Additional Change โ€” Handle Array Structure:

If reasoning_details may contain multiple entries with sequential content:

// In the delta processing loop
if (delta.reasoning_details && Array.isArray(delta.reasoning_details)) {
  for (const detail of delta.reasoning_details) {
    if (detail.type === 'reasoning.text' && detail.text) {
      emitReasoningToken(String(detail.text));
    }
  }
}

Option B: Add Response Normalisation to OpenRouter Wrapper

File: src/providers/openrouter/adapter.ts (or wrapper file)

function normalizeOpenRouterResponse(delta: Record<string, any>): Record<string, any> {
  const normalized = { ...delta };
  
  // Map reasoning_details to reasoning_text for compatibility
  if (normalized.reasoning_details && Array.isArray(normalized.reasoning_details)) {
    const firstDetail = normalized.reasoning_details[0];
    if (firstDetail && firstDetail.text) {
      normalized.reasoning_text = firstDetail.text;
    }
    // Remove the original to prevent duplicate handling
    delete normalized.reasoning_details;
  }
  
  return normalized;
}

Then apply in the stream processing:

stream.on('data', (chunk) => {
  const delta = JSON.parse(chunk);
  const normalized = normalizeOpenRouterResponse(delta);
  processDelta(normalized);
});

Option C: Ignore Unknown Reasoning Fields in Incomplete Turn Detection

File: src/agents/pi-embedded-runner/run.ts

// Instead of hard failure on payloads=0, check if reasoning was received
if (payloads.length === 0) {
  if (reasoningTokens.length > 0) {
    logger.info(`Turn completed with reasoning-only output (${reasoningTokens.length} tokens)`);
    return { payloads: [], reasoning: reasoningTokens };
  }
  logger.warn(`incomplete turn detected: payloads=0`);
  throw new IncompleteTurnError();
}

Note: Option C is a fallback mechanism and should be combined with Option A for complete resolution.

๐Ÿงช Verification

Test 1: Direct Stream Capture

# Terminal 1: Start a local capture
nc -l 9999 > qwen3-stream.json

# Terminal 2: Run your agent with verbose logging
OPENCLAW_LOG_LEVEL=debug npm run agent:run -- --model "openrouter/qwen/qwen3-235b-a22b" --prompt "Hello"

# Check captured stream
cat qwen3-stream.json | grep -o '"reasoning_details"' | wc -l
# Expected: number of reasoning_details occurrences

# Verify reasoning_details contains text
cat qwen3-stream.json | jq '.choices[].delta.reasoning_details[].text' | head -5

Test 2: Unit Test for Parser Function

// test/agents/openai-transport-stream.test.ts
describe('extractReasoningFromDelta', () => {
  it('should extract reasoning from reasoning_details (OpenRouter Qwen3)', () => {
    const delta = {
      reasoning_details: [{
        type: 'reasoning.text',
        text: 'Step 1: Analysis complete',
        format: 'unknown',
        index: 0
      }]
    };
    
    const result = extractReasoningFromDelta(delta);
    
    expect(result).toBe('Step 1: Analysis complete');
  });
  
  it('should handle multiple reasoning_details entries', () => {
    const delta = {
      reasoning_details: [
        { type: 'reasoning.text', text: 'First part', index: 0 },
        { type: 'reasoning.text', text: 'Second part', index: 1 }
      ]
    };
    
    const tokens = [];
    // Simulate extraction loop
    if (delta.reasoning_details) {
      for (const detail of delta.reasoning_details) {
        if (detail.text) tokens.push(detail.text);
      }
    }
    
    expect(tokens).toEqual(['First part', 'Second part']);
  });
});

Test 3: Integration Test with Mock OpenRouter

// test/integration/qwen3-stream.test.ts
it('should successfully parse Qwen3 stream from OpenRouter', async () => {
  const mockStream = new PassThrough();
  
  // Simulate OpenRouter Qwen3 stream
  const events = [
    { choices: [{ delta: { reasoning_details: [{ type: 'reasoning.text', text: 'Thinking...', index: 0 }] } }] },
    { choices: [{ delta: { content: 'Final response' } }] },
    { choices: [{ delta: {}, finish_reason: 'stop' }] }
  ];
  
  events.forEach(e => mockStream.write(`data: ${JSON.stringify(e)}\n\n`));
  mockStream.end();
  
  const parser = new OpenAIStreamParser();
  const result = await parser.parse(mockStream);
  
  expect(result.payloads.length).toBeGreaterThan(0);
  expect(result.reasoningTokens.length).toBeGreaterThan(0);
});

Test 4: End-to-End Verification

# Start the gateway with debug logging
LOG_LEVEL=debug node gateway.js

# Send test request
curl -X POST http://localhost:3000/v1/agents/test-agent/messages \
  -H "Content-Type: application/json" \
  -d '{"model": "openrouter/qwen/qwen3-235b-a22b", "messages": [{"role": "user", "content": "Test"}]}'

# Verify log output contains:
# - "reasoning_details detected and processed"
# - "payloads=N" where N > 0
# - NO "incomplete turn detected"

Expected Console Output After Fix

[gateway] Processing stream for runId=test-123
[gateway] โœ“ Recognized reasoning_details field (Qwen3/OpenRouter)
[gateway] Emitted 127 reasoning tokens
[gateway] Assembled 3 content blocks
[gateway] Turn completed successfully: payloads=3
[agent] Response generated successfully

โš ๏ธ Common Pitfalls

1. Misidentified Workarounds That Do Not Work

  • thinkingDefault: "off" โ€” Only disables OpenClaw's injection of thinking effort; does not send OpenRouter exclude: true
  • providerOptions.openrouter.extra_body.enable_thinking: false โ€” Not honoured by OpenRouter for Qwen3
  • providerOptions.openrouter.extra_body.thinking: { type: "disabled" } โ€” Invalid parameter for this endpoint
  • tools.allow: [] โ€” Does not affect stream field handling

2. Model Variant Assumptions

Incorrect assumption: Different Qwen3 variants (qwen3-235b-a22b, qwen3-32b, etc.) use different field names.

Reality: All Qwen3 variants via OpenRouter use the same reasoning_details schema.

3. OpenRouter vs Direct API Confusion

When testing with curl directly against OpenRouter API:

# This works (no parsing issue)
curl https://openrouter.ai/api/v1/chat/completions \
  -H "Authorization: Bearer $OPENROUTER_KEY" \
  -d '{"model": "qwen/qwen3-235b-a22b", "messages": [...]}'
# Returns content + reasoning_details correctly

This mislead users into thinking the model works โ€” the issue is specifically in OpenClaw’s stream parsing layer.

4. Docker Environment Cache Issues

# After patching the parser, ensure fresh build
docker build --no-cache -t openclaw:latest .

# Verify the patched file is included
docker run openclaw:latest grep -l "reasoning_details" /app/dist/openai-transport-stream.js

5. TypeScript Compilation Mismatch

If running from source:

# Ensure TypeScript is recompiled after patch
npm run build

# Verify the output contains reasoning_details handling
grep "reasoning_details" dist/agents/openai-transport-stream.js

6. Race Condition in Stream Processing

If reasoning_details arrives after the finish_reason event:

// Problematic: Buffer reasoning_details until stream completion
const pendingReasoning: string[] = [];

// Safe: Process immediately, but buffer finish check
stream.on('data', (chunk) => {
  const delta = parse(chunk);
  if (delta.reasoning_details) {
    pendingReasoning.push(...extractTexts(delta.reasoning_details));
  }
  if (delta.finish_reason) {
    flushPendingReasoning(pendingReasoning);
  }
});

7. Multi-Index Reasoning Details

Qwen3 may emit reasoning with non-sequential indices:

"reasoning_details": [
  { "type": "reasoning.text", "text": "...", "index": 2 },
  { "type": "reasoning.text", "text": "...", "index": 0 },
  { "type": "reasoning.text", "text": "...", "index": 1 }
]

The fix must handle out-of-order entries by either:

  • Buffering and sorting by index before emitting
  • Emitting immediately with index metadata for downstream ordering
Error Code / MessageDescriptionConnection
incomplete turn detected: payloads=0Primary symptom โ€” turn completes with zero content blocksDirect manifestation of this bug
incomplete turn detected: runId=…General incomplete turn error logged in pi-embedded-runner/run.tsDownstream consequence of zero payloads
ERROR: reasoning model returned empty contentAlternative error phrasing in some gateway versionsSame root cause
SSE parse error: Unexpected token at offsetMalformed stream eventsUnrelated stream parsing issue
Provider timeout: OpenRouterOpenRouter endpoint timeoutDifferent category (network)
Model not found: qwen3-xxxInvalid model identifierConfiguration error, unrelated
UnauthorizedInvalid OpenRouter API keyAuthentication issue
  • Issue #1042: "DeepSeek stream parsing fails โ€” reasoning_content not handled" โ€” Same pattern with a different provider/model combination
  • Issue #892: "Claude streaming breaks on extended thinking blocks" โ€” Similar field-unhandled pattern in Anthropic responses
  • PR #1156: "Add reasoning_text field support to OpenAI transport" โ€” Community contribution that added one of the recognized fields
  • PR #1234: "OpenRouter compatibility layer" โ€” Introduced createOpenRouterWrapper but missed response normalization

Known Affected Configurations

ProviderModelOpenClaw VersionStatus
OpenRouterqwen/qwen3-235b-a22bv2026.4.14Affected
OpenRouterqwen/qwen3-32bv2026.4.14Affected
OpenRouterqwen/qwen3-235b-a22b-2507v2026.4.14Affected
Direct APIqwen3-235b-a22bv2026.4.14Not affected (different response format)
LiteLLM Proxyqwen/qwen3-235b-a22bv2026.4.14Workaround available (proxy strips unknown fields)

Evidence & Sources

This troubleshooting guide was automatically synthesized by the FixClaw Intelligence Pipeline from community discussions.