Skip to content

[Bug] openai-agents and vercel-ai-sdk (TypeScript): a cancelled model Activity doesn't stop the model call #503

Open

Description

@campoy

What are you really trying to do?

I want a cancelled agent Workflow to stop its model call, so nobody waits for (or pays for) an answer the Workflow already gave up on. I set a heartbeatTimeout on the model Activity, so the cancel reaches the Worker.

Describe the bug

The cancel reaches the Activity, but the model call keeps running to the end.

In openai-agents, invokeModelActivity and invokeModelStreamActivity never read the Activity's cancellationSignal. The ModelRequest they build has no signal, so getResponse and getStreamedResponse can't stop. That's the field @openai/agents-openai passes to the OpenAI client to abort the request.

vercel-ai-sdk has the same gap. invokeModel, invokeModelStreaming and invokeEmbeddingModel call doGenerate, doStream and doEmbed with no abortSignal. The README says that without a heartbeatTimeout a cancellation request doesn't reach the Activity. With one, it does, but nothing passes it on to the provider. In my run the cancelled Workflow even completed with the model's answer: the Activity finished normally, and with WAIT_CANCELLATION_COMPLETED the Workflow got its result.

The TypeScript google-adk and strands-agents plugins already do this. google-adk passes the signal to generateContentAsync, and strands-agents passes it as cancelSignal.

The fix is to pass Context.current().cancellationSignal to the model call: as signal on the ModelRequest in openai-agents, and as abortSignal in vercel-ai-sdk. I tried both in a local copy. The model call then stops at 1.7 s (openai-agents) and 1.1 s (vercel-ai-sdk), and both Workflows end cancelled right away. In openai-agents the catch also has to let the cancellation through. toModelInvocationFailure wraps the abort, so the Activity failed with a retryable ModelInvocationError instead of being cancelled. google-adk's rethrowIfCancelled handles the same case.

For vercel-ai-sdk, #470 already passes the signal in all three Activities, so that part is fixed once it merges. #491 makes heartbeats deliver the cancel with the default settings; this issue is about making the cancel stop the call once it arrives. #465 added the heartbeats in vercel-ai-sdk.

I couldn't find a reason to leave the signal out in openai-agents. Did I miss one?

How did you hit this issue?

I looked at activity timeouts and heartbeats across all the plugins for #491. Then I checked what each model Activity does with a cancel once a heartbeat delivers it. These two drop it.

Minimal Reproduction

One file per plugin, on main, with a fake model and no credentials. The fake model call takes 6 s unless its abort signal fires. The Workflow makes one model call with a 2 s heartbeatTimeout and WAIT_CANCELLATION_COMPLETED, and the client cancels the Workflow after 1 s. (Both scripts use the non-streamed call. The streamed one builds the same request.)

From typescript/openai-agents, after pnpm install && pnpm run build:

pnpm exec tsx repro-openai-agents.ts

Output, with the Worker logs left out:

0.1s model call started, request.signal is undefined
1.0s cancelling the Workflow
1.7s Activity cancellationSignal aborted
6.1s model call ran to the end
6.1s Workflow failed: CancelledFailure

The Activity hears the cancel at 1.7 s, but the model call runs for the whole 6 s, and the Workflow waits for it.

repro-openai-agents.ts
// Run from typescript/openai-agents after `pnpm install && pnpm run build`:
//   pnpm exec tsx repro-openai-agents.ts
import { Agent, type ModelRequest } from '@openai/agents-core';
import { ActivityCancellationType } from '@temporalio/workflow';
import { TemporalOpenAIRunner } from '@temporalio/openai-agents/workflow';
// Worker side only: left out of the Workflow bundle below.
import { Context } from '@temporalio/activity';
import { TestWorkflowEnvironment } from '@temporalio/testing';
import { Worker } from '@temporalio/worker';
import { OpenAIAgentsPlugin } from '@temporalio/openai-agents';

export async function cancelModelCall(): Promise<string> {
  const runner = new TemporalOpenAIRunner({
    defaultModelParams: {
      heartbeatTimeout: '2s',
      cancellationType: ActivityCancellationType.WAIT_CANCELLATION_COMPLETED,
    },
  });
  const agent = new Agent({ name: 'Assistant', instructions: 'Say hi.', model: 'slow-model' });
  const result = await runner.run(agent, 'Hi');
  return String(result.finalOutput);
}

let start = 0;
const log = (msg: string) => console.log(`${((Date.now() - start) / 1000).toFixed(1)}s ${msg}`);

// A model call that takes 6 s, unless the request's abort signal fires first.
const slowModel = {
  async getResponse(request: ModelRequest) {
    Context.current().cancellationSignal.addEventListener('abort', () => log('Activity cancellationSignal aborted'));
    log(`model call started, request.signal is ${request.signal ? 'set' : 'undefined'}`);
    await new Promise<void>((resolve, reject) => {
      const timer = setTimeout(resolve, 6000);
      request.signal?.addEventListener('abort', () => {
        clearTimeout(timer);
        log('model call aborted');
        reject(request.signal!.reason);
      });
    });
    log('model call ran to the end');
    return {
      output: [{ type: 'message', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text: 'hi' }] }],
      usage: { requests: 1, inputTokens: 1, outputTokens: 1, totalTokens: 2 },
    };
  },
  async *getStreamedResponse(): AsyncIterable<never> {},
};

async function main() {
  const env = await TestWorkflowEnvironment.createLocal();
  try {
    const worker = await Worker.create({
      connection: env.nativeConnection,
      taskQueue: 'repro',
      workflowsPath: __filename,
      bundlerOptions: {
        ignoreModules: ['@temporalio/activity', '@temporalio/testing', '@temporalio/worker', '@temporalio/openai-agents$'],
      },
      plugins: [new OpenAIAgentsPlugin({ modelProvider: { getModel: () => slowModel as any } })],
    });
    await worker.runUntil(async () => {
      start = Date.now();
      const handle = await env.client.workflow.start(cancelModelCall, { taskQueue: 'repro', workflowId: 'repro' });
      await new Promise((resolve) => setTimeout(resolve, 1000));
      log('cancelling the Workflow');
      await handle.cancel();
      await handle.result().then(
        (output) => log(`Workflow completed: ${output}`),
        (err) => log(`Workflow failed: ${err.cause?.name ?? err.name}`)
      );
    });
  } finally {
    await env.teardown();
  }
}

if (require.main === module) {
  main().catch((err) => {
    console.error(err);
    process.exit(1);
  });
}

The same check for vercel-ai-sdk, from typescript/vercel-ai-sdk, with pnpm exec tsx repro-vercel-ai-sdk.ts:

0.1s model call started, abortSignal is undefined
1.0s cancelling the Workflow
1.1s Activity cancellationSignal aborted
6.1s model call ran to the end
6.1s Workflow completed: hi
repro-vercel-ai-sdk.ts
// Run from typescript/vercel-ai-sdk after `pnpm install && pnpm run build`:
//   pnpm exec tsx repro-vercel-ai-sdk.ts
import type { LanguageModelV4CallOptions, ProviderV4 } from '@ai-sdk/provider';
import { generateText } from 'ai';
import { ActivityCancellationType } from '@temporalio/workflow';
import { TemporalProvider } from '@temporalio/vercel-ai-sdk/workflow';
// Worker side only: left out of the Workflow bundle below.
import { Context } from '@temporalio/activity';
import { TestWorkflowEnvironment } from '@temporalio/testing';
import { Worker } from '@temporalio/worker';
import { AiSdkPlugin } from '@temporalio/vercel-ai-sdk';

export async function cancelModelCall(): Promise<string> {
  const provider = new TemporalProvider({
    languageModel: {
      startToCloseTimeout: '30s',
      heartbeatTimeout: '2s',
      cancellationType: ActivityCancellationType.WAIT_CANCELLATION_COMPLETED,
    },
  });
  const result = await generateText({ model: provider.languageModel('slow-model'), prompt: 'Say hi.' });
  return result.text;
}

let start = 0;
const log = (msg: string) => console.log(`${((Date.now() - start) / 1000).toFixed(1)}s ${msg}`);

// A model call that takes 6 s, unless its abort signal fires first.
const slowModel = {
  specificationVersion: 'v4',
  provider: 'fake',
  modelId: 'slow-model',
  supportedUrls: {},
  async doGenerate(options: LanguageModelV4CallOptions) {
    Context.current().cancellationSignal.addEventListener('abort', () => log('Activity cancellationSignal aborted'));
    log(`model call started, abortSignal is ${options.abortSignal ? 'set' : 'undefined'}`);
    await new Promise<void>((resolve, reject) => {
      const timer = setTimeout(resolve, 6000);
      options.abortSignal?.addEventListener('abort', () => {
        clearTimeout(timer);
        log('model call aborted');
        reject(options.abortSignal!.reason);
      });
    });
    log('model call ran to the end');
    return {
      content: [{ type: 'text', text: 'hi' }],
      finishReason: { unified: 'stop', raw: undefined },
      usage: {
        inputTokens: { total: 1, noCache: 1, cacheRead: 0, cacheWrite: 0 },
        outputTokens: { total: 1, text: 1, reasoning: 0 },
      },
      warnings: [],
    };
  },
  async doStream(): Promise<never> {
    throw new Error('unused');
  },
};

const modelProvider = {
  specificationVersion: 'v4',
  languageModel: () => slowModel,
  embeddingModel: () => {
    throw new Error('unused');
  },
  imageModel: () => {
    throw new Error('unused');
  },
} as unknown as ProviderV4;

async function main() {
  const env = await TestWorkflowEnvironment.createLocal();
  try {
    const worker = await Worker.create({
      connection: env.nativeConnection,
      taskQueue: 'repro',
      workflowsPath: __filename,
      bundlerOptions: {
        ignoreModules: ['@temporalio/activity', '@temporalio/testing', '@temporalio/worker', '@temporalio/vercel-ai-sdk$'],
      },
      plugins: [new AiSdkPlugin({ modelProvider })],
    });
    await worker.runUntil(async () => {
      start = Date.now();
      const handle = await env.client.workflow.start(cancelModelCall, { taskQueue: 'repro', workflowId: 'repro' });
      await new Promise((resolve) => setTimeout(resolve, 1000));
      log('cancelling the Workflow');
      await handle.cancel();
      await handle.result().then(
        (output) => log(`Workflow completed: ${output}`),
        (err) => log(`Workflow failed: ${err.cause?.name ?? err.name}`)
      );
    });
  } finally {
    await env.teardown();
  }
}

if (require.main === module) {
  main().catch((err) => {
    console.error(err);
    process.exit(1);
  });
}

Environment/Versions

  • ai-integrations main as of 2026-11-12
  • @openai/agents-core and @openai/agents-openai 0.14.3
  • ai 7.0.127, @ai-sdk/provider 4.0.21
  • @temporalio/* 1.24.0
  • Node 24.22.0 on Linux (Docker), Temporal CLI 1.10.0 dev server (Server 1.32.2)

Activity

  1. added
    bug
    on Nov 13, 2026
  2. rahulsjha commented on Nov 17, 2026

    @rahulsjha

    Hi @campoy, I'd like to pick this up. Plan: vercel-ai-sdk already passes Context.current().cancellationSignal as abortSignal, so the remaining work is typescript/openai-agents/src/worker/activities.ts, where invokeModelActivity and invokeModelStreamActivity build the ModelRequest without a signal; I'd set signal: Context.current().cancellationSignal on it. Edge cases: the stream loop should stop publishing once aborted, and the abort should surface as a cancellation rather than a retryable failure. Tests would use a fake model that waits on request.signal and assert that cancelling the Activity aborts both getResponse and getStreamedResponse. Could you assign it to me?

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