ai icon indicating copy to clipboard operation
ai copied to clipboard

[Bug] @ai-sdk/cerebras: assistant reasoning serialized as 'reasoning_content' but Cerebras expects 'reasoning' (zai-glm-4.7 multi-step 400)

Open fogx opened this issue 6 months ago • 6 comments

Description

GLM 4.7 on Cerebras (cerebras:zai-glm-4.7) breaks after step 1 of any multi-step run. step 1 returns a tool call, step 2 sends the assistant turn back as history and gets a 400:

POST https://api.cerebras.ai/v1/chat/completions
400 Bad Request
{
  "code": "wrong_api_format",
  "message": "messages.3.assistant.reasoning_content: property 'messages.3.assistant.reasoning_content' is unsupported"
}

@ai-sdk/openai-compatible serializes the assistant reasoning as reasoning_content here:

https://github.com/vercel/ai/blob/main/packages/openai-compatible/src/chat/convert-to-openai-compatible-chat-messages.ts#L242-L248

messages.push({
  role: 'assistant',
  content: toolCalls.length > 0 ? text || null : text,
  ...(reasoning.length > 0 ? { reasoning_content: reasoning } : {}),
  tool_calls: toolCalls.length > 0 ? toolCalls : undefined,
  ...metadata,
});

cerebras's chat-completions API doesnt accept reasoning_content on input. their assistant-message schema uses a reasoning field instead (string | null), and the docs explicitly say "Include this when passing back assistant messages that contained reasoning":

https://inference-docs.cerebras.ai/api-reference/chat-completions

so streamText runs fine for a one-shot call and dies on any agentic flow that needs >=2 steps with a reasoning model behind cerebras.

Reproduction

import { cerebras } from '@ai-sdk/cerebras';
import { streamText, stepCountIs, tool } from 'ai';
import { z } from 'zod';

const result = streamText({
  model: cerebras('zai-glm-4.7'),
  tools: {
    create_thing: tool({
      inputSchema: z.object({ name: z.string() }),
      execute: async ({ name }) => ({ id: 'abc', name }),
    }),
  },
  stopWhen: stepCountIs(5),
  messages: [{ role: 'user', content: 'create a thing called foo, then say done' }],
});

for await (const _ of result.fullStream) {}
console.log('steps:', (await result.steps).length);
// expected: >= 2 (tool call step + final message step)
// actual: 1, run terminates with AI_APICallError 400 wrong_api_format

Suggested fix

Same shape as the deepseek-v4 fix in #14741 (model-aware reasoning_content handling). For cerebras, serialize reasoning parts as the reasoning field on assistant messages, not reasoning_content. Either in the @ai-sdk/cerebras package via a custom message converter, or in @ai-sdk/openai-compatible if a flag/option fits there cleanly.

cerebras also exposes clear_thinking (boolean, default true, drops historical reasoning from the prompt context) and reasoning_effort ("low" | "medium" | "high" | "none") which give callers per-request control once the field name is correct.

Workaround

Strip reasoning content parts from assistant turns via a wrapLanguageModel middleware that filters them in transformParams.prompt. Drops the interleaved-thinking continuity across steps but unblocks multi-step runs.

const stripReasoningMiddleware: LanguageModelMiddleware = {
  specificationVersion: 'v3',
  transformParams: async ({ params }) => ({
    ...params,
    prompt: params.prompt.map((m) =>
      m.role === 'assistant' && Array.isArray(m.content)
        ? { ...m, content: m.content.filter((p) => p.type !== 'reasoning') }
        : m
    ),
  }),
};

Related

  • #14741 - same class of bug in @ai-sdk/deepseek (deepseek-v4 multi-turn requires reasoning_content in input)
  • #11783 - same model+provider, different error (server 500 / response Zod parse fail)
  • #11682 - parsing reasoning_content from response (closed)

AI SDK Version

ai: ^5.x
@ai-sdk/cerebras: 2.0.34
@ai-sdk/openai-compatible: 2.0.30

Code of Conduct

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

fogx avatar May 05 '26 20:05 fogx

I believe this is not perse a GLM issue but also happening for gpt-oss-120b.

st3phan avatar May 07 '26 08:05 st3phan

I believe this is not perse a GLM issue but also happening for gpt-oss-120b.

yes, this happens to all openAI-compatible thinking models with different fieldnames, like the mentioned deepseek model. Just that the implementation there only fixed it for one particular model. best solution would be to make this configurable in @ai-sdk/openai-compatible i guess.

fogx avatar May 07 '26 13:05 fogx

Great catch. This is a common serialization mismatch when providers return reasoning_content (Cerebras, DeepSeek, some OpenAI-compatible backends) but the SDK normalizer expects reasoning.

A few approaches that have worked in production:

  1. Normalize at the gateway layer — if you proxy through a multi-provider gateway, map reasoning_content → reasoning before it hits the SDK. This avoids per-SDK fixes.

  2. Content block union — treat both field names as valid in the parser:

const reasoning = block.reasoning ?? block.reasoning_content;
  1. Provider capability negotiation — some providers (e.g. Cerebras, SambaNova) use OpenAI's wire format but diverge on extended fields. Maintaining a small provider quirks table helps:
const PROVIDER_REASONING_FIELD: Record<string, string> = {
  cerebras: 'reasoning_content',
  deepseek: 'reasoning_content',
  openai: 'reasoning',
};

The broader pattern: OpenAI-compatible ≠ OpenAI-identical, especially for newer features like reasoning traces. Worth testing against the actual provider response shape rather than assuming OpenAI's schema.

XidaoApi avatar May 07 '26 14:05 XidaoApi

+1 to cerebras API issue with opencode CLI too

functionstackx avatar May 09 '26 21:05 functionstackx

closed as of https://github.com/vercel/ai/pull/15416

aayush-kapoor avatar May 19 '26 03:05 aayush-kapoor

Identify issue type

Identified as Bug
Confidence: High

Rationale

This is a concrete provider serialization defect that breaks existing multi-step agent flows, rather than a request for a new capability.

Evidence

  • Multi-step Cerebras reasoning runs fail after the first tool call with a 400 because assistant history contains the unsupported reasoning_content field.
  • Cerebras expects historical assistant reasoning in the reasoning field, while @ai-sdk/openai-compatible serializes it as reasoning_content.
  • A commenter reports the issue also affects another Cerebras model, and the issue was closed after PR #15416.

lgrammel avatar Jul 22 '26 11:07 lgrammel