Assistants API active run cannot be cancelled via NodeJS

I have assistants API in my app and I use createAndStream

          const run = openai.beta.threads.runs
            .createAndStream(threadId, {
              assistant_id: assistant_id,
            })

All works perfectly until I try to cancel it via:

  try {
    await openai.beta.threads.runs.cancel(thread_id, run_id);
    socket.emit("chatAborted", {
      threadId: thread_id,
      runId: run_id,
      status: "Aborted successfully",
    });
  } catch (error) {
    console.error("Error aborting chat:", error);
    socket.emit("error", "Failed to abort chat.");
  }
});

It returns the error:

Error aborting chat: BadRequestError: 400 Cannot cancel run with status 'cancelling'.
    at APIError.generate (/home/runner/ChatNodeServer/node_modules/openai/error.js:44:20)
    at OpenAI.makeStatusError (/home/runner/ChatNodeServer/node_modules/openai/core.js:263:33)
    at OpenAI.makeRequest (/home/runner/ChatNodeServer/node_modules/openai/core.js:306:30)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Socket.<anonymous> (/home/runner/ChatNodeServer/socketLogic.js:147:9) {
  status: 400,
  headers: {
    'alt-svc': 'h3=":443"; ma=86400',
    'cf-cache-status': 'DYNAMIC',
    'cf-ray': '87360bd918078140-ORD',
    connection: 'keep-alive',
    'content-length': '155',
    'content-type': 'application/json',
    date: 'Fri, 12 Apr 2024 20:43:02 GMT',
    'openai-organization': 'abc,
    'openai-processing-ms': '21',
    'openai-version': '2020-10-01',
    server: 'cloudflare',
    'set-cookie': '__cf_bm=asdadad.uKOV_TYc-1712954582-1.0.1.1-asdad; path=/; expires=Fri, 12-Apr-24 21:13:02 GMT; domain=.api.openai.com; HttpOnly; Secure; SameSite=None, _cfuvid=I.0XS6UXhSDFihj9duGTRlf4T6999lEcE_WE1W73EraU-179854582067-0.0.1.1-604800000; path=/; domain=.api.openai.com; HttpOnly; Secure; SameSite=None',
    'strict-transport-security': 'max-age=15724800; includeSubDomains',
    'x-request-id': 'req_08c4fbcc022b58ebce249------'
  },
  error: {
    message: "Cannot cancel run with status 'cancelling'.",
    type: 'invalid_request_error',
    param: null,
    code: null
  },
  code: null,
  param: null,
  type: 'invalid_request_error'
}

I guess the error is not about me because I provide the run id and thread id as requested. Anyone knows what is wrong and how to fix?

1 Like