ai icon indicating copy to clipboard operation
ai copied to clipboard

onFinish callback for streamText is missing tool information

Open matthiasmoke opened this issue 1 year ago • 9 comments

Description

For calls of streamText, the onFinish callback context does not contain information on tool calls and results, even though tool steps were executed. In my example, I connected the Linear MCP server and tried to fetch my issues. The tool is executed and the LLM responds with the results in the second step. The onStepFinish callback is executed as well and contains information on the tool call. The finish callback is only contains information on which steps were executed, but the dedicated properties for tool calls and results are empty.

My use case is to save the tool results to the database. Using the onStepFinish callback is a workaround, but it results in way more database queries and complicates logic, which I'd like to avoid.

Below is a snippet of my route implementation as well as the value of the context.

Context (with omitted request and response properties)

{
  "finishReason": "stop",
  "totalUsage": {
    "inputTokens": 7813,
    "outputTokens": 595,
    "totalTokens": 8408,
    "reasoningTokens": 0,
    "cachedInputTokens": 0
  },
  "usage": {
    "inputTokens": 5734,
    "outputTokens": 572,
    "totalTokens": 6306,
    "reasoningTokens": 0,
    "cachedInputTokens": 0
  },
  "content": [
    {
      "type": "text",
      "text": "Here are your 5 latest Linear issues: ... (omitted for brevity)"
    }
  ],
  "text": "Here are your 5 latest Linear issues: ... (omitted for brevity)",
  "reasoning": [],
  "files": [],
  "sources": [],
  "toolCalls": [],
  "staticToolCalls": [],
  "dynamicToolCalls": [],
  "toolResults": [],
  "staticToolResults": [],
  "dynamicToolResults": [],
  "warnings": [],
  "providerMetadata": {
    "openai": {
      "acceptedPredictionTokens": 0,
      "rejectedPredictionTokens": 0
    }
  },
  "steps": [
    {
      "content": [
        {
          "type": "tool-call",
          "toolCallId": "call_bQ9ImRPvwXQZIIB1XARkfgZ8",
          "toolName": "list_my_issues",
          "input": {
            "limit": 5,
            "orderBy": "updatedAt"
          },
          "dynamic": true
        },
        {
          "type": "tool-result",
          "toolCallId": "call_bQ9ImRPvwXQZIIB1XARkfgZ8",
          "toolName": "list_my_issues",
          "input": {
            "limit": 5,
            "orderBy": "updatedAt"
          },
          "dynamic": true,
          "output": {
            "content": [
              {
                "type": "text",
                "text": ""
              }
            ],
            "isError": false
          }
        }
      ],
      "finishReason": "tool-calls",
      "usage": {
        "inputTokens": 2079,
        "outputTokens": 23,
        "totalTokens": 2102,
        "reasoningTokens": 0,
        "cachedInputTokens": 0
      },
      "warnings": [],
      "providerMetadata": {
        "openai": {
          "acceptedPredictionTokens": 0,
          "rejectedPredictionTokens": 0
        }
      }
    },
    {
      "content": [
        {
          "type": "text",
          "text": "Here are your 5 latest Linear issues: ..."
        }
      ],
      "finishReason": "stop",
      "usage": {
        "inputTokens": 5734,
        "outputTokens": 572,
        "totalTokens": 6306,
        "reasoningTokens": 0,
        "cachedInputTokens": 0
      },
      "warnings": [],
      "providerMetadata": {
        "openai": {
          "acceptedPredictionTokens": 0,
          "rejectedPredictionTokens": 0
        }
      }
    }
  ]
}

route.ts snippet:

  return createUIMessageStreamResponse({
    stream: createUIMessageStream({
      execute: async ({
        writer
      }: {
        writer: UIMessageStreamWriter<ChatMessage>
      }) => {
        const processedMessagesWithApproval = await processToolCalls(
          {
            messages: processedMessages,
            writer,
            tools
          },
          executeFunctions
        )
        const result = streamText({
          model,
          messages: convertToModelMessages(processedMessagesWithApproval),
          system: prompt,
          topP: assistant.topP,
          temperature: assistant.temperature,
          maxOutputTokens: assistant.maxTokens || undefined,
          stopWhen: stepCountIs(10),
          tools: {
            ...tools,
            ...(hasCanvasEnabled
              ? {
                  createDocument: createDocument({
                    writer,
                    model,
                    chatId: id,
                    messages: processedMessagesWithApproval,
                    assistant
                  }),
                  updateDocument: updateDocument({
                    writer,
                    model,
                    chatId: id,
                    messages: processedMessagesWithApproval,
                    assistant
                  })
                }
              : {}),
            ...(hasWebSearchEnabled
              ? {
                  searchWeb: getSearchWebTool(writer)
                }
              : {})
          },
          toolChoice: 'auto',
          experimental_transform: smoothStream({ chunking: 'word' }),
          onFinish: async context =>
            finishHandler(
              context,
              numberOfPages,
              id,
              userId,
              title,
              assistant,
              processedMessagesWithApproval,
              clients
            )
        })
        result.consumeStream()
        return writer.merge(result.toUIMessageStream({ sendReasoning: true }))
      },
      onError: (error: any) =>
        errorHandler({
          error,
          mcpClients: clients,
          userId,
          chatId: id,
          title,
          locale
        })
    })
  })

AI SDK Version

"ai": "5.0.40", "@ai-sdk/azure": "^2.0.28", "@ai-sdk/deepseek": "^1.0.8", "@ai-sdk/google": "^2.0.6", "@ai-sdk/google-vertex": "^3.0.9", "@ai-sdk/mistral": "^2.0.5", "@ai-sdk/openai": "^2.0.28", "@ai-sdk/react": "^2.0.40"

Code of Conduct

  • [x] I agree to follow this project's Code of Conduct

matthiasmoke avatar Sep 11 '25 09:09 matthiasmoke

@gr2m we're also seeing missing toolCalls on streamText for 5.0.81 with sonnet 4.5, sonnet 4, and gpt-4-1 on all providers (anthropic, vertex, bedrock)

nikitatome avatar Oct 27 '25 17:10 nikitatome

For what it's worth. Claude found a simple workaround for this.

const steps = await streamResult.steps;
const allToolCalls = steps.flatMap((step) => step.toolCalls);

Here's the full explanation for context, and hopefully to aid in fixing this issue:

I found it. Look at line 5999-6000:

if (part.type === "start-step") {
  recordedContent = [];  // <-- Content is RESET for each step!

And then look at how toolCalls is resolved (line 6792-6793):

get toolCalls() {
  return this.finalStep.then((step) => step.toolCalls);
}

The issue: toolCalls returns finalStep.toolCalls - the tool calls from the LAST step only.

Looking at your messages data, there are 3 steps:

  1. Step 1: Assistant with reasoning + text + tool-call
  2. Step 2: Tool role with tool-result
  3. Step 3: Assistant with final text

The finalStep is Step 3 - which has no tool calls, just the final text response. The tool calls are in Step 1, but toolCalls only looks at the last step!

Let me verify by checking if there's a way to get all steps:

[1 tool called]

Root cause confirmed: streamResult.toolCalls returns finalStep.toolCalls - only the last step's tool calls, not all tool calls across the entire multi-step generation.

Your flow has 3 steps.

The SDK provides streamResult.steps to access all steps. The proper fix:

[2 tools called]

The fix uses streamResult.steps to get all steps, then extracts tool calls from each step with steps.flatMap((step) => step.toolCalls).

Summary of the issue:

  • The AI SDK's streamResult.toolCalls only returns tool calls from finalStep (the last step)
  • In multi-step tool execution, the tool calls happen in earlier steps, not the final one
  • The final step is just the text response after tool execution, which has no tool calls
  • Using streamResult.steps gives access to all steps, allowing you to collect tool calls from the entire conversation

shalomscott avatar Jan 18 '26 20:01 shalomscott

You should extract the information from the steps as described above.

lgrammel avatar Jan 19 '26 10:01 lgrammel

Identify issue type

{
  "evidence": [
    "Reporter states `streamText` `onFinish` context has empty `toolCalls` and `toolResults` even though tool steps executed and `onStepFinish` contains the tool call.",
    "Provided `onFinish` context shows tool-call and tool-result entries inside `steps`, while top-level `toolCalls`, `dynamicToolCalls`, `toolResults`, and related arrays are empty.",
    "Another user reports the same missing `toolCalls` behavior across AI SDK 5.0.81 and multiple providers/models.",
    "A later comment identifies that `toolCalls` resolves from the final step only, so multi-step tool calls from earlier steps are omitted from the top-level result."
  ],
  "rationale": "The issue reports a concrete incorrect/missing result in current `streamText` `onFinish` behavior for tool calls in multi-step generations. Although comments mention a workaround via `steps`, the primary report is about missing tool information from existing callback fields.",
  "type": "bug",
  "confidence": "high"
}

lgrammel avatar Jul 02 '26 09:07 lgrammel

Bug Reproduction

Bug could not be reproduced.

Target branch: main

  • The current checkout uses ai 7.0.26; the issue was reported against 5.0.40.
  • Created examples/ai-functions/src/reproduction/issue-8578-stream-text-on-finish-tool-information.ts with a dynamic tool call/result in the first step and a text-only final step.
  • The final step had zero tool calls and results, but onFinish.toolCalls and onFinish.toolResults each contained call-list-my-issues; the reported empty top-level arrays did not occur.

Relevant Documentation

  • https://ai-sdk.dev/docs/reference/ai-sdk-core/stream-text
  • https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling

Closed PR: cannot-reproduce investigation pull request

lgrammel avatar Jul 14 '26 12:07 lgrammel

Bug Reproduction

Bug was reproduced.

Branch: release-v5.0 PR: successful reproduction pull request

Details

  • Added runnable reproduction at examples/ai-functions/src/reproduction/issue-8578-stream-text-on-finish-tool-information.ts against AI SDK 5.0.212.
  • A two-step dynamic tool flow executed call-list-my-issues and produced its result in the first step, followed by a text-only final step.
  • onFinish.steps contained the tool call and result, while top-level toolCalls, dynamicToolCalls, toolResults, and dynamicToolResults were all empty.
  • The expected issue behavior was observed: the dedicated top-level onFinish fields omitted tool information executed during an earlier step.

Relevant Documentation

  • https://ai-sdk.dev/docs/reference/ai-sdk-core/stream-text
  • https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling

lgrammel avatar Jul 14 '26 13:07 lgrammel

Bug Reproduction

Bug was reproduced.

Branch: release-v6.0 PR: successful reproduction pull request

Details

  • Added runnable reproduction at examples/ai-functions/src/reproduction/issue-8578-stream-text-on-finish-tool-information.ts against AI SDK 6.0.225.
  • The two-step flow recorded call-list-my-issues and its result in onFinish.steps, followed by a text-only final step.
  • Top-level onFinish.toolCalls, dynamicToolCalls, toolResults, and dynamicToolResults were empty instead of exposing the completed tool information, reproducing the reported persistence-impacting behavior.

Relevant Documentation

  • https://ai-sdk.dev/docs/reference/ai-sdk-core/stream-text
  • https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling

lgrammel avatar Jul 14 '26 13:07 lgrammel

Please use const allToolCalls = steps.flatMap((step) => step.toolCalls); to get all tool calls. In AI SDK 7 the distinction is clearer.

lgrammel avatar Jul 14 '26 13:07 lgrammel

Bug Reproduction - AI SDK 6

Bug was reproduced.

Branch: release-v6.0 PR: successful reproduction pull request

Details

  • Updated examples/ai-functions/src/reproduction/issue-8578-stream-text-on-finish-tool-information.ts to verify the completed dynamic tool call and result are available through both onStepFinish and onFinish.steps.
  • Against AI SDK 6.0.261, the final text-only step completes successfully, but onFinish.toolCalls, dynamicToolCalls, toolResults, and dynamicToolResults all omit call-list-my-issues.
  • The expected behavior is for the top-level onFinish tool fields to expose completed tool information from all steps, allowing one callback to persist the results.

Relevant Documentation

  • https://v6.ai-sdk.dev/docs/reference/ai-sdk-core/stream-text
  • https://v6.ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling

ai-sdk-factory[bot] avatar Aug 20 '26 21:08 ai-sdk-factory[bot]