Skip to content

Feature request: onToolResult callback in useChat #6080

@ericqqqqq

Description

@ericqqqqq

Description

The current useChat hook supports onToolCall, which triggers when a tool starts running. However, there's no built-in way to detect when a tool finishes and returns a result.

Right now, to detect a finished tool result, I have to hack around it like this:

const seenToolIds = useRef<Set<string>>(new Set());

useEffect(() => {
  if (!messages || messages.length === 0) return;

  const lastMessage = messages[messages.length - 1];
  if (messages.length <= initialMessages.length) return;
  if (!lastMessage.parts) return;

  lastMessage.parts.forEach((part: any) => {
    if (
      part.type === 'tool-invocation' &&
      part.toolInvocation &&
      part.toolInvocation.toolCallId &&
      part.toolInvocation.state === 'result' &&
      !seenToolIds.current.has(part.toolInvocation.toolCallId)
    ) {
      seenToolIds.current.add(part.toolInvocation.toolCallId);
      handleToolResult(part.toolInvocation);
    }
  });
}, [messages, initialMessages]);

This workaround works but is clunky and fragile. I'd love a native onToolResult callback that fires once when a tool call completes, just like onToolCall does when it starts.

Metadata

Metadata

Assignees

No one assigned

    Labels

    ai/corecore functions like generateText, streamText, etc. Provider utils, and provider spec.ai/uianything UI relatedfeatureNew feature or request

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions