Skip to content

Aborting Conversations stream mid-tool-call drops it from server state, causing 400 error on next turn (Same as Python #3561) #2571

Closed as not planned

Description

@sipa-echo-ngbm

Confirm this is a Node library issue and not an underlying OpenAI API issue

  • This is an issue with the Node library

Describe the bug

When using the Conversations API (client.responses.create with a conversation_id), if a stream is aborted mid-flight after a function_call item has started streaming, the OpenAI server discards the tool call from the conversation state.

However, the client has already received the call_id. When the client attempts the next turn by providing the function_call_output matching that ID, the server rejects it with a 400 BadRequest because it has no record of the tool call. This completely breaks client-side state management frameworks (like Agents/LangChain/PydanticAI) that attempt to gracefully stitch interrupted tool calls.

Note: I have fully verified this is a server-side state mismatch, as it happens identically in the Python SDK. I am opening this here to track the impact on the Node.js ecosystem and cross-link it to the Python repository.

To Reproduce

  1. Create a conversation via client.conversations.create() and save the ID.
  2. Start a streaming responses.create request that triggers a tool call.
  3. Listen for the response.output_item.added event and capture the call_id.
  4. Immediately abort the stream (stream.controller.abort()).
  5. (Optional) Check conversations.items.list() — observe the function_call is missing.
  6. Send the next turn using the same conversation ID, passing the function_call_output for the captured call_id.
  7. Receive 400 No tool call found for function call output with call_id...

Code snippets

import OpenAI from "openai";
const client = new OpenAI(); 

async function runTest() {
  const conv = await client.conversations.create({});
  const convId = conv.id;
  console.log(`[Client] Created conversation ID: ${convId}`);

  const stream = await client.responses.create({
    model: "gpt-4.1-mini",
    input: "What is the weather in Amsterdam?",
    conversation: convId,
    tools: [{
      type: "function",
      name: "get_weather",
      description: "Get the weather",
      parameters: { type: "object", properties: { location: { type: "string" } }, required: ["location"] }
    }],
    tool_choice: "required",
    stream: true,
  });

  let toolCallId = null;
  for await (const chunk of stream) {
    const item = chunk.item || chunk.output?.[0];
    if (item?.type === "function_call" && item.call_id) {
      toolCallId = item.call_id;
      console.log(`[Client] Captured tool call ID: ${toolCallId}. Aborting!`);
      stream.controller.abort();
      break;
    }
  }

  await new Promise(resolve => setTimeout(resolve, 1000));

  try {
    await client.responses.create({
      model: "gpt-4.1-mini",
      conversation: convId, 
      input: [
        { type: "function_call_output", call_id: toolCallId, output: '{"temp": 18}' },
        { type: "message", role: "user", content: "Is it cold?" }
      ]
    });
  } catch (error) {
    console.error(`\n[Result] API Error Caught!`);
    console.error(`Status: ${error.status} | Message: ${error.message}`);
  }
}
runTest();

OS

Windows

Node version

Node v22.22.0

Library version

openai v7.9.0

Activity

  1. added
    bug
    on Sep 2, 2026
  2. Shivang9983 commented on Sep 7, 2026

    @Shivang9983

    Hi @sipa-echo-ngbm and @maintainers, I would love to work on fixing this issue. Since this involves a server-side state drop vs client-side tracking mismatch (similar to python #3561), I can help investigate the fix/workaround for the Node SDK. Could you please assign this issue to me?

  3. sipa-echo-ngbm commented on Sep 8, 2026

    @sipa-echo-ngbm
    Author

    Hi @Shivang9983 you could work on this issue. Thank you

  4. HAYDEN-OAI commented on Sep 16, 2026

    @HAYDEN-OAI
    Contributor

    Thanks for the clear reproduction and for cross-linking the Python report, @sipa-echo-ngbm. We understand why this is disruptive for applications that need to recover from interrupted tool calls, and appreciate @Shivang9983 offering to help investigate.

    We reviewed the reported Node SDK version (v7.9.0) and the current streaming implementation, compared the Python report and the linked Agents JS fix, and checked relevant SDK changes since this issue was opened. We also ran the 56 existing streaming-core tests and three focused local transport checks against v7.9.0. All passed: the SDK delivers the observed event unchanged, aborts the transport, and forwards the subsequent tool-output request unchanged. These checks establish SDK behavior; they are not a fresh reproduction against the production API.

    The key distinction is between observing a streamed item and having that item committed to a conversation. The Responses API reference documents that response input and output items are added to the conversation after the response completes.

    In this reproduction:

    1. response.output_item.added exposes the tool's call_id while the item is still being generated; its arguments may not yet be complete.
    2. Aborting at that point closes the transport and requests cancellation of the foreground response. Breaking out of the loop also aborts the request. This can happen before conversation finalization; cancellation can also race with completion.
    3. When the call has not been committed, the next request supplies a function_call_output for a call that is absent from the conversation, leading to the reported 400.

    The linked Agents JS fix (#1241) addresses a different case: supplying missing outputs for known calls. It tracks response.output_item.done and does not recreate a call that was never committed. Similarly, the recent Node fixes for early-break cleanup (#2613) and terminal SSE events at EOF (#2726) do not change conversation persistence or resolve this early-abort case.

    For applications using server-managed conversation history:

    • Consume through response.completed before relying on that history to submit tool results. An item-done or arguments-done event alone is not a conversation commit acknowledgment.
    • After an interruption, inspect the persisted conversation before continuing. Do not execute a call based only on .added with incomplete arguments, or submit an output for a call that was never committed.
    • If generation should survive a disconnected stream, consider background mode and retrieve or resume the response until completion.

    We're closing this as not planned for a change in the Node SDK, rather than as fixed by an SDK release. The broader request for preserving unfinished calls concerns API interruption and recovery semantics. If you have a case where the call is missing after receiving response.completed, please share a minimal reproduction and request ID; that would warrant a separate investigation.

    Thank you again for raising this and helping clarify an important edge case.

  5. sipa-echo-zaoa commented on Sep 17, 2026

    @sipa-echo-zaoa

    @HAYDEN-OAI Thanks for the detailed investigation. I agree that closing this as not planned for the Node SDK is appropriate, and that the original minimal reproduction does not demonstrate a call missing after the client receives the streamed response.completed event.

    I ran a separate minimal reproduction using Node.js v24.15.0 and openai-node v7.17.0. This checks a narrower API-state question:

    1. Abort the stream at response.output_item.added.
    2. Retrieve the Response and verify that both the Response and function call are completed.
    3. Wait five seconds.
    4. Confirm that the associated Conversation still contains no items.
    5. Submit the function output and observe the missing-call 400.

    To be precise, the client does not receive the response.completed SSE event because the stream is intentionally interrupted. Instead, the completed state is observed afterward through responses.retrieve().

    Minimal reproduction

    Install the current SDK version:

    npm install [email protected]

    Save the following as repro.mjs and run it with OPENAI_API_KEY set:

    import OpenAI from "openai";
    
    const client = new OpenAI({ maxRetries: 0 });
    const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
    
    const tools = [
      {
        type: "function",
        name: "get_weather",
        description: "Get the current weather for a location",
        parameters: {
          type: "object",
          properties: { location: { type: "string" } },
          required: ["location"],
        },
      },
    ];
    
    const conversationResult = await client.conversations.create().withResponse();
    const conversationID = conversationResult.data.id;
    
    const streamResult = await client.responses
      .create({
        model: "gpt-4.1-mini",
        input: "What is the weather in Amsterdam?",
        conversation: conversationID,
        tools,
        tool_choice: "required",
        store: true,
        stream: true,
      })
      .withResponse();
    
    let responseID;
    let callID;
    
    for await (const event of streamResult.data) {
      if (event.type === "response.created") {
        responseID = event.response.id;
      }
    
      if (
        event.type === "response.output_item.added" &&
        event.item.type === "function_call"
      ) {
        callID = event.item.call_id;
        break; // Early break aborts the underlying request.
      }
    }
    
    if (!responseID || !callID) {
      throw new Error("Missing Response or call ID");
    }
    
    const retrieveResult = await client.responses
      .retrieve(responseID)
      .withResponse();
    
    const retrieved = retrieveResult.data;
    const completedCall = retrieved.output.find(
      (item) =>
        item.type === "function_call" &&
        item.call_id === callID &&
        item.status === "completed",
    );
    
    if (retrieved.status !== "completed" || !completedCall) {
      throw new Error("The retrieved Response or function call was not completed");
    }
    
    await sleep(5000);
    
    const itemsResult = await client.conversations.items
      .list(conversationID, { order: "asc", limit: 100 })
      .withResponse();
    
    let outputError;
    
    try {
      await client.responses.create({
        model: "gpt-4.1-mini",
        input: [
          {
            type: "function_call_output",
            call_id: callID,
            output: JSON.stringify({ temp: 18, condition: "cloudy" }),
          },
        ],
        conversation: conversationID,
        tools,
        store: true,
      });
    } catch (error) {
      outputError = {
        status: error.status,
        requestID: error.requestID,
        message: error.message,
      };
    }
    
    console.log({
      response: {
        id: retrieved.id,
        status: retrieved.status,
        completed_at: retrieved.completed_at,
        conversation: retrieved.conversation,
        functionCall: completedCall,
      },
      conversationItemsAfterFiveSeconds: itemsResult.data.data,
      outputError,
      requestIDs: {
        stream: streamResult.request_id,
        retrieveCompletedResponse: retrieveResult.request_id,
        listConversationItems: itemsResult.request_id,
        submitFunctionOutput: outputError?.requestID,
      },
    });

    Result

    The issue reproduced on 2026-09-17 at approximately 07:35:16 UTC.

    The retrieved Response contained:

    {
      "status": "completed",
      "completed_at": 1789630510,
      "conversation": {
        "id": "conv_6aab982ca4608193b3825b1b9e7819750911efe8eb692313"
      },
      "functionCall": {
        "type": "function_call",
        "status": "completed",
        "arguments": "{\"location\":\"Amsterdam\"}",
        "call_id": "call_yOrOVwdXgqZwiXk01VXxtXAV",
        "name": "get_weather"
      }
    }

    After waiting five seconds, the Conversation-items result was still:

    []

    Submitting the function output then returned:

    400 No tool call found for function call output with call_id call_yOrOVwdXgqZwiXk01VXxtXAV.
    

    Relevant request IDs:

    • Interrupted stream: req_b3f098a3a1f8425cb21fc527686a8de2
    • Completed Response retrieval: req_5c15731eb6bf4a72a5d9c6ab34843404
    • Conversation-items request after five seconds: bc9eeea7-88a8-4c37-9563-34747709b94f
    • Rejected function output: req_17ca6dfdac8c4b0394b26bc36af0ddc8

    Another python repro script with it's full diagnostic evidence has also been supplied privately under OpenAI Support case 14838625.

    The Response retrieval reference describes the retrieved Response as belonging to the Conversation and states that its input and output items were automatically added to that Conversation.

    Could you clarify whether retrieving a Response with status: "completed" is expected to imply successful Conversation finalization?

    If it is, would this retrieved-completed case warrant the separate API-level investigation you mentioned?
    If it is not, applications currently do not appear to have an exposed state that distinguishes “response generation completed” from “Conversation commit completed.”

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions