ai icon indicating copy to clipboard operation
ai copied to clipboard

AgentCallParameters type missing experimental_onToolCallStart/Finish callbacks that work at runtime

Open manupadev-taxxa opened this issue 7 months ago • 4 comments

Description

ToolLoopAgent.generate() accepts experimental_onToolCallStart and experimental_onToolCallFinish at runtime — they flow through the ...options rest spread into generateText(), which fully supports them. However, the AgentCallParameters TypeScript type doesn't include these properties, causing type errors.

This forces consumers to use as any on the generate() call to pass these documented callbacks.

Reproduction

import { ToolLoopAgent, stepCountIs, tool } from 'ai';
import { z } from 'zod';

const agent = new ToolLoopAgent({
  model: myModel,
  tools: {
    myTool: tool({
      description: 'A tool',
      parameters: z.object({ query: z.string() }),
      execute: async ({ query }) => `result for ${query}`,
    }),
  },
  stopWhen: stepCountIs(3),
});

// ❌ Type error: 'experimental_onToolCallStart' does not exist on type
const result = await agent.generate({
  prompt: 'Do something',
  experimental_onToolCallStart: ({ toolCall }) => {
    console.log(`Starting: ${toolCall.toolName}`);
  },
  experimental_onToolCallFinish: ({ toolCall }) => {
    console.log(`Finished: ${toolCall.toolName}`);
  },
});

// ✅ Works at runtime — callbacks fire correctly
// Workaround: `as any` on the options object
const result2 = await agent.generate({
  prompt: 'Do something',
  experimental_onToolCallStart: ({ toolCall }) => {
    console.log(`Starting: ${toolCall.toolName}`);
  },
  experimental_onToolCallFinish: ({ toolCall }) => {
    console.log(`Finished: ${toolCall.toolName}`);
  },
} as any);

Why it works at runtime

In the compiled source (dist/index.mjs), ToolLoopAgent.generate() destructures only abortSignal, timeout, and onStepFinish — everything else lands in ...options, which is spread into prepareCall() and then into generateText():

async generate({ abortSignal, timeout, onStepFinish, ...options }) {
    return generateText({
        ...await this.prepareCall(options),
        abortSignal,
        timeout,
        onStepFinish: this.mergeOnStepFinishCallbacks(onStepFinish)
    });
}

generateText() accepts experimental_onToolCallStart and experimental_onToolCallFinish in both its types and runtime.

Expected behavior

AgentCallParameters (or the generate() method signature) should include experimental_onToolCallStart and experimental_onToolCallFinish so they can be passed without type assertions.

Context

These callbacks are useful for emitting real-time per-tool activity events (e.g., showing "searching..." spinners in a UI as each tool starts and finishes). onStepFinish is not a substitute — it fires once per step after all tool calls complete, losing per-tool timing granularity.

AI SDK Version

  • ai: 6.0.154

manupadev-taxxa avatar Apr 09 '26 17:04 manupadev-taxxa

Confirmed still present in v6.0.158 (latest as of 2026-04-13).

Type gap (dist/index.d.ts, AgentCallParameters):

{
    abortSignal?: AbortSignal;
    timeout?: TimeoutConfiguration;
    onStepFinish?: ToolLoopAgentOnStepFinishCallback<TOOLS>;
}

No experimental_onToolCallStart / experimental_onToolCallFinish.

Runtime support (dist/index.mjs, ToolLoopAgent.generate):

async generate({ abortSignal, timeout, onStepFinish, ...options }) {
  return generateText({
    ...await this.prepareCall(options),
    abortSignal, timeout,
    onStepFinish: this.mergeOnStepFinishCallbacks(onStepFinish)
  });
}

options (including the experimental callbacks) flows through prepareCall into generateText, which destructures both at index.mjs line ~1426.

Scope note: ToolLoopAgent.stream() has the identical destructure pattern and forwards to streamText, which also accepts these callbacks. Since AgentStreamParameters = AgentCallParameters & { experimental_transform?: ... }, adding the two properties to AgentCallParameters fixes both generate() and stream() in one edit.

ZWhiteTrace avatar Apr 13 '26 00:04 ZWhiteTrace

:rocket: Published in:

Package Version
ai 7.0.6 github npm
@ai-sdk/angular 3.0.6 github npm
@ai-sdk/gateway 4.0.5 github npm
@ai-sdk/harness 1.0.8 github npm
@ai-sdk/harness-claude-code 1.0.8 github npm
@ai-sdk/harness-codex 1.0.8 github npm
@ai-sdk/harness-deepagents 1.0.7 github npm
@ai-sdk/harness-opencode 1.0.8 github npm
@ai-sdk/harness-pi 1.0.8 github npm
@ai-sdk/langchain 3.0.6 github npm
@ai-sdk/llamaindex 3.0.6 github npm
@ai-sdk/otel 1.0.6 github npm
@ai-sdk/policy-opa 1.0.6 github npm
@ai-sdk/react 4.0.7 github npm
@ai-sdk/rsc 3.0.6 github npm
@ai-sdk/sandbox-just-bash 1.0.8 github npm
@ai-sdk/sandbox-vercel 1.0.8 github npm
@ai-sdk/svelte 5.0.6 github npm
@ai-sdk/tui 1.0.6 github npm
@ai-sdk/vue 4.0.6 github npm
@ai-sdk/workflow 1.0.6 github npm
@ai-sdk/workflow-harness 1.0.8 github npm

github-actions[bot] avatar Jun 29 '26 19:06 github-actions[bot]

Identify issue type

Identified as Bug
Confidence: High

Rationale

This is a concrete type-definition defect: existing runtime-supported callbacks cannot be used through the typed agent API without an any assertion.

Evidence

  • ToolLoopAgent.generate() forwards the callbacks to generateText() and they fire correctly at runtime.
  • AgentCallParameters omits experimental_onToolCallStart and experimental_onToolCallFinish, causing TypeScript errors for supported options.
  • A follow-up confirms the mismatch in v6.0.158 and notes the same issue affects stream().

lgrammel avatar Jul 22 '26 11:07 lgrammel

There is a remaining runtime problem on [email protected]: the aliases now type-check, but neither fires through ToolLoopAgent.generate() or .stream(). The tool still executes. Passing the same aliases directly to generateText or streamText works.

The merged #16461 added the types. The runtime wiring in he-yufeng's #15588 is relevant, but that PR was closed without merging.

Current root cause: the agent always supplies onToolExecutionStart / onToolExecutionEnd from mergeCallbacks, even when no stable callbacks were provided. That creates a function which takes precedence over the legacy aliases in the underlying text APIs. The aliases passed through ...options are therefore ignored.

Minimal reproduction, no provider or credentials:

npm init -y
npm install --save-exact [email protected] [email protected]
# Save the following as repro.mts, then run: node repro.mts
import assert from 'node:assert/strict';
import { ToolLoopAgent, isStepCount, tool } from 'ai';
import { MockLanguageModelV4 } from 'ai/test';
import { z } from 'zod';

const events: string[] = [];
const agent = new ToolLoopAgent({
  model: new MockLanguageModelV4({
    doGenerate: {
      content: [{ type: 'tool-call', toolCallId: 'call-1', toolName: 'lookup', input: '{}' }],
      finishReason: { unified: 'tool-calls', raw: 'tool_calls' },
      usage: {
        inputTokens: { total: 1, noCache: 1, cacheRead: 0, cacheWrite: 0 },
        outputTokens: { total: 1, text: 1, reasoning: 0 },
      },
      warnings: [],
    },
  }),
  tools: {
    lookup: tool({
      inputSchema: z.object({}),
      execute: async () => { events.push('execute'); return 'ok'; },
    }),
  },
  stopWhen: isStepCount(1),
});

await agent.generate({
  prompt: 'Run the lookup.',
  experimental_onToolCallStart: () => { events.push('start'); },
  experimental_onToolCallFinish: () => { events.push('finish'); },
});
console.log(events);
assert.deepEqual(events, ['start', 'execute', 'finish']);

Actual: ['execute']. Expected: ['start', 'execute', 'finish']. The reproduction passes strict TypeScript checking.

I also tested both agent methods on Node 22.20.0 and 24.13.0, against the published package and current main:

  • Six regression cases fail: legacy callbacks for successful/failed tools, plus constructor callbacks combined with call-level aliases.
  • Eight controls pass: stable callbacks, stable-name precedence, no callbacks, and direct text API aliases.

A fix can extract the aliases in both methods, then merge the constructor callback with onToolExecutionStart ?? experimental_onToolCallStart (and the equivalent end callback). All 14 focused cases pass with that local change.

One detail worth retaining from the controls: adding the legacy alias as a third mergeCallbacks argument, as in #15588, invokes both names when both are supplied. Using the nullish fallback preserves the existing text API precedence. Reapplying the earlier wiring to current source passes 12/14 cases; the two precedence checks fail.

The current-source runs used a targeted bundle with published dependencies. Full repository tests and full type checking were not run for this follow-up. This is reproduction/review evidence and a local proposal, not a submitted implementation PR. I used AI assistance to prepare it.

brennanbutler01 avatar Sep 18 '26 11:09 brennanbutler01