ai icon indicating copy to clipboard operation
ai copied to clipboard

Item 'rs_...' of type 'reasoning' was provided without its required following item

Open iborqe opened this issue 1 year ago • 49 comments

Description

When using the openai.responses() API with a reasoning model, a tool call results in an error.
However, using openai.chat() avoids the error — but tool calling and reasoning streaming are not available in that mode.


Code

import { openai } from "@ai-sdk/openai";
import { streamText, Output, stepCountIs, convertToModelMessages } from "ai";
import { devTools } from "../tools";
import { z } from "zod";

// Allow streaming responses up to 60 seconds for more complex generations
export const maxDuration = 60;

export function errorHandler(error: unknown) {
  if (error == null) {
    return "unknown error";
  }
  if (typeof error === "string") {
    return error;
  }
  if (error instanceof Error) {
    return error.message;
  }
  return JSON.stringify(error);
}

// Structured output schema for website code
const WebsiteSchema = z.object({
  html: z.string().describe("Whole HTML code"),
});

export async function POST(req: Request) {
  try {
    const { messages } = await req.json();

    // Validate messages
    if (!Array.isArray(messages)) {
      return new Response("Invalid messages format", { status: 400 });
    }

    const result = streamText({
      model: openai.responses(process.env.OPENAI_MODEL || "gpt-4o"),
      system: "...",
      messages: convertToModelMessages(messages),
      stopWhen: stepCountIs(100),
      tools: devTools,
      abortSignal: req.signal, // Add abort signal for proper cancellation
      experimental_output: Output.object({
        schema: WebsiteSchema,
      }),
    });

    return result.toUIMessageStreamResponse({
      onError: errorHandler,
    });
  } catch (error) {
    console.error("Dev API error:", error);
    return new Response(errorHandler(error), { status: 500 });
  }
}

Problem

When using reasoning models with openai.responses(), calling a tool throws the following error:

[Error [AI_APICallError]: Item 'rs_...' of type 'reasoning' was provided without its required following item.] {
  cause: undefined,
  url: 'https://api.openai.com/v1/responses',
  requestBodyValues: [Object],
  statusCode: 400,
  responseHeaders: [Object],
  responseBody: '{
    "error": {
      "message": "Item 'rs_...' of type 'reasoning' was provided without its required following item.",
      "type": "invalid_request_error",
      "param": "input",
      "code": null
    }
  }',
  isRetryable: false,
  data: [Object]
}

Workaround

Using openai.chat() avoids the error entirely, but does not support streaming reasoning or tool calls, which limits its utility in certain applications.


AI SDK Versions

  • ai: ^5.0.0-beta.7
  • @ai-sdk/openai: ^2.0.0-beta.5
  • @ai-sdk/react: ^2.0.0-beta.7

iborqe avatar Jul 07 '25 13:07 iborqe

@lgrammel is there any hot-fix for this issue?

iborqe avatar Jul 07 '25 14:07 iborqe

Hi can you check the latest ai sdk 5 beta and latest ai sdk 5 beta openai provider? we made fixes in that area

lgrammel avatar Jul 10 '25 12:07 lgrammel

This is still happening in the latest beta releases

garymjr avatar Jul 10 '25 23:07 garymjr

@lgrammel still there

  cause: undefined,
  url: 'https://api.openai.com/v1/responses',
  requestBodyValues: [Object],
  statusCode: 400,
  responseHeaders: [Object],
  responseBody: '{\n' +
    '  "error": {\n' +
    `    "message": "Item 'rs_68705394944881a0bad1de4b641bb7a80d2db2349dd4408e' of type 'reasoning' was provided without its required following item.",\n` +
    '    "type": "invalid_request_error",\n' +
    '    "param": "input",\n' +
    '    "code": null\n' +
    '  }\n' +
    '}',
  isRetryable: false,
  data: [Object]
}```

iborqe avatar Jul 10 '25 23:07 iborqe

I am also experiencing the same issue and am on the latest version of the v5 beta.

nneven avatar Jul 12 '25 07:07 nneven

is there any update?

iborqe avatar Jul 12 '25 11:07 iborqe

we're seeing this as well in opencode

thdxr avatar Jul 12 '25 22:07 thdxr

ai: "^5.0.0-beta.16" still have the issue

iborqe avatar Jul 13 '25 21:07 iborqe

@thdxr I am facing this while using opencode too. It seems the issue is at openai's end and the workaround is to set reasoning-effort=none Related: https://github.com/openai/codex/issues/1498

dineshgadge avatar Jul 14 '25 03:07 dineshgadge

Starting to look into this, suspect it is related to tool calling and openai item ids.

Can someone share a minimal reproduction that leaves nothing out?

lgrammel avatar Jul 14 '25 12:07 lgrammel

The following example works without issues with tool calling:

import { openai, OpenAIResponsesProviderOptions } from '@ai-sdk/openai';
import { stepCountIs, ModelMessage, streamText, tool } from 'ai';
import 'dotenv/config';
import * as readline from 'node:readline/promises';
import { z } from 'zod/v4';

const terminal = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const messages: ModelMessage[] = [];

async function main() {
  while (true) {
    const userInput = await terminal.question('You: ');

    messages.push({ role: 'user', content: userInput });

    const result = streamText({
      model: openai.responses('o3'),
      tools: {
        weather: tool({
          description: 'Get the weather in a location',
          inputSchema: z.object({
            location: z
              .string()
              .describe('The location to get the weather for'),
          }),
          execute: async ({ location }) => ({
            location,
            temperature: 72 + Math.floor(Math.random() * 21) - 10,
          }),
        }),
      },
      stopWhen: stepCountIs(5),
      messages,
      providerOptions: {
        openai: {
          store: false, // No data retention - makes interaction stateless
          reasoningEffort: 'medium',
          reasoningSummary: 'auto', // output reasoning
          include: ['reasoning.encrypted_content'], // Hence, we need to retrieve the model's encrypted reasoning to be able to pass it to follow-up requests
        } satisfies OpenAIResponsesProviderOptions,
      },
    });

    process.stdout.write('\nAssistant: ');
    for await (const delta of result.textStream) {
      process.stdout.write(delta);
    }
    process.stdout.write('\n\n');

    messages.push(...(await result.response).messages);
  }
}

main().catch(console.error);

lgrammel avatar Jul 14 '25 12:07 lgrammel

@hamidrezaborghei can you try setting the following provider options?

 const result = streamText({
    // ....
    providerOptions: {
      openai: {
        store: false, // No data retention - makes interaction stateless
        reasoningEffort: 'medium',
        reasoningSummary: 'auto', // output reasoning
        include: ['reasoning.encrypted_content'], // Hence, we need to retrieve the model's encrypted reasoning to be able to pass it to follow-up requests
      } satisfies OpenAIResponsesProviderOptions,
    }
})

lgrammel avatar Jul 14 '25 13:07 lgrammel

Problem reproduced. Tool calling with o3 and no provider options results in this error.

lgrammel avatar Jul 14 '25 13:07 lgrammel

Most likely the issue is that function calls in reasoning sequences require a call_id and an item id.

lgrammel avatar Jul 14 '25 13:07 lgrammel

#7285 is a basic fix for stream text. plan to expand to generatetext, test, and ship tomorrow.

lgrammel avatar Jul 14 '25 14:07 lgrammel

Thank you for your efforts to solve the problem, but the problem is only solved for the first message, and when we send the second message, we see the exact same problem again. I think we should reopen the issue @lgrammel

iborqe avatar Jul 16 '25 00:07 iborqe

@hamidrezaborghei i tested this with several messages. can you provide a complete code snippet that reproduces the problem?

lgrammel avatar Jul 16 '25 05:07 lgrammel

@dineshgadge

import { stepCountIs, streamText, convertToModelMessages } from "ai";
import { chatTools } from "../tools";

// Allow streaming responses up to 30 seconds
export const maxDuration = 30;
export function errorHandler(error: unknown) {
  if (error == null) {
    return "unknown error";
  }

  if (typeof error === "string") {
    return error;
  }

  if (error instanceof Error) {
    return error.message;
  }

  return JSON.stringify(error);
}
export async function POST(req: Request) {
  try {
    const { messages } = await req.json();

    // Validate messages
    if (!Array.isArray(messages)) {
      return new Response("Invalid messages format", { status: 400 });
    }

    const result = streamText({
      system: "...",
      model: openai.responses(process.env.OPENAI_MODEL || "gpt-4o"),
      messages: convertToModelMessages(messages),
      stopWhen: stepCountIs(100),
      tools: chatTools,
      abortSignal: req.signal, // Add abort signal for proper cancellation
    });

    return result.toUIMessageStreamResponse({
      onError: errorHandler,
      sendSources: true,
    });
  } catch (error) {
    console.error("Chat API error:", error);
    return new Response(errorHandler(error), { status: 500 });
  }
}

ask for a tool calling in second message after first message called a tool and it will get exact same error.

iborqe avatar Jul 16 '25 06:07 iborqe

Hi,

It's also happening to me, I am using gpt-5-nano model.

I am using following dependencies:

    "@ai-sdk/openai": "^2.0.15",
    "@ai-sdk/react": "^2.0.15",
    "ai": "^5.0.15",

Here is the implementation.

export async function chatStream({ messages, model }: ChatRequestSchema) {
  const openai = createOpenAI({ apiKey: env.OPENAI_API_KEY });

  const result = streamText({
    model: openai(model),
    messages: convertToModelMessages(messages),
    system: "You are a helpful assistant that can answer questions and help with tasks",
  });

  return result.toUIMessageStreamResponse({
    sendSources: true,
    sendReasoning: true,
  });
}

This was the message:

 {
    "id": "msg-06JMpoUmfT8ajKij",
    "role": "user",
    "parts": [
      {
        "text": "can you reasoning how to elaborate a biscuit",
        "type": "text"
      }
    ]
  }

This was the error.

app:dev: [Error [AI_APICallError]: Item 'rs_68a170b8b5f081a2acba5b8d0c950e5308d016c272d19215' of type 'reasoning' was provided without its required following item.] {
app:dev:   cause: undefined,
app:dev:   url: 'https://api.openai.com/v1/responses',
app:dev:   requestBodyValues: [Object],
app:dev:   statusCode: 400,
app:dev:   responseHeaders: [Object],
app:dev:   responseBody: '{\n' +
app:dev:     '  "error": {\n' +
app:dev:     `    "message": "Item 'rs_68a170b8b5f081a2acba5b8d0c950e5308d016c272d19215' of type 'reasoning' was provided without its required following item.",\n` +
app:dev:     '    "type": "invalid_request_error",\n' +
app:dev:     '    "param": "input",\n' +
app:dev:     '    "code": null\n' +
app:dev:     '  }\n' +
app:dev:     '}',
app:dev:   isRetryable: false,
app:dev:   data: [Object]
app:dev: }

Thanks in advance, Regards, Javier

jsa4000 avatar Aug 17 '25 06:08 jsa4000

I am still facing this issue while using gpt-5-mini

My package.json -

"@ai-sdk/openai": "^2.0.16", "@ai-sdk/react": "^2.0.16", "ai": "^5.0.16",

anish2110 avatar Aug 19 '25 08:08 anish2110